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>wjq1994/Util<file_sep>/externals/常用库.md 1. [detect a browser vendor and version](https://github.com/DamonOehlman/detect-browser) 2. [vue-resize](https://github.com/Akryum/vue-resize#readme) <file_sep>/src/type.js export const emptyObject = Object.freeze({}) /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ export function isObject(obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value, e.g., [object Object]. */ const _toString = Object.prototype.toString; export function toRawType(value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ export function isPlainObject(obj) { return _toString.call(obj) === '[object Object]' } export function isRegExp(obj) { return _toString.call(obj) === '[object RegExp]' } /** * 是否能转换为Number * @param {string | number} obj */ export function isNumber(obj) { if(obj === null || obj === undefined || typeof obj === "boolean") { return false; } return !Number.isNaN(Number(obj)); }<file_sep>/readme.md ### 开发中常用的开发类库
792bc961f032368406d8a6013a77df684c25b6b9
[ "Markdown", "JavaScript" ]
3
Markdown
wjq1994/Util
93657c5300bf51d91c23cdb57eeb2a0ed33431ce
530f06f23e2fed2b8779e1b8e558cccacf702ab8
refs/heads/master
<repo_name>bridgecrew-perf5/terraform-provider-sqlite<file_sep>/sqlite/provider.go package sqlite import ( "context" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func Provider() *schema.Provider { return &schema.Provider{ Schema: map[string]*schema.Schema{ "path": { Type: schema.TypeString, Required: true, DefaultFunc: schema.EnvDefaultFunc("SQLITE_DB_PATH", nil), }, }, ResourcesMap: map[string]*schema.Resource{ "sqlite_table": resourceTable(), "sqlite_index": resourceIndex(), }, DataSourcesMap: map[string]*schema.Resource{}, ConfigureContextFunc: providerConfigure, ProviderMetaSchema: map[string]*schema.Schema{}, } } func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { var err error var diags diag.Diagnostics dbPath := d.Get("path").(string) if len(dbPath) < 1 { diags = append(diags, diag.Diagnostic{ Severity: diag.Error, Summary: "parameter 'path' can not be empty", }) return nil, diags } sqlW := NewSqLiteWrapper() err = sqlW.Open(dbPath) if err != nil { diags = append(diags, diag.Diagnostic{ Severity: diag.Error, Summary: fmt.Sprintf("error opening the database '%s'", dbPath), Detail: fmt.Sprint(err), }) return nil, diags } return sqlW, diags } <file_sep>/sqlite/templates_helpers.go package sqlite import ( "bytes" "fmt" "strconv" "strings" "text/template" ) // helper functions for templates func templateSub(a, b int) int { return a - b } func templateMkSlice(elems ...string) []string { return elems } func templateToString(i interface{}) string { switch v := i.(type) { case string: return v case bool: return strconv.FormatBool(v) case int: return strconv.Itoa(v) default: return "" } } var templateFuncMap = template.FuncMap{ "sub": templateSub, "strJoin": strings.Join, "mkSlice": templateMkSlice, "toStr": templateToString, "escapeSql": escapeSQLEntity, } func renderTemplate(t string, data interface{}) (string, error) { tmpl, err := template.New("").Funcs(templateFuncMap).Parse(t) if err != nil { return "", err } buf := &bytes.Buffer{} err = tmpl.Execute(buf, data) if err != nil { return "", err } return string(buf.Bytes()), nil } func escapeSQLEntity(s string) string { ns := s if strings.ContainsAny(ns, `" `) { ns = strings.Replace(s, "\"", "\"\"", -1) ns = fmt.Sprintf("\"%s\"", ns) } return ns } <file_sep>/sqlite/resource_index.go package sqlite import ( "context" "fmt" "log" "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceIndex() *schema.Resource { return &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "SQLite index name.", }, "table": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "SQLite table name to create index on.", }, "created": { Type: schema.TypeString, Computed: true, Optional: true, Description: "Index creation timestamp.", }, "columns": { Type: schema.TypeList, Optional: true, ForceNew: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "unique": { Type: schema.TypeBool, Optional: true, ForceNew: true, }, }, SchemaVersion: 0, CreateContext: resourceIndexCreate, ReadContext: resourceIndexRead, DeleteContext: resourceIndexDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, UseJSONNumber: false, } } func resourceIndexCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { var err error var index struct { Name string Table string Columns []string Unique bool } c := m.(*sqLiteWrapper) index.Name = d.Get("name").(string) index.Table = d.Get("table").(string) index.Unique = d.Get("unique").(bool) colsRaw := d.Get("columns").([]interface{}) index.Columns = make([]string, 0, len(colsRaw)) for _, v := range colsRaw { index.Columns = append(index.Columns, templateToString(v)) } query, err := renderTemplate(createIndexTemplate, index) if err != nil { return diag.FromErr(err) } log.Println(query) _, err = c.Exec(query) if err != nil { return diag.FromErr(err) } d.SetId(index.Name) if err := d.Set("created", time.Now().Format(time.RFC850)); err != nil { return diag.FromErr(err) } return diag.Diagnostics{} } func resourceIndexRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { var err error var indexName string type pragmaColumns struct { SeqNo int Cid int Name string } c := m.(*sqLiteWrapper) // SQL statements for getting table information // Resource Id in our case corresponds to table name schemaStmt := fmt.Sprintf("PRAGMA INDEX_INFO(%s);", d.Id()) indexStmt := fmt.Sprintf("SELECT name FROM sqlite_master WHERE type='index' AND name='%s';", d.Id()) log.Println(indexStmt) log.Println(schemaStmt) // check if table exists and get its name res, err := c.QueryRow(indexStmt) if err != nil { return diag.FromErr(fmt.Errorf("finding index: %w", err)) } // name will be empty if table does not exist err = res.Scan(&indexName) if err != nil || len(indexName) < 1 { d.SetId("") return diag.Diagnostics{ diag.Diagnostic{ Severity: diag.Warning, Summary: "index was not found in the database, re-creating...", Detail: fmt.Sprintf("%s", err), }, } } err = d.Set("name", indexName) if err != nil { diag.FromErr(fmt.Errorf("setting index name: %s", err)) } // make up a new list of columns with the same type as defined in schema columns := make([]interface{}, 0) // query for index schema // result will be empty if index does not exist rows, err := c.Query(schemaStmt) if err != nil { return diag.FromErr(err) } for rows.Next() { col := pragmaColumns{} err = rows.Scan(&col.SeqNo, &col.Cid, &col.Name) if err != nil { return diag.FromErr(fmt.Errorf("getting column info: %w", err)) } columns = append(columns, col.Name) } // write our columns values into the resource data if err := d.Set("columns", columns); err != nil { return diag.FromErr(fmt.Errorf("reading index columns: %w", err)) } return diag.Diagnostics{} } func resourceIndexDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*sqLiteWrapper) query := fmt.Sprintf("DROP INDEX %s;", d.Id()) log.Println(query) _, err := c.Exec(query) if err != nil { return diag.FromErr(err) } // set empty resource Id to mark it as destroyed // and make TF remove it from the state d.SetId("") return diag.Diagnostics{} } <file_sep>/go.mod module github.com/Burmuley/terraform-provider-sqlite go 1.16 require ( github.com/golang/snappy v0.0.1 // indirect github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect github.com/hashicorp/terraform-plugin-sdk/v2 v2.7.1 github.com/pierrec/lz4 v2.0.5+incompatible // indirect modernc.org/sqlite v1.12.0 ) <file_sep>/sqlite/resource_table.go package sqlite import ( "context" "fmt" "log" "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceTable() *schema.Resource { return &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "SQLite table name.", }, "created": { Type: schema.TypeString, Computed: true, Optional: true, Description: "Table creation timestamp.", }, "column": { Type: schema.TypeList, Required: true, ForceNew: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Column name.", }, "type": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Column data type.", ValidateFunc: validation.StringInSlice([]string{ "INTEGER", "TEXT", "BLOB", "REAL", "NUMERIC", }, false), }, "constraints": { Type: schema.TypeList, MaxItems: 1, Optional: true, ForceNew: true, Description: "The list of column constraints.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "primary_key": { Type: schema.TypeBool, Optional: true, ForceNew: true, Default: false, }, "not_null": { Type: schema.TypeBool, Optional: true, ForceNew: true, Default: false, }, "default": { Type: schema.TypeString, Optional: true, ForceNew: true, Default: nil, }, }, }, }, }, }, }, }, SchemaVersion: 0, CreateContext: resourceTableCreate, ReadContext: resourceTableRead, DeleteContext: resourceTableDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, UseJSONNumber: false, } } func resourceTableCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { var err error var table struct { Name string Created string Columns []map[string]interface{} } c := m.(*sqLiteWrapper) table.Name = d.Get("name").(string) table.Created = d.Get("created").(string) columns := d.Get("column").([]interface{}) table.Columns = make([]map[string]interface{}, 0, len(columns)) for _, column := range columns { colMap := column.(map[string]interface{}) var constrMaps []map[string]interface{} if constraints, ok := colMap["constraints"]; ok { for _, c := range constraints.([]interface{}) { constrMaps = append(constrMaps, c.(map[string]interface{})) } colMap["constraints"] = constrMaps } table.Columns = append(table.Columns, colMap) } query, err := renderTemplate(createTableTemplate, table) if err != nil { return diag.FromErr(err) } log.Println(query) _, err = c.Exec(query) if err != nil { return diag.FromErr(err) } d.SetId(table.Name) if err := d.Set("created", time.Now().Format(time.RFC850)); err != nil { return diag.FromErr(fmt.Errorf("set created: %w", err)) } return diag.Diagnostics{} } func resourceTableRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { // list of columns returned by `PRAGMA TABLE_INFO` query type pragmaColumns struct { Cid int Name string DataType string NotNull int DefaultValue interface{} PrimaryKey int } var err error var tableName string c := m.(*sqLiteWrapper) // SQL statements for getting table information // Resource Id in our case corresponds to table name SchemaStmt := fmt.Sprintf("PRAGMA TABLE_INFO(%s);", escapeSQLEntity(d.Id())) TableStmt := fmt.Sprintf("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';", d.Id()) log.Println(TableStmt) log.Println(SchemaStmt) // check if table exists and get its name res, err := c.QueryRow(TableStmt) if err != nil { return diag.FromErr(err) } // name will be empty if table does not exist err = res.Scan(&tableName) if err != nil || len(tableName) < 1 { d.SetId("") return diag.Diagnostics{ diag.Diagnostic{ Severity: diag.Warning, Summary: "table was not found in the database, re-creating...", Detail: fmt.Sprintf("%s", err), }, } } err = d.Set("name", tableName) if err != nil { diag.FromErr(fmt.Errorf("error setting table name: %s", err)) } // make up a new list of columns with the same type as defined in schema columns := make([]map[string]interface{}, 0) // query for table schema // result will be empty if table does not exist rows, err := c.Query(SchemaStmt) if err != nil { return diag.FromErr(err) } // iterate over result and retrieve columns configuration // see details: https://www.sqlite.org/pragma.html#pragma_table_info for rows.Next() { col := pragmaColumns{} constraints := make([]map[string]interface{}, 0) err = rows.Scan(&col.Cid, &col.Name, &col.DataType, &col.NotNull, &col.DefaultValue, &col.PrimaryKey) if err != nil { return diag.FromErr(err) } cConstr := make(map[string]interface{}, 0) if col.PrimaryKey > 0 { cConstr["primary_key"] = true } if col.NotNull > 0 { cConstr["not_null"] = true } if col.DefaultValue != nil { cConstr["default"] = col.DefaultValue } if len(cConstr) > 0 { constraints = append(constraints, cConstr) } dCol := map[string]interface{}{ "name": col.Name, "type": col.DataType, } dCol["constraints"] = constraints columns = append(columns, dCol) } // write our columns values into the resource data if err := d.Set("column", columns); err != nil { return diag.FromErr(fmt.Errorf("reading table columns: %w", err)) } return diag.Diagnostics{} } func resourceTableDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { c := m.(*sqLiteWrapper) query := fmt.Sprintf("DROP TABLE %s;", escapeSQLEntity(d.Id())) log.Println(query) _, err := c.Exec(query) if err != nil { return diag.FromErr(err) } // set empty resource Id to mark it as destroyed // and make TF remove it from the state d.SetId("") return diag.Diagnostics{} } <file_sep>/build.sh #!/usr/bin/env bash rm -f terraform-provider-sqlite go build -o terraform-provider-sqlite mkdir -p ~/.terraform.d/plugins/burmuley.com/edu/sqlite/0.1/darwin_amd64 mv terraform-provider-sqlite ~/.terraform.d/plugins/burmuley.com/edu/sqlite/0.1/darwin_amd64 <file_sep>/sqlite/templates_helpers_test.go package sqlite import "testing" func Test_escapeTableName(t *testing.T) { type args struct { s string } tests := []struct { name string args args want string }{ { name: "Name with space", args: args{s: "table name"}, want: `"table name"`, }, { name: "Name with double quotes", args: args{s: `table"name`}, want: `"table""name"`, }, { name: "Name with double quotes and space", args: args{s: `table"name two`}, want: `"table""name two"`, }, { name: "Name with no quotes and spaces", args: args{s: "table_name"}, want: "table_name", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := escapeSQLEntity(tt.args.s); got != tt.want { t.Errorf("escapeSQLEntity() = %v, want %v", got, tt.want) } }) } } <file_sep>/sqlite/sqlite.go package sqlite import ( "database/sql" "errors" "sync" _ "modernc.org/sqlite" ) type sqLiteWrapper struct { *sync.Mutex db *sql.DB dbPath string } func NewSqLiteWrapper() *sqLiteWrapper { s := &sqLiteWrapper{ Mutex: &sync.Mutex{}, } return s } func (s *sqLiteWrapper) Open(path string) error { var err error var db *sql.DB // if DB has been already opened - do nothing if path == s.dbPath && s.db != nil { return nil } db, err = sql.Open("sqlite", path) if err != nil { return err } s.db = db s.dbPath = path return nil } func (s *sqLiteWrapper) Query(query string, args ...interface{}) (*sql.Rows, error) { if s.db == nil { return nil, errors.New("database not initialized") } s.Lock() defer s.Unlock() return s.db.Query(query, args...) } func (s *sqLiteWrapper) QueryRow(query string, args ...interface{}) (*sql.Row, error) { if s.db == nil { return nil, errors.New("database not initialized") } s.Lock() defer s.Unlock() row := s.db.QueryRow(query, args...) return row, row.Err() } func (s *sqLiteWrapper) Exec(query string, args ...interface{}) (sql.Result, error) { if s.db == nil { return nil, errors.New("database not initialized") } s.Lock() defer s.Unlock() return s.db.Exec(query, args...) } func (s *sqLiteWrapper) Ping() error { return s.db.Ping() } <file_sep>/sqlite/templates_test.go package sqlite import ( "bytes" "fmt" "testing" "text/template" "time" ) func Test_createTableTemplate(t *testing.T) { // not a real test // used to use it for SQL statements generation debugging var table struct { Name string Created string Overwrite bool Columns []map[string]interface{} } table.Name = "test_table" table.Created = time.Now().Format(time.RFC850) table.Overwrite = false table.Columns = make([]map[string]interface{}, 0, 2) table.Columns = append(table.Columns, map[string]interface{}{ "name": "tst_field1", "type": "INT", "constraints": []map[string]interface{}{ { "primary_key": interface{}(true), "not_null": interface{}(true), }, }, }) table.Columns = append(table.Columns, map[string]interface{}{ "name": "tst_field2", "type": "TEXT", "constraints": []map[string]interface{}{ { "not_null": interface{}(true), }, }, }) tmpl, err := template.New("create_table").Funcs(templateFuncMap).Parse(createTableTemplate) if err != nil { t.Error(err) } buf := &bytes.Buffer{} err = tmpl.Execute(buf, table) if err != nil { t.Error(err) } fmt.Println(string(buf.Bytes())) } <file_sep>/main.go package main import ( "github.com/Burmuley/terraform-provider-sqlite/sqlite" "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" ) func main() { plugin.Serve(&plugin.ServeOpts{ ProviderFunc: sqlite.Provider, }) } <file_sep>/sqlite/provider_test.go package sqlite import ( "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) var testSqliteProviders map[string]*schema.Provider var testSqliteProvider *schema.Provider func init() { testSqliteProvider = Provider() testSqliteProviders = map[string]*schema.Provider{ "sqlite": testSqliteProvider, } } func TestProvider(t *testing.T) { if err := Provider().InternalValidate(); err != nil { t.Fatalf("err: %s", err) } } func TestProvider_impl(t *testing.T) { var _ *schema.Provider = Provider() } <file_sep>/sqlite/templates.go package sqlite var createTableTemplate = ` CREATE TABLE {{ .Name | escapeSql }} ( {{- $lenColumns := sub (len .Columns) 1 -}} {{- range $i, $v := .Columns }} {{- $constr_str := "" -}} {{- range (index $v "constraints") }} {{- range $ck, $cv := . }} {{- if and (eq $ck "primary_key") (eq (toStr $cv) "true") }} {{- $constr_str = (strJoin (mkSlice "PRIMARY KEY" $constr_str) " ") }} {{- else if and (eq $ck "not_null") (eq (toStr $cv) "true") }} {{- $constr_str = (strJoin (mkSlice "NOT NULL" $constr_str) " ") }} {{- else if and (eq $ck "default") (gt (len (toStr $cv)) 0) }} {{- $constr_str = (strJoin (mkSlice "DEFAULT" $cv $constr_str) " ") }} {{ end -}} {{ end -}} {{ end }} {{ index $v "name" | escapeSql }} {{ index $v "type" }} {{ $constr_str -}}{{- if lt $i $lenColumns -}},{{- end -}} {{ end }} ); ` var createIndexTemplate = ` {{- $colsStr := "" -}} {{- if gt (len .Columns) 0 }} {{- $cols := strJoin .Columns "," -}} {{- $colsStr = strJoin (mkSlice " (" $cols ")") "" -}} {{- end -}} CREATE {{if eq (toStr .Unique) "true"}}UNIQUE {{end}}INDEX {{ .Name | escapeSql }} ON {{ .Table | escapeSql }}{{ $colsStr }}; ` <file_sep>/README.md # Terraform provider for SQLite database engine **!!! WARNING !!!**<br> This is an educational project. Not intended for any production use! <br>**!!! WARNING !!!** Here is my first implemetation of SQLite plugin (provider) for Terraform. There's no many docs and tests yet. The code is intended for local development and use for now. Plugin was tested on MacOS X, but should work on any other platform as well. Prequisites: * Go >= 1.16 * Terraform >= 1.0 Provider supports: * Creating database tables with basic constraints like `NOT NULL`, `PRIMARY KEY` and `DEFAULT` * Creating database basic indexes Provider **does not** support: * Table/index schema upgrades (in case of schema changes resources will be recreated) * Resources import Known issues: * If you delete/recreate table having any indexes on it, provider will not automatically recreate indexes; it will be recreated on the next run of `terraform apply` ## How to build 1. Clone repository and make Go download dependencies ```shell git clone https://github.com/Burmuley/terraform-provider-sqlite cd terraform-provider-sqlite go get ``` 2. Run script `build.sh` to build and install provider to the Terraform local cache, or run these commands to achieve the same ```shell go build -o terraform-provider-sqlite mkdir -p ~/.terraform.d/plugins/burmuley.com/edu/sqlite/0.1/darwin_amd64 mv terraform-provider-sqlite ~/.terraform.d/plugins/burmuley.com/edu/sqlite/0.1/darwin_amd64 ``` ## How to use And example code is located in the `example` directory. ```shell cd example terraform init ``` Then Terraform should find local provider and successfully initialize the local module. ```shell Initializing the backend... Initializing provider plugins... - Reusing previous version of burmuley.com/edu/sqlite from the dependency lock file - Installing burmuley.com/edu/sqlite v0.1.0... - Installed burmuley.com/edu/sqlite v0.1.0 (unauthenticated) Terraform has been successfully initialized! ``` Simply run the `apply` command and confirm you want to provision "the infrastructure". :) ```shell terraform apply ``` ```shell Terraform will perform the following actions: # sqlite_index.test_index1 will be created + resource "sqlite_index" "test_index1" { + columns = [ + "id", + "name", ] + created = (known after apply) + id = (known after apply) + name = "users_index" + table = "users" } # sqlite_table.test_table will be created + resource "sqlite_table" "test_table" { + created = (known after apply) + id = (known after apply) + name = "users" + column { + name = "id" + type = "INTEGER" + constraints { + not_null = true + primary_key = true } } + column { + name = "name" + type = "TEXT" + constraints { + not_null = true + primary_key = false } } + column { + name = "last_name" + type = "TEXT" + constraints { + not_null = true + primary_key = false } } + column { + name = "password" + type = "TEXT" + constraints { + default = "123" + not_null = true + primary_key = false } } } # sqlite_table.test_table2 will be created + resource "sqlite_table" "test_table2" { + created = (known after apply) + id = (known after apply) + name = "projects" + column { + name = "id" + type = "INTEGER" + constraints { + not_null = true + primary_key = true } } + column { + name = "user" + type = "INTEGER" + constraints { + not_null = true + primary_key = false } } + column { + name = "name" + type = "TEXT" + constraints { + not_null = true + primary_key = false } } } Plan: 3 to add, 0 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes sqlite_table.test_table2: Creating... sqlite_table.test_table: Creating... sqlite_table.test_table2: Creation complete after 0s [id=projects] sqlite_table.test_table: Creation complete after 0s [id=users] sqlite_index.test_index1: Creating... sqlite_index.test_index1: Creation complete after 0s [id=users_index] Apply complete! Resources: 3 added, 0 changed, 0 destroyed. ```
a47a15c7e18bbb65b914989149b1cf150c27cea1
[ "Markdown", "Go Module", "Go", "Shell" ]
13
Go
bridgecrew-perf5/terraform-provider-sqlite
6813e094a55723cada81703b3a05f2f5ee465aa4
a1e3449b8a98316b1cf6cae899ce5fd6dc5653df
refs/heads/master
<file_sep>#include "rotatingcamera.h" #include "glhelper.h" #include <QMatrix4x4> #include <cmath> #define M_PI 3.14159265358979323846 const qreal CAMERA_ROTATION_SENSIVITY = 0.03; const qreal CAMERA_ZOOM_SENSIVITY = 0.005; RotatingCamera::RotatingCamera(QSize viewport, QObject *parent) : QObject(parent) , m_viewport(viewport) { } void RotatingCamera::loadMatrix() const { QMatrix4x4 matrix; matrix.lookAt(m_eye, m_eye + m_front, m_up); GLHelper::setModelViewMatrix(matrix); } void RotatingCamera::lookAt(const QVector3D &eye, const QVector3D &at, const QVector3D &up) { m_eye = eye; m_front = at - eye; m_up = up; m_front.normalize(); m_at = at; m_radius = sqrt(m_eye.x()*m_eye.x() + m_eye.y()*m_eye.y() + m_eye.z()*m_eye.z()); } void RotatingCamera::advance(int64_t msec) { QVector3D left = QVector3D::crossProduct(m_up, m_front); float seconds = float(msec) * 0.001f; float dFront = m_speed.x() * seconds; float dLeft = m_speed.y() * seconds; float dUp = m_speed.z() * seconds; m_eye += m_front * dFront; m_eye += left * dLeft; m_eye += m_up * dUp; } QSize RotatingCamera::viewport() const { return m_viewport; } void RotatingCamera::setViewport(QSize viewport) { m_viewport = viewport; } QVector3D RotatingCamera::eye() const { return m_eye; } void RotatingCamera::rotateZ(qreal dl) { qreal a = dl / sqrt(m_eye.x()*m_eye.x() + m_eye.y()*m_eye.y()); qreal newEyePointX, newEyePointY; newEyePointX = cos(a)*m_eye.x() - sin(a)*m_eye.y(); newEyePointY = sin(a)*m_eye.x() + cos(a)*m_eye.y(); m_eye.setX(newEyePointX); m_eye.setY(newEyePointY); lookAt(m_eye, m_at, m_up); } void RotatingCamera::rotateViewAngle(qreal dl) { qreal a = dl / m_radius; qreal currentAngle = asin(m_eye.z() / m_radius); a = (a + currentAngle > M_PI/2) ? M_PI/2 - currentAngle : (a + currentAngle < 0) ? 0 - currentAngle : a; qreal r1 = sqrt(m_eye.x()*m_eye.x() + m_eye.y()*m_eye.y()); qreal newEyePointZ = sin(a)*r1 + cos(a)*m_eye.z(); qreal r2 = cos(a)*r1 - sin(a)*m_eye.z(); qreal newEyePointX = r2 * m_eye.x() / r1; qreal newEyePointY = r2 * m_eye.y() / r1; m_eye.setX(newEyePointX); m_eye.setY(newEyePointY); m_eye.setZ(newEyePointZ); lookAt(m_eye, m_at, m_up); } void RotatingCamera::modifyRadius(qreal dr) { qreal newRadius = m_radius + dr; newRadius = (newRadius > 16) ? 16 : (newRadius < 3) ? 3 : newRadius; qreal newEyePointX, newEyePointY, newEyePointZ; newEyePointX = m_eye.x() * newRadius/m_radius; newEyePointY = m_eye.y() * newRadius/m_radius; newEyePointZ = m_eye.z() * newRadius/m_radius; m_radius = newRadius; m_eye.setX(newEyePointX); m_eye.setY(newEyePointY); m_eye.setZ(newEyePointZ); lookAt(m_eye, m_at, m_up); } void RotatingCamera::onKeyDown(QKeyEvent *) { } void RotatingCamera::onKeyUp(QKeyEvent *) { } void RotatingCamera::onMouseDown(QMouseEvent *ev) { m_prevMouseX = ev->x(); m_prevMouseY = ev->y(); } void RotatingCamera::onMouseMove(QMouseEvent *ev) { if (ev->buttons() & Qt::LeftButton) { int curX = ev->x(); int curY = ev->y(); int dx = curX - m_prevMouseX; int dy = curY - m_prevMouseY; m_prevMouseX = curX; m_prevMouseY = curY; rotateZ(dx * CAMERA_ROTATION_SENSIVITY); rotateViewAngle(-dy * CAMERA_ROTATION_SENSIVITY); } } void RotatingCamera::onWheelMove(QWheelEvent *ev) { int dr = ev->angleDelta().y(); modifyRadius(-dr * CAMERA_ZOOM_SENSIVITY); } <file_sep>#ifndef DIAGRAMWINDOW_H #define DIAGRAMWINDOW_H #include <QDialog> namespace Ui { class DiagramWindow; } class DiagramWindow : public QDialog { Q_OBJECT public: explicit DiagramWindow(QWidget *parent = 0); ~DiagramWindow(); private: Ui::DiagramWindow *ui; // QWidget interface protected: void paintEvent(QPaintEvent *); }; #endif // DIAGRAMWINDOW_H <file_sep>#pragma once #include <QVector3D> #include <QKeyEvent> #include <QMouseEvent> #include <QWheelEvent> class ISceneCamera { public: virtual void loadMatrix() const = 0; virtual void lookAt(QVector3D const& eye, QVector3D const& at, QVector3D const& up) = 0; virtual void advance(int64_t msec) = 0; virtual void setViewport(QSize size) = 0; virtual QSize viewport() const = 0; virtual QVector3D eye() const = 0; virtual void onKeyDown(QKeyEvent *) = 0; virtual void onKeyUp(QKeyEvent *) = 0; virtual void onMouseDown(QMouseEvent *) = 0; virtual void onMouseMove(QMouseEvent *) = 0; virtual void onWheelMove(QWheelEvent *) = 0; }; <file_sep>#include "diagramwindow.h" #include "ui_diagramwindow.h" #include <QPainter> DiagramWindow::DiagramWindow(QWidget *parent) : QDialog(parent), ui(new Ui::DiagramWindow) { ui->setupUi(this); } DiagramWindow::~DiagramWindow() { delete ui; } void DiagramWindow::paintEvent(QPaintEvent *) { int v1 = 100; int v2 = 300; int v3 = 25; int vsum = v1 + v2 + v3; QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); //painter.drawArc(10, 10, 170, 100, 180*16, 180*16); int h = 20; int startAngle = 0; //painter.drawArc(10, 10+h, 170, 100, 180*16, 180*16); int v1Angle = 360 * 16 * v1 / vsum; int v2Angle = 360 * 16 * v2 / vsum; int v3Angle = 360 * 16 - v2Angle - v1Angle; auto v1Color = Qt::red; auto v2Color = Qt::green; auto v3Color = Qt::blue; // painter.setPen(QPen(QBrush(v1Color), 0)); // painter.setBrush(QBrush(v1Color)); // painter.drawPie(10, 10, 170, 100, startAngle, v1Angle); // startAngle += v1Angle; // painter.setPen(QPen(QBrush(v2Color), 0)); // painter.setBrush(QBrush(v2Color)); // painter.drawPie(10, 10, 170, 100, startAngle, v2Angle); // startAngle += v2Angle; // painter.setPen(QPen(QBrush(v3Color), 0)); // painter.setBrush(QBrush(v3Color)); // painter.drawPie(10, 10, 170, 100, startAngle, v3Angle); qreal percent = 0.2; QPainterPath path(QPointF(10, 10)); path.lineTo(10, 10+h); path.arcTo(10, -15+h, 300, 50, 180, 180); auto curPoint = path.currentPosition(); path.lineTo(curPoint.x(), curPoint.y()-h); path.arcTo(10, -15, 300, 50, 0, -180); // qreal percent = 0.2; // QPainterPath path(QPointF(10, 10)); // path.lineTo(10, 10+h); // path.arcTo(10, -15+h, 300, 50, 280, 180*percent); //auto curPoint = path.currentPosition(); //path.lineTo(curPoint.x(), curPoint.y()-h); //auto curPoint2 = path.currentPosition(); //path.arcTo(10, -15, curPoint2.x(), curPoint2.y(), 0, -180*percent); //path.lineTo(10+300*percent, 10); //path.arcTo(10, -15, 300*percent, 50, 0, -180*percent); //path.lineTo(10, 10+h); //path.lineTo(170, 10+h); //path.arcTo(10, 10, 170, 100, 0*16, 10*16); //path.lineTo(170, 10); //path.lineTo(10, 10); //path.arcTo(10, 10+h, 170, 100, 180*16, 180*16); painter.setClipRect(10, 10, 180, 25+10+h); painter.setPen(QPen(v1Color)); painter.setBrush(QBrush(v1Color)); painter.drawPath(path); painter.setClipRect(10+180, 10, 300-180, 25+10+h); painter.setPen(QPen(v2Color)); painter.setBrush(QBrush(v2Color)); painter.drawPath(path); //painter.drawLine(10, 10+100/2, 10, 10+100/2+h); //painter.drawLine(10+170, 10+100/2, 10+170, 10+100/2+h); } <file_sep>#pragma once #include <QObject> #include <QVector3D> #include <QSize> #include <stdint.h> #include "iscenecamera.h" /// Static camera, can be manually controlled. class RotatingCamera : public QObject, public ISceneCamera { Q_OBJECT Q_DISABLE_COPY(RotatingCamera) Q_PROPERTY(QSize viewport READ viewport WRITE setViewport) Q_PROPERTY(QVector3D eye READ eye) public: explicit RotatingCamera(QSize viewport, QObject *parent = 0); void loadMatrix() const override; void lookAt(QVector3D const &eye, QVector3D const& at, QVector3D const& up) override; /// @param msec - milliseconds since last advance or creation. void advance(int64_t msec) override; QSize viewport() const override; void setViewport(QSize viewport) override; QVector3D eye() const override; void onKeyDown(QKeyEvent *ev) override; void onKeyUp(QKeyEvent *ev) override; void onMouseDown(QMouseEvent *ev) override; void onMouseMove(QMouseEvent *ev) override; void onWheelMove(QWheelEvent *ev) override; private: void rotateZ(qreal dl); void rotateViewAngle(qreal dl); void modifyRadius(qreal dr); private: QSize m_viewport; QVector3D m_eye; /**< Eye position */ QVector3D m_front; /**< Front direction */ QVector3D m_up; /**< Up direction */ QVector3D m_speed; /**< Speed, meters per second, front/left/up */ qreal m_radius; QVector3D m_at; int m_prevMouseX; int m_prevMouseY; }; <file_sep>#include "viewcontorller.h" ViewContorller::ViewContorller(QSize viewportSize, QObject *parent) : QObject(parent) , m_rotatingCamera(viewportSize) , m_freeCamera(viewportSize) { m_camera = &m_rotatingCamera; } void ViewContorller::setViewport(QSize viewport) { m_rotatingCamera.setViewport(viewport); m_freeCamera.setViewport(viewport); } ISceneCamera& ViewContorller::camera() { return *m_camera; } const ISceneCamera& ViewContorller::camera() const { return *m_camera; } void ViewContorller::switchCameras() { //m_camera = (m_camera == &m_rotatingCamera) ? &m_freeCamera : &m_rotatingCamera; if (m_camera == &m_rotatingCamera) { m_camera = &m_freeCamera; } else { m_camera = &m_rotatingCamera; } } <file_sep>#include "insertrowdialog.h" #include "ui_insertrowdialog.h" #include <QPushButton> InsertRowDialog::InsertRowDialog(QWidget *parent) : QDialog(parent), ui(new Ui::InsertRowDialog) { ui->setupUi(this); connect(this, SIGNAL(accepted()), this, SLOT(onAccepted())); ui->buttonBox->button(QDialogButtonBox::Ok)->setDisabled(true); } InsertRowDialog::~InsertRowDialog() { delete ui; } void InsertRowDialog::onAccepted() { emit rowReady(ui->editName->text(), ui->editValue->value()); } void InsertRowDialog::on_editName_textChanged(const QString &) { UpdateOkButtonState(); } void InsertRowDialog::on_editValue_valueChanged(int) { UpdateOkButtonState(); } bool InsertRowDialog::IsTheDataAcceptable() { return (!(ui->editName->text().isEmpty()) && (ui->editValue->value() != 0)); } void InsertRowDialog::UpdateOkButtonState() { if (IsTheDataAcceptable()) { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } else { ui->buttonBox->button(QDialogButtonBox::Ok)->setDisabled(true); } } <file_sep>#include "freecamera.h" #include "glhelper.h" #include <QMatrix4x4> #include <QGenericMatrix> #include <cmath> const qreal CAMERA_MOVE_SPEED = 3; const qreal CAMERA_ROTATION_SPEED = 0.3; namespace { QVector3D RotateVector(QVector3D const &vec3D, QVector3D const &axis, qreal angle) { QMatrix4x4 transformationMatrix; transformationMatrix.rotate(angle, axis); QVector4D vec4D(vec3D); vec4D = vec4D * transformationMatrix; return vec4D.toVector3D(); } QVector3D MoveVector(QVector3D const &vector, QVector3D const &axis, qreal distance) { return QVector3D(vector + axis * (distance / axis.length())); } } FreeCamera::FreeCamera(QSize viewport, QObject *parent) : QObject(parent) , m_viewport(viewport) { } void FreeCamera::loadMatrix() const { QMatrix4x4 matrix; matrix.lookAt(m_eye, m_eye + m_front, m_up); GLHelper::setModelViewMatrix(matrix); } void FreeCamera::lookAt(const QVector3D &eye, const QVector3D &at, const QVector3D &up) { m_eye = eye; m_front = at - eye; m_up = up; m_front.normalize(); } void FreeCamera::advance(int64_t msec) { QVector3D left = QVector3D::crossProduct(m_up, m_front); float seconds = float(msec) * 0.001f; m_eye = (m_movingRight) ? MoveVector(m_eye, left, -CAMERA_MOVE_SPEED * seconds) : m_eye; m_eye = (m_movingLeft) ? MoveVector(m_eye, left, CAMERA_MOVE_SPEED * seconds) : m_eye; m_eye = (m_movingForward) ? MoveVector(m_eye, m_front, CAMERA_MOVE_SPEED * seconds) : m_eye; m_eye = (m_movingBackwards) ? MoveVector(m_eye, m_front, -CAMERA_MOVE_SPEED * seconds) : m_eye; } QSize FreeCamera::viewport() const { return m_viewport; } void FreeCamera::setViewport(QSize viewport) { m_viewport = viewport; } QVector3D FreeCamera::eye() const { return m_eye; } void FreeCamera::onKeyDown(QKeyEvent *ev) { switch (ev->key()) { case Qt::Key_Left: m_movingLeft = true; break; case Qt::Key_Right: m_movingRight = true; break; case Qt::Key_Up: m_movingForward = true; break; case Qt::Key_Down: m_movingBackwards = true; break; } } void FreeCamera::onKeyUp(QKeyEvent *ev) { switch (ev->key()) { case Qt::Key_Left: m_movingLeft = false; break; case Qt::Key_Right: m_movingRight = false; break; case Qt::Key_Up: m_movingForward = false; break; case Qt::Key_Down: m_movingBackwards = false; break; } } void FreeCamera::onMouseDown(QMouseEvent *ev) { m_prevMouseX = ev->x(); m_prevMouseY = ev->y(); } void FreeCamera::onMouseMove(QMouseEvent *ev) { if (ev->buttons() & Qt::LeftButton) { int curX = ev->x(); int curY = ev->y(); int dx = curX - m_prevMouseX; int dy = curY - m_prevMouseY; m_prevMouseX = curX; m_prevMouseY = curY; rotateUp(-dy * CAMERA_ROTATION_SPEED); rotateRight(dx * CAMERA_ROTATION_SPEED); } } void FreeCamera::onWheelMove(QWheelEvent *) { } void FreeCamera::rotateRight(qreal angle) { m_front = RotateVector(m_front, m_up, angle); m_front.normalize(); } void FreeCamera::rotateUp(qreal angle) { QVector3D axis = QVector3D::crossProduct(m_up, m_front); m_front = RotateVector(m_front, axis, angle); m_up = RotateVector(m_up, axis, angle); m_front.normalize(); m_up.normalize(); } void FreeCamera::initMousePosition(QMouseEvent *ev) { m_prevMouseX = ev->x(); m_prevMouseY = ev->y(); } <file_sep>#pragma once #include <QObject> #include <QSize> #include <QVector3D> #include "rotatingcamera.h" #include "freecamera.h" #include "iscenecamera.h" class ViewContorller : public QObject { Q_OBJECT Q_DISABLE_COPY(ViewContorller) public: ViewContorller(QSize viewportSize, QObject *parent = 0); void setViewport(QSize viewport); ISceneCamera& camera(); const ISceneCamera& camera() const; void switchCameras(); private: FreeCamera m_freeCamera; RotatingCamera m_rotatingCamera; ISceneCamera* m_camera; }; <file_sep>#include "statsdocument.h" #include "statskeyvaluemodel.h" #include "istatsmodelprovider.h" #include "statsserializer.h" #include <QWidget> #include <QFileDialog> #include <QStandardPaths> namespace { const QLatin1String FILE_FORMAT_FILTER("*.json"); } StatsDocument::StatsDocument(QWidget *parent, IStatsModelProvider &provider) : QObject(parent) , m_provider(provider) { } void StatsDocument::createNew() { StatsKeyValueModel model; m_provider.setStatsModel(model); m_loadedDocumentPath = ""; } bool StatsDocument::open() { QString openPath = selectOpenPath(); if (openPath.isEmpty()) { return false; } m_loadedDocumentPath = openPath; StatsKeyValueModel model; StatsSerializer serializer(openPath); if (!serializer.load(model)) { return false; } m_provider.setStatsModel(model); return true; } bool StatsDocument::save() { if (m_loadedDocumentPath.isEmpty()) { return saveAs(); } if (saveData(m_loadedDocumentPath)) { return true; } return saveAs(); } bool StatsDocument::saveAs() { QString savePath = selectSavePath(); if (savePath.isEmpty()) { return false; } m_loadedDocumentPath = savePath; return saveData(savePath); } QString StatsDocument::selectSavePath() const { QString fromDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); auto parentWindow = qobject_cast<QWidget *>(parent()); return QFileDialog::getSaveFileName(parentWindow, QString(), fromDir, FILE_FORMAT_FILTER); } QString StatsDocument::selectOpenPath() const { QString fromDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); auto parentWindow = qobject_cast<QWidget *>(parent()); return QFileDialog::getOpenFileName(parentWindow, QString(), fromDir, FILE_FORMAT_FILTER); } bool StatsDocument::saveData(const QString &savePath) const { StatsSerializer serializer(savePath); return serializer.save(m_provider.statsModel()); } <file_sep>#pragma once #include "../gl/scenenode.h" class ColoredCube : public SceneNode { public: ColoredCube(SceneNode *parent); void advance(int64_t msec) override; void render(QPainter &painter) override; }; <file_sep>#pragma once #include "../gl/scenenode.h" class Cylinder : public SceneNode { public: Cylinder(SceneNode *parent); void advance(int64_t msec) override; void render(QPainter &painter) override; }; <file_sep>#include <qopengl.h> #include <QVector> #include "cylinder.h" struct Vec3 { GLfloat x, y, z; }; namespace { QVector<Vec3> getCircle(GLfloat r, Vec3 const& center, uint precision) { (void)r; (void)center; (void)precision; return { center, { 1, 0, 1}, {-1, 0, 1}, {-1, 0, -1}, { 1, 0, -1} }; } void drawCircle(QVector<Vec3> const& circle) { //glEnableClientState(GL_VERTEX_ARRAY); // glVertexPointer(3, GL_FLOAT, sizeof(SimpleVertex), &vertices[0].pos); //glDrawElements(GL_TRIANGLE_FAN, 3, GL_UNSIGNED_BYTE, faces); //glDisableClientState(GL_VERTEX_ARRAY); glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0,1.0,0.0); const unsigned char faces[1][3] = { {0, 2, 1}//, //{0, 1, 4}, //{0, 3, 4}, //{0, 3, 2}, }; //glVertexPointer(3, GL_FLOAT, 0, &circle[0]); //glEnableClientState(GL_VERTEX_ARRAY); //glDrawElements(GL_TRIANGLES, 1, GL_UNSIGNED_BYTE, faces); //glDisableClientState(GL_VERTEX_ARRAY); GLfloat pVerts[]= {-0.5f, -0.5f, 0.0f, 0.5f, 0.0f, 0.0f, -0.5f , 0.5f, 0.0f, -0.5f, 0.0f, 0.0f}; //glEnableClientState(GL_VERTEX_ARRAY); //glVertexPointer(3, GL_FLOAT, 0, pVerts); //glDrawArrays(GL_TRIANGLE_FAN,0,4); //glDisableClientState(GL_VERTEX_ARRAY); glBegin(GL_TRIANGLE_FAN); glVertex3f( 0, 0, 0); glVertex3f( 1, 1, 0); glVertex3f(-1, 1, 0); glVertex3f(-1, -1, 0); glEnd(); glBegin(GL_TRIANGLE_FAN); glColor3d(0,0,1); glVertex3d(4,2,0); glVertex3d(2.6,2.8,0); glVertex3d(2,2,0); glVertex3d(3,1.1,0); glEnd(); } } Cylinder::Cylinder(SceneNode *parent) : SceneNode(parent) { } void Cylinder::advance(int64_t msec) { (void)msec; } void Cylinder::render(QPainter &painter) { (void)painter; GLfloat r = 100; GLfloat h = 100; uint precision = 4; Vec3 bottomCircleCenter = { 0, 0, 0 }; Vec3 topCircleCenter = { 0, bottomCircleCenter.y + h, 0 }; QVector<Vec3> topCircle = getCircle(r, topCircleCenter, precision); //QVector<Vec3> bottomCircle = getCircle; drawCircle(topCircle); }
3f314234749e30da3fb13b0fc06593ee36a476f4
[ "C++" ]
13
C++
RattleInGlasses/ps_cg
1bf9cb272142299c5de8fef182cc2059932d5a81
fc4e236559713cec51b46c7fb988beab8963ef76
refs/heads/master
<file_sep> // Main app class enyo.kind({ name: "Farming.App", kind: enyo.Control, classes: "main", components: [ {components: [ {name: "crops", kind: "Image", src: "icons/crops.png", classes: "cropsbutton", ontap: "showCrops"}, {name: "livestock", kind: "Image", src: "icons/livestock.png", classes: "livestockbutton", ontap: "showLivestock"}, {content: "Crops", classes: "crops_text"}, {content: "Livestock", classes: "livestock_text"}, ]}, ], // Constructor create: function() { this.inherited(arguments); }, // Show all crops showCrops: function(e, s) { Farming.context.home = new Farming.Crops().renderInto(document.getElementById("body")); }, // Show all livestock showLivestock: function(e, s) { Farming.context.home = new Farming.Livestock().renderInto(document.getElementById("body")); } });<file_sep>// List of all crops enyo.kind({ name: "Farming.Crops", kind: enyo.Control, classes: "board", published: { context: null, }, components: [ {components: [ {name: "Corn", kind: "Image", src: "icons/corn.svg", classes: "secondmenubutton", ontap: "showCorn"}, {name: "Wheat", kind: "Image", src: "icons/wheat.svg", classes: "secondmenubutton", ontap: "showWheat"}, {name: "Potatoes", kind: "Image", src: "icons/potatoes.svg", classes: "secondmenubutton", ontap: "showPotatoes"}, {name: "Rice", kind: "Image", src: "icons/rice.svg", classes: "secondmenubutton", ontap: "showRice"}, {name: "Cassava", kind: "Image", src: "icons/cassava.png", classes: "secondmenubutton", ontap: "showCassava"}, {content: "Corn/Maize", classes: "secondmenutext"}, {content: "Wheat", classes: "secondmenutext"}, {content: "Potatoes", classes: "secondmenutext"}, {content: "Rice", classes: "secondmenutext"}, {content: "Cassava", classes: "secondmenutext"}, {name: "Sorghum", kind: "Image", src: "icons/sorghum.svg", classes: "secondmenubutton", ontap: "showSorghum"}, {name: "Sweet Potatoes", kind: "Image", src: "icons/sweet_potatoes.svg", classes: "secondmenubutton", ontap: "showSweetPotatoes"}, {name: "Yam", kind: "Image", src: "icons/yam.png", classes: "secondmenubutton", ontap: "showYam"}, {name: "Soybeans", kind: "Image", src: "icons/soybeans.svg", classes: "secondmenubutton", ontap: "showSoybeans"}, {name: "Coconuts", kind: "Image", src: "icons/coconuts.svg", classes: "secondmenubutton", ontap: "showCoconuts"}, {content: "Sorghum", classes: "secondmenutext"}, {content: "Sweet Potatoes", classes: "secondmenutext"}, {content: "Yam", classes: "secondmenutext"}, {content: "Soybeans", classes: "secondmenutext"}, {content: "Coconuts", classes: "secondmenutext"}, ]}, ], // Constructor create: function() { this.inherited(arguments); }, // show corn function showCorn: function(e, s) { Farming.context.home = new Farming.Corn().renderInto(document.getElementById("body")); }, // show wheat function showWheat: function(e, s) { Farming.context.home = new Farming.Wheat().renderInto(document.getElementById("body")); }, // show potatoes function showPotatoes: function(e, s) { Farming.context.home = new Farming.Potatoes().renderInto(document.getElementById("body")); }, // show rice function showRice: function(e, s) { Farming.context.home = new Farming.Rice().renderInto(document.getElementById("body")); }, // show cassava function showCassava: function(e, s) { Farming.context.home = new Farming.Cassava().renderInto(document.getElementById("body")); }, // show sorghum function showSorghum: function(e, s) { Farming.context.home = new Farming.Sorghum().renderInto(document.getElementById("body")); }, // show sweet potatoes function showSweetPotatoes: function(e, s) { Farming.context.home = new Farming.SweetPotatoes().renderInto(document.getElementById("body")); }, // show function showYam: function(e, s) { Farming.context.home = new Farming.Yam().renderInto(document.getElementById("body")); }, // show cassava function showSoybeans: function(e, s) { Farming.context.home = new Farming.Soybean().renderInto(document.getElementById("body")); }, // show cassava function showCoconuts: function(e, s) { Farming.context.home = new Farming.Coconuts().renderInto(document.getElementById("body")); }, }); <file_sep>define(function (require) { Farming.activity = require("sugar-web/activity/activity"); app = null; // Manipulate the DOM only when it is ready. require(['domReady!'], function (doc) { // Initialize the activity. Farming.activity.setup(); // Home button document.getElementById("home").onclick = function() { Farming.context.home = app = new Farming.App().renderInto(document.getElementById("body")); }; // Forum button document.getElementById("forum"); // Create and display first screen Farming.context.home = app = new Farming.App().renderInto(document.getElementById("body")); }); }); <file_sep> // List of all crops enyo.kind({ name: "Farming.Livestock", kind: enyo.Control, classes: "board", published: { context: null, }, components: [ {components: [ {name: "Cattle", kind: "Image", src: "icons/cattle.svg", classes: "secondmenubutton", ontap: "showCattle"}, {name: "Sheep", kind: "Image", src: "icons/sheep.svg", classes: "secondmenubutton", ontap: "showSheep"}, {name: "Goats", kind: "Image", src: "icons/goats.svg", classes: "secondmenubutton", ontap: "showGoats"}, {name: "Horse", kind: "Image", src: "icons/horse.svg", classes: "secondmenubutton", ontap: "showHorses"}, {name: "Pig", kind: "Image", src: "icons/pig.svg", classes: "secondmenubutton", ontap: "showPigs"}, {content: "Cattle", classes: "secondmenutext"}, {content: "Sheep", classes: "secondmenutext"}, {content: "Goats", classes: "secondmenutext"}, {content: "Horses", classes: "secondmenutext"}, {content: "Pigs", classes: "secondmenutext"}, {name: "Deer", kind: "Image", src: "icons/deer.svg", classes: "secondmenubutton", ontap: "showDeer"}, {name: "Poultry", kind: "Image", src: "icons/chicken.svg", classes: "secondmenubutton", ontap: "showPoultry"}, {name: "Guinea Pig", kind: "Image", src: "icons/guinea_pig.png", classes: "secondmenubutton", ontap: "showGuineaPig"}, {name: "Buffalo", kind: "Image", src: "icons/buffalo.svg", classes: "secondmenubutton", ontap: "showBuffalo"}, {name: "Rabbit", kind: "Image", src: "icons/rabbit.svg", classes: "secondmenubutton", ontap: "showRabbit"}, {content: "Deer", classes: "secondmenutext"}, {content: "Poultry", classes: "secondmenutext"}, {content: "Guinea Pig", classes: "secondmenutext"}, {content: "Buffalo", classes: "secondmenutext"}, {content: "Rabbit", classes: "secondmenutext"}, ]}, ], // Constructor create: function() { this.inherited(arguments); }, // show cattle function showCattle: function(e, s) { Farming.context.home = new Farming.Cattle().renderInto(document.getElementById("body")); }, // show sheep function showSheep: function(e, s) { Farming.context.home = new Farming.Sheep().renderInto(document.getElementById("body")); }, // show goats function showGoats: function(e, s) { Farming.context.home = new Farming.Goats().renderInto(document.getElementById("body")); }, // show horses function showHorses: function(e, s) { Farming.context.home = new Farming.Horses().renderInto(document.getElementById("body")); }, // show pigs function showPigs: function(e, s) { Farming.context.home = new Farming.Pigs().renderInto(document.getElementById("body")); }, // show deer function showDeer: function(e, s) { Farming.context.home = new Farming.Deer().renderInto(document.getElementById("body")); }, // show poultry function showPoultry: function(e, s) { Farming.context.home = new Farming.Poultry().renderInto(document.getElementById("body")); }, // show guinea pig function showGuineaPig: function(e, s) { Farming.context.home = new Farming.GuineaPig().renderInto(document.getElementById("body")); }, // show buffalo function showBuffalo: function(e, s) { Farming.context.home = new Farming.Buffalo().renderInto(document.getElementById("body")); }, // show rabbit function showRabbit: function(e, s) { Farming.context.home = new Farming.Rabbit().renderInto(document.getElementById("body")); }, });<file_sep># farming-activity An activity that helps farmers improve their farming skills <file_sep>// List of all crops enyo.kind({ name: "Farming.SweetPotatoes", kind: "FittableRows", classes: "enyo-list", components: [ { kind: "Farming.Header" }, { name: "appList", kind: "List", fit:true, count:0, touch:true, onSetupItem: "setupItem", components: [ { kind: "FittableColumns", components: [ { name: "imageSource", kind: "Image", classes: "list-image", src: "Set Source...", }, { name: "listItem", classes:'listItemContainer', ontap:'listItemTapped', components: [ { name: "itemTitle", content:"Set Title..." } ] } ] }, ] }, ], create: function(){ this.inherited(arguments); this.$.appList.setCount(sweetpotatoes.length); }, setupItem: function(inSender,inEvent) { //During the iteration of setupItem, this event will create inEvent.index which is //assigned automatically. inEvent.index is very useful, to map array index of datasource later. //In enyo, this.variableName is the same as to var a variable. Only difference is they remained //within the closure. this.crop = sweetpotatoes[inEvent.index].crop; this.disease = sweetpotatoes[inEvent.index].disease; this.id = sweetpotatoes[inEvent.index].identification; this.management = sweetpotatoes[inEvent.index].management; this.photos = sweetpotatoes[inEvent.index].src; // this.$.itemTitle.setContent(this.id); // Yup, as simple as assigning properties. this.$.itemTitle.setContent(this.disease+"\n"+": "+this.id); this.$.imageSource.setSrc(this.photos); }, listItemTapped: function(inSender,inEvent){ //Best practice you should always refer your index with the ones in memory. //Reason being, list can be highly dynamic and some can be sorted and filtered search. //Always try to referred the index with the ones in the memory. alert("Management of "+this.disease+":\n\n"+this.management); } });<file_sep>enyo.depends( "js/crops/corn.js", "js/crops/wheat.js", "js/crops/potatoes.js", "js/crops/rice.js", "js/crops/cassava.js", "js/crops/sorghum.js", "js/crops/sweetpotatoes.js", "js/crops/yam.js", "js/crops/soybeans.js", "js/crops/coconuts.js", "js/livestock/test.js", "js/livestock/sheep.js", "js/livestock/cattle.js", "js/livestock/goats.js", "js/livestock/horses.js", "js/livestock/pigs.js", "js/livestock/buffalo.js", "js/livestock/deer.js", "js/livestock/guineapig.js", "js/livestock/poultry.js", "js/livestock/rabbit.js", "js/livestock.js", "js/crops.js", "js/header.js", "app.js" );
88d8fc4c2131c8b7e2f3a8332a639e6896e1f803
[ "JavaScript", "Markdown" ]
7
JavaScript
WorldWideSemanticWeb/farming-activity
4250e16b59f9e6e33925fd07d15b020772a19328
90ad958546695abb778b1194833ed766dbb88ff9
refs/heads/master
<file_sep>var Utils = require ('../utils'); /** * This class will store Mqtt configuration details * @class MqttConfig * @constructor */ function MqttConfig() { this.brokerPort = null; this.brokerHost = null; this.options = {}; this.options.clean = false; this.options.clientId = null; this.options.username = null; this.options.password = <PASSWORD>; this.topicSubscribe = []; this.publish = {}; this.publish.topic = null; this.publish.qos = 0; }; /** * Initialize Amqp channel from a json configuration object * @method init * @param {String} _config: json configuration object * @return */ MqttConfig.prototype.init = function(_config) { Utils.assertValueIsSet(_config, 'Config is missing', 'MqttConfig', 'init'); this.brokerHost = Utils.getValue(_config.broker.host, 'localhost'); this.brokerPort = Utils.getValue(_config.broker.port, '1883'); this.options.clean = Utils.getBooleanValue(_config.cleanSession, false); if (!this.options.clean) { Utils.assertValueIsSet(_config.clientId, 'Client Id is mandatory when cleanSession is false', 'MqttConfig', 'init'); } this.options.clientId = Utils.getValue(_config.clientId, null); this.options.username = Utils.getValue(_config.userName, null); this.options.password = Utils.getValue(_config.password, null); this.topicSubscribe = _config.topicSubscribe; if ( Utils.valueIsSet(_config.publish) ) { this.publish.topic = _config.publish.topic; this.publish.qos = Utils.getIntValue(_config.publish.qos, 0); } }; /** * Return Mqtt options as a JSON string * @method options * @return Mqtt options as a JSON string */ MqttConfig.prototype.getOptions = function(_config) { return JSON.stringify(this.options); }; module.exports = MqttConfig; <file_sep>var Utils = require ('../utils'); var Mongodb = require('mongoose'); var When = require('when'); var Defer = require('when').defer; var Logger = require('../Logger'); /** * This class will handle all interactions with Mongodb database * It relies on mongodb client npm/mongoose * @class MongodbClient * @constructor */ function MongodbClient() { this.host = null; this.connection = null; } /** * Initialize Mongodb Client from a json configuration object * @method init * @param {String} _config: json configuration object * @return */ MongodbClient.prototype.init= function(_config) { Utils.assertValueIsSet(_config, 'Config is missing', 'MongodbClient', 'init'); Utils.assertValueIsSet(_config.host, 'Mongodb host is missing', 'MongodbClient', 'init'); this.host = _config.host; return; }; /** * Connect to Mongodb Broker * @method open * @return (Defer) A promise that is resolved once the connection is successfull, * or rejected if the connection failed */ MongodbClient.prototype.open = function() { var open = Defer(); var self = this; Logger.info('Connecting to MongoDb on %s ', this.host, {module: "MongodbClient=", function:"mongodbOpen"}); Mongodb.connect(this.host); this.connection = Mongodb.connection; this.connection.on('error', function(e) { open.reject(new Error('Mongodb Connect failed: ' + e.message)); } ); this.connection.once('open', function() { open.resolve(); }); return open.promise; }; /** * Disconnect to Amqp Broker * @method close * @return */ MongodbClient.prototype.close= function() { if (this.connection != null && this.connection != undefined) { this.connection.close(); } }; module.exports = MongodbClient; <file_sep>var Utils = require ('../utils'); /** * This class will store Amqp channels configuration details * @class AmqpChannel * @constructor */ function AmqpChannel() { this.exchange = null; this.exchangeType = null; this.topic = null; this.queue = null; this.exclusive = null; this.routingKey = null; }; /** * Initialize Amqp channel from a json configuration object * @method init * @param {String} _config: json configuration object * @return */ AmqpChannel.prototype.init = function(_config) { Utils.assertValueIsSet(_config, '[AmqpChannel][init] Config is missing'); Utils.assertValueIsSet(_config.exchange, '[AmqpChannel][init] exchange field is missing in config.json'); Utils.assertValueIsSet(_config.exchangeType, '[AmqpChannel][init] exchangeType field is missing in config.json'); Utils.assertValueIsSet(_config.routingKey, '[AmqpChannel][init] routingKey field is missing in config.json'); this.exchange = _config.exchange; this.exchangeType = _config.exchangeType; this.routingKey = _config.routingKey; }; module.exports = AmqpChannel; <file_sep>var config = {}; var Utils = require ('./utils'); var Defer = require('when').defer; var When = require('when'); var Logger = require('./Logger'); /** * This class defines the common behavior to all Agents * Depending on their configurations, agent may interact with different transports: * AMQP broker * MQTT broker * Mongodb * ACS * * @class Agent * @constructor */ function Agent() { this.amqpClient = null; this.onAmqpMessage = null; this.mqttClient = null; this.onMqttMessage = null; this.mongodbClient = null; this.acs = null; }; /** * Initialize Agent from a json configuration object * Based on the configuration file, corresponding transports will be created and initialized * @method init * @param {String} _config: json configuration object * @return */ Agent.prototype.init = function(_config) { Logger.init(_config); if ( Utils.valueIsSet(_config.amqp) ) { this.initAmqp(_config.amqp); } if (Utils.valueIsSet(_config.mongodb) ) { this.initMongodb(_config.mongodb); } if ( Utils.valueIsSet(_config.mqtt) ) { this.initMqtt(_config.mqtt); } return; } /** * Initialize Amqp client from a json configuration object * @method initAmqp * @param {String} _config: json configuration object * @return */ Agent.prototype.initAmqp = function(configAmqp) { Logger.info('', {module: "Agent", function:"initAmqp"}); Amqp = require('./amqp/client'); this.amqpClient = new Amqp(); this.amqpClient.init(configAmqp); return; } /** * Initialize Mqtt client from a json configuration object * @method initMqtt * @param {String} _config: json configuration object * @return */ Agent.prototype.initMqtt = function(_configMqtt) { Logger.info('', {module: "Agent", function:"initMqtt"}); Mqtt = require('./mqtt/client'); this.mqttClient = new Mqtt(); this.mqttClient.init(_configMqtt); return; }; /** * Initialize Mongodb client from a json configuration object * @method initMongodb * @param {String} _config: json configuration object * @return */ Agent.prototype.initMongodb = function(configMongodb) { Logger.info('', {module: "Agent", function:"initMongodb"}); Mongodb = require('./mongodb/client'); this.mongodbClient = new Mongodb(); this.mongodbClient.init(configMongodb); return; }; /** * Initialize ACS client from a json configuration object * @method initAmqp * @param {String} _config: json configuration object * @return */ Agent.prototype.initACS = function(configAcs) { config.acs = configAcs; Logger.info('config.acs.active = ' + config.acs.active, {module: "Agent", function:"initACS"}); if (config.acs.active == "yes") { Acs = require('./acs'); this.acs = new Acs(config.acs.login, config.acs.password); } return; }; /** * Start Agent. Will connect to all transports that have been configured * @method start * @return (Defer) A promise that is resolved once the agent is successfully connected to all configured transports * or fail if the connection to any of the transports fails */ Agent.prototype.start = function() { Logger.info("starting...", {module: "Agent", function:"start"}); var started = []; // // connect to AMQP if configured // if (this.amqpClient != null) { var amqpStarted = Defer(); started.push(amqpStarted.promise); this.amqpClient.open() .then( function() { Logger.info('Connected to Amqp', {module: "Agent", function:"start"}); amqpStarted.resolve(); }).catch( function(e) { amqpStarted.reject(e); }); } else { Logger.info('No amqp client set', {module: "Agent", function:"start"}); } // // connect to Mqtt if configured // if (this.mqttClient != null) { var mqttStarted = Defer(); started.push(mqttStarted.promise); this.mqttClient.open() .then( function() { Logger.info('Connected to Mqtt', {module: "Agent", function:"start"}); mqttStarted.resolve(); }).catch( function(e) { mqttStarted.reject(e); }); } else { Logger.info('No mqtt client set', {module: "Agent", function:"start"}); } // // connect to MongoDb if configured // if (this.mongodbClient != null) { var mongodbStarted = Defer(); started.push(mongodbStarted.promise); this.mongodbClient.open() .then( function() { Logger.info('Connected to Mongodb', {module: "Agent", function:"start"}); mongodbStarted.resolve(); }).catch( function(e) { mongodbStarted.reject(e); }); } else { Logger.info('No mongodb client set', {module: "Agent", function:"start"}); } return When.all(started); /* var self = this; // connect to appcelerator cloud if (config.acs != undefined && config.acs.active == "yes" && self.acs != null) { self.acs.login(started.bind(self), self.stop.bind(self)); } else { started(); } } function started() { Logger.info("[Agent] started"); onSuccess(); } */ }; /** * Stop Agent. Will disconnect from all transports that have been configured * @method start * @return */ Agent.prototype.stop = function() { Logger.info("stopping...", {module: "Agent", function:"stop"}); // stop amqp if (this.amqpClient != null) { this.amqpClient.close(); Logger.info('Amqp client stopped', {module: "Agent", function:"stop"}); } else { Logger.info('No amqp client set', {module: "Agent", function:"stop"}); } // stop mongodb if (this.mongodbClient != null) { this.mongodbClient.close(); Logger.info('Mongodb client stopped', {module: "Agent", function:"stop"}); } else { Logger.info('No mongodb client set', {module: "Agent", function:"stop"}); } // stop mqtt if (this.mqttClient != null) { this.mqttClient.close(); Logger.info('Mqtt client stopped', {module: "Agent", function:"stop"}); } else { Logger.info('No mqtt client set', {module: "Agent", function:"stop"}); } return; }; /** * Register callback function to be called whenever a subscribe message is received * @method registerOnMessageReceived * @param {String} _callback: callback function * @return */ Agent.prototype.registerOnMessageReceived = function(_callback) { if (this.amqpClient != null) { this.amqpClient.registerOnMessageReceived(_callback); } if (this.mqttClient != null) { this.mqttClient.registerOnMessageReceived(_callback); } return; }; /** * Publish a message on the transport Broker (AMQP of MQTT) * If not transport broker is configured, it will throw an exception * If 2 transport brokers are defined, it's published on both * @method publish * @param {String} _msg: Message to be published * @return (Defer) A promise that is resolved once the message has been successfully published, * or rejected if it failed to publish on any of the configured brokers */ Agent.prototype.publish = function(_msg) { if (this.amqpClient == null && this.mqttClient != null) { throw new Error('[Agent][Publish] No transport broker is configured. At least one AMQP or MQTT transport should be defined'); } var published = []; if (this.amqpClient != null) { var amqpPublished = Defer(); published.push(amqpPublished.promise); this.amqpClient.publish(_msg) .then( function() { amqpPublished.resolve(); }) .catch( function(e) { amqpPublished.reject(e); }); } if (this.mqttClient != null) { var mqttPublished = Defer(); published.push(mqttPublished.promise); this.mqttClient.publish(_msg) .then( function() { mqttPublished.resolve(); }) .catch( function(e) { mqttPublished.reject(e); }); } return When.all(published); } Agent.prototype.deletePastEventsFromCloud = function() { if (config.acs.active == "yes" && this.acs != null) { this.acs.deletePastEvents(); } }; Agent.prototype.queryCloudEvents = function(onEvent) { if (config.acs.active == "yes" && this.acs != null) { this.acs.queryEvents(onEvent); } else { Logger.info('Simulate new event...', {module: "Agent", function:"queryCloudEvent"}); var Event = require('Event'); var nearFuture = new Date(); nearFuture.setSeconds(nearFuture.getSeconds() + 3610); var e = new Event(); e.id = 1; e.summary = 'Stade de Reims - Paris Saint-Germain'; e.description = 'Ligue 1 - 14eme journee - En direct sur Canal +'; e.dateStart = nearFuture; e.duration = 7200; onEvent(e); } }; /** * createEventOnCloud * @param {Object} event */ Agent.prototype.createEventOnCloud = function(event) { if (config.acs.active == "yes" && this.acs != null) { this.acs.createEvent(event); } }; /** * deleteEventFromCloud * @param {Object} event */ Agent.prototype.deleteEventFromCloud = function(event) { if (config.acs.active == "yes" && this.acs != null) { this.acs.deleteEvent(event); } }; module.exports = Agent; <file_sep>var Utils = require ('../utils'); var Mqtt = require('mqtt'); var When = require('when'); var Defer = require('when').defer; var Logger = require('../Logger'); var MqttConfig = require('../mqtt/config'); /** * This class will handle all interactions with Mqtt broker * It relies on Mqtt client npm/mqttLib * @class AmqpClient * @constructor */ function MqttClient() { this.config = null; this.client = null; }; /** * Initialize Mqtt Client from a json configuration object * @method init * @param {String} _config: json configuration object * @return */ MqttClient.prototype.init = function(_config) { Utils.assertValueIsSet(_config, '[AmqpClient][Init] Config is missing'); this.config = new MqttConfig(); this.config.init(_config); return; }; /** * Connect to Mqtt Broker * @method open * @return (Defer) A promise that is resolved once the connection is successfull, * or rejected if the connection failed */ MqttClient.prototype.open = function() { var opened = Defer(); Logger.info("Connecting to Mqtt broker %s:'%s' with options %s", this.config.brokerHost, this.config.brokerPort, this.config.getOptions(), {module: "MqttClient", function:"open"}); this.client = Mqtt.createClient(this.config.brokerPort, this.config.brokerHost, this.config.options); this.client.on('connect', function() { opened.resolve(); }); this.client.on('error', function(e) { opened.reject(new Error('Mqtt open failed: ' + e.message)); }); for (var i = 0; i < this.config.topicSubscribe.length; i++) { Logger.info("Subscribing to <" + this.config.topicSubscribe[i] + ">", {module: "MqttClient", function:"open"}); this.client.subscribe(this.config.topicSubscribe[i]); } return opened.promise; }; /** * Disconnect from Mqtt Broker * @method close * @return */ MqttClient.prototype.close= function() { if (this.client != null) { this.client.end(); } return; }; /** * Publish message on Mqtt Broker * @method mqttPublish * @param {String} _msg: Message to publish * @return (Defer) A promise that is resolved once the message has been successfully published, * or rejected if it failed to publish */ MqttClient.prototype.publish = function(_msg) { Logger.info("%s:'%s'", this.config.publish.topic, _msg, {module: "MqttClient", function:"publish"}); var published = Defer(); Utils.assertValueIsSet(this.config.publish.topic); Utils.assertValueIsSet(this.config.publish.qos); this.client.publish(this.config.publish.topic, _msg, {qos: this.config.publish.qos}, function(e) { if (!Utils.valueIsSet(e)) { published.resolve(); } else { published.reject(e); } }); return published.promise; }; /** * Register callback function to be called whenever a subscribe message is received * @method registerOnMessageReceived * @param {String} _callback: callback function * @return */ MqttClient.prototype.registerOnMessageReceived = function(_callback) { this.client.on('message', (function(t, m) { _callback(t, m); })); }; /** * mqttPublish * Publish a message on the mqtt broker */ /* Agent.prototype.mqttSubscribe= function(topic) { if (this.mqttClient != null) { this.mqttClient.subscribe(topic); } };*/ module.exports = MqttClient; <file_sep>var winston = require('winston'); function _Logger() { winston.extend(this); winston.remove(winston.transports.Console); // added by default }; _Logger.prototype.init = function(_cfg) { var transports = _cfg.logs.transports; for (var i = 0; i < transports.length; i++) { for (key in transports[i]) { this.addTransport(key, transports[i][key]); } } winston.cli(); } _Logger.prototype.addTransport = function(name, value) { winston.add(winston.transports[name], value); } var Logger = new _Logger(); module.exports = Logger; <file_sep>AgentLib ========
5037cab98190619a7898816bcc4ea7ec14665144
[ "JavaScript", "Markdown" ]
7
JavaScript
jnguillerme/AgentLib
42d0f66164df64fd845a4d818380cbe014bc2d1b
b30baab6c21283d778751bd270a4d1922e6d0bf2
refs/heads/master
<repo_name>Abdulazeem000/18SW145<file_sep>/labs/Lab1/NameAndRollNo.java class NameAndRollNo { public static void main(String args[]) { String a = args[0]; String b = args[1]; String c = args[2]; int x = Integer.parseInt(c); String d = args[3]; String e = args[4]; String f = args[5]; int g = Integer.parseInt(f); System.out.print(a); System.out.println(b); System.out.print(x); System.out.print(d); System.out.print(e); System.out.print(g); } } <file_sep>/labs/Lab1/Conveerts.java class Conveerts { public static void main (String[] args) { double value = 684.884d; long ipart = (long) value; double fracpart = value - ipart; System.out.println("integer part = " + ipart); System.out.println("fractonal part = " + fracpart); } }<file_sep>/labs/Lab1/CircumferenceDiameterArea.java public class CircumferenceDiameterArea { public static void main(String[] args) { float radius = 2.98f; float pi = 3.14f; float Circumference = 2*pi; float diameter = radius*2; float area = pi*radius*radius; System.out.println("Circumference of a Circle " + (Circumference) ); System.out.println("Diameter of a Circle " + (diameter) ); System.out.println("Area of a Circle " + (area) ); } } <file_sep>/labs/Lab1/StudentInformation.java public class StudentInformation { public static void main(String[] args) { String Task_Done = "Total 8 DataTypes Use For This Task Also use If and Else Statment\n"; String name = "<NAME>"; byte number_of_students = 1; short Total_Marks_in_Major_subjects = 98; int Total_getting_marks_of_practical = 45; float Total_marks_of_practical = 45; float pass_marks_of_practical = 30; float Total_percentage_of_practical = 1.5f; float pass_percentage_of_practical = 1.2f; long Total_getting_marks_of_semister = 930; long Pass_marks_of_semister = 840; double Total_percentage_of_semister = 80; double Pass_percentage_of_semister = 60; char grade = 'A'; boolean pass = true; System.out.println(Task_Done); System.out.println("Name Of Student " + (name) ); System.out.println("number of students " + (number_of_students) ); System.out.println("Total Marks in Major subjects " + (Total_Marks_in_Major_subjects) ); System.out.println("Total getting marks of practical " + (Total_getting_marks_of_practical) ); if (Total_marks_of_practical > pass_marks_of_practical ) { System.out.println("Pass in practical because pass marks is 30 "); } else { System.out.println("Fail."); } if (Total_percentage_of_practical > pass_percentage_of_practical ) { System.out.println("Percentage of a practical is good for pass because pass percenatge required is 1.2"); } else { System.out.println("Fail."); } System.out.println("Total getting marks of semister " + (Total_getting_marks_of_semister) ); if (Total_getting_marks_of_semister > Pass_marks_of_semister ) { System.out.println(" So Pass in Semister because for pass marks is required 840"); } else { System.out.println("Fail."); } System.out.println(" Total percentage in Semister " + (Total_percentage_of_semister) ); if (Total_percentage_of_semister > Pass_percentage_of_semister ) { System.out.println("Percentage of a Semister is good for pass because for pass percentage is required 60"); } else { System.out.println("Fail."); } System.out.println("So The Getting Grade is " + (grade) ); if (true==pass) System.out.println("pass"); else System.out.println("fail"); } }
ec05cc9ea088ac289ad7a7ad279a744a69a1025c
[ "Java" ]
4
Java
Abdulazeem000/18SW145
82847dd91eab11d0bb8cc8fb871ee10525166a07
4840531ccef43be3b5ab6090f130d9b201d08227
refs/heads/main
<repo_name>JuliaDSolano/Estrutura-de-dados-1<file_sep>/README.md # Estrutura-de-dados-1 Códigos em C <file_sep>/Aula 1 e 2 - Julia Solano/conversaoGraus.c //importa biblioteca #include <stdio.h> //------ função main int main (){ // declaração de variáveis float C, F; int c = 167; //mensagem para usuario digitar uma temperatura printf("Digite uma temperatura em %cC : ", c); //Pegar dado digitado pelo usuario e redirecionar para a variavel C scanf("%f", &C); //conversão de temperatura F = C*(9.0/5.0)+32; //Mostra para o usuario a conversão feita printf("%3.f%cC e o mesmo que %3.f%cF", C, c, F,c ); } <file_sep>/Aula 3 e 4 - Julia Solano/ponteiros.c #include <stdio.h> int main() { int i = 1; //valor inteiro que a variável será apontada pelo ponteiro int *ponteiroint = &i; //delcarando valor para o ponteiro *ponteiroint = 2; //atribuicao de valor para ponteiro //valor em float float f = 0.6; float *ponteirofloat = &f; *ponteirofloat = 0.2; //valor em char char c ='n'; char *ponteirochar = &c; *ponteirochar = 'b'; //imprimir para o usuario os valores correspondentes printf("O valor do inteiro e %i ", *ponteiroint); printf("\nO valor real e %f", *ponteirofloat); printf("\nO valor de Char e %c", *ponteirochar); } <file_sep>/Aula 1 e 2 - Julia Solano/compara maior.c //inclusão de biblioteca //decalaração de variáveis #include <stdio.h> int compara(int a, int b, float c); //-------- função main int main(){ int n1, n2, n3, res; //declarção de variaveis no corpo printf("Digite dois valores inteiros e um real, todos separados por espaço:\n"); //comando para inserção de dados do usuário scanf("%d", &n1,"%d", &n2, "%f", &n3); //pegar os valores digitados e colocalos em variavéis res = compara(n1, n2, n3); //variavel recebendo uma lista com os valores printf("o maior número é: %d\n", res); //retornar o maior numero entre os tres return 0; } // ------- função de comparação dos valores int compara(int a, int b, float c){ if (a > b, c) { return a; }else if(b > a,c){ return b; }else{ return c; } }
edd25207cc1e1f85bbc9b84c1b48a8d348c8f884
[ "Markdown", "C" ]
4
Markdown
JuliaDSolano/Estrutura-de-dados-1
f966069185550d76345d7726926b7be59579b7cd
8e0d7264e8e5b5743cb744ecc18bba2d5edd5c9f
refs/heads/master
<file_sep>package com.roadandfields.tests; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.Test; import com.roadandfields.pages.CAPage; import com.roadandfields.util.BrowserFactory; @Test public class Test1 { public void main() throws InterruptedException { WebDriver driver = BrowserFactory.openBrowser("firefox", "https://www.rodanandfields.com/ca/"); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //Click All Product link CAPage CAPage= new CAPage(driver); CAPage.allProductsClick(); //System.out.println(quickPageURL); Thread.sleep(3000); String quickPageURL = driver.getCurrentUrl(); Assert.assertEquals(quickPageURL, "https://www.rodanandfields.com/ca/quick-shop/quickShop"); CAPage.productsDropDown(); CAPage.priceDropDown(); String RedefineText = driver.findElement(By.xpath(".//*[@id='quick-filtered']/ul[2]/li[1]/form/label")).getText(); String ReverseText = driver.findElement(By.xpath(".//*[@id='quick-filtered']/ul[2]/li[2]/form/label")).getText(); Assert.assertEquals(RedefineText, "REDEFINE"); Assert.assertEquals(ReverseText, "REVERSE"); String ProductPrice = driver.findElement(By.xpath(".//*[@id='main-content']/div[5]/div[1]/p/span")).getText(); System.out.println(ProductPrice); for(int i=0; i<ProductPrice.length(); i++) if( ProductPrice.charAt(i) > 47 && ProductPrice.charAt(i) < 58) System.out.print(ProductPrice.charAt(i)); } } <file_sep>#Fri Sep 02 11:34:41 IST 2016 org.eclipse.core.runtime=2 org.eclipse.platform=4.6.0.v20160525-2000
1c1f4093a45c92590730f2d5d923f7a4f2764cc4
[ "Java", "INI" ]
2
Java
2shantanu/Shubham
a7bfd4a8503e595bf1e3cd95a6eb8aa45531161d
8f3daf4cc9fb69d536d902c3b817cf4980a136d9
refs/heads/master
<file_sep>var vm = new Vue({ el: '#example', data: { showWordIndex: null, times: [ {'hour':'12','minute':'00','type':'AM'}, {'hour':'12','minute':'30','type':'AM'}, {'hour':'1','minute':'00','type':'AM'}, {'hour':'1','minute':'30','type':'AM'}, {'hour':'2','minute':'00','type':'AM'}, {'hour':'2','minute':'30','type':'AM'}, {'hour':'3','minute':'00','type':'AM'}, {'hour':'3','minute':'30','type':'AM'}, {'hour':'4','minute':'00','type':'AM'}, {'hour':'4','minute':'30','type':'AM'}, {'hour':'5','minute':'00','type':'AM'}, {'hour':'5','minute':'30','type':'AM'}, {'hour':'6','minute':'00','type':'AM'}, {'hour':'6','minute':'30','type':'AM'}, {'hour':'7','minute':'00','type':'AM'}, {'hour':'7','minute':'30','type':'AM'}, {'hour':'8','minute':'00','type':'AM'}, {'hour':'8','minute':'30','type':'AM'}, {'hour':'9','minute':'00','type':'AM'}, {'hour':'9','minute':'30','type':'AM'}, {'hour':'10','minute':'00','type':'AM'}, {'hour':'10','minute':'30','type':'AM'}, {'hour':'11','minute':'00','type':'AM'}, {'hour':'11','minute':'30','type':'AM'}, {'hour':'12','minute':'00','type':'PM'}, {'hour':'12','minute':'30','type':'PM'}, {'hour':'1','minute':'00','type':'PM'}, {'hour':'1','minute':'30','type':'PM'}, {'hour':'2','minute':'00','type':'PM'}, {'hour':'2','minute':'30','type':'PM'}, {'hour':'3','minute':'00','type':'PM'}, {'hour':'3','minute':'30','type':'PM'}, {'hour':'4','minute':'00','type':'PM'}, {'hour':'4','minute':'30','type':'PM'}, {'hour':'5','minute':'00','type':'PM'}, {'hour':'5','minute':'30','type':'PM'}, {'hour':'6','minute':'00','type':'PM'}, {'hour':'6','minute':'30','type':'PM'}, {'hour':'7','minute':'00','type':'PM'}, {'hour':'7','minute':'30','type':'PM'}, {'hour':'8','minute':'00','type':'PM'}, {'hour':'8','minute':'30','type':'PM'}, {'hour':'9','minute':'00','type':'PM'}, {'hour':'9','minute':'30','type':'PM'}, {'hour':'10','minute':'00','type':'PM'}, {'hour':'10','minute':'30','type':'PM'}, {'hour':'11','minute':'00','type':'PM'}, {'hour':'11','minute':'30','type':'PM'}, ], active: false, timeData: {}, startTime: {}, startTimeString: '', endTime: '', eventLabel: '', eventMessage:'', }, methods: { openModal: function(time,index){ vm.startTime.hour = time.hour; vm.startTime.minute = time.minute; vm.startTime.type = time.type; vm.startTimeString=time.hour+':'+time.minute+' '+time.type; }, saveTime: function() { if(vm.eventLabel === '') vm.eventLabel = '(No title)' vm.eventMessage = vm.eventLabel+'-'+vm.startTimeString+'-'+vm.endTime; } } }); $(document).ready(function(){ $('#startTime').mdtimepicker({ readOnly:true, theme:'indigo', format:'h:mm tt' }); $('#startTime').mdtimepicker().on('timechanged', function(e){ vm.startTimeString = e.value; }); $('#endTime').mdtimepicker({ readOnly:true, theme:'indigo', format:'h:mm tt' }); $('#endTime').mdtimepicker().on('timechanged', function(e){ vm.endTime = e.value }); }); <file_sep># catchthatbus Assignment for catch that bus Download or clone the repository Open the project files in command prompt Type in "npm install" to install all the dependencies. Open the index.html file directly in chrome browser
ab38ff20c26c9612b78c376d75968af1dfd43fd0
[ "JavaScript", "Markdown" ]
2
JavaScript
raza125/catchthatbus
f68e655681df59ac65bbbefb5115b52bf2054dc4
e8cd8842ac855adac3c56d75f91ad95e4aab3eb7
refs/heads/master
<repo_name>bertinatto/dotfiles<file_sep>/bin/dualmon.sh #!/bin/sh INTERN=LVDS1 EXTERN=HDMI1 LIDFILE=/proc/acpi/button/lid/LID/state function intern_is_on() { if grep open "$LIDFILE"; then return 0 # true else return 1 # false fi } function extern_is_on() { if xrandr | grep "$EXTERN connected"; then return 0 # true else return 1 # false fi } function main() { if extern_is_on; then if intern_is_on; then xrandr --output "$INTERN" --primary --auto xrandr --output "$EXTERN" --left-of "$INTERN" --auto else xrandr --output "$INTERN" --off xrandr --output "$EXTERN" --left-of "$INTERN" --auto fi else xrandr --output "$EXTERN" --off xrandr --output "$INTERN" --primary --auto fi } #main xrandr --output eDP-1 --primary --auto setxkbmap -option caps:swapescape <file_sep>/README.md dotfiles ======== A man without his dotfiles is like a ship without a sail.<file_sep>/bash_profile export EDITOR="nvim -f" export MANPAGER="less -X"; export BROWSER="firefox" export GOPATH=$HOME export PATH="${PATH}:${HOME}/bin" export PATH="$HOME/.cargo/bin:$PATH" export LIBVIRT_DEFAULT_URI="qemu:///system" export PIPSI_BIN_DIR="${HOME}/bin" <file_sep>/initialize.sh #!/bin/bash # Get the directory this script lives in dir="$(cd "${0%/*}" && pwd -P)" link_dir() { for file in $(find $dir/$1 -maxdepth 1 -type f \ ! -regex ".*\(MAPPING\|initialize.sh\|.git\|README.md\|urxvt-scripts\)" \ -printf '%P\n') do # Check if we got a custom mapping DEST=$(grep "^$file " $dir/MAPPING | cut -d ' ' -f 2-) if [ -z "$DEST" ] then # Standard location: ~/.filename DEST="$HOME/.$file" else # replace ~ with $HOME DEST=${DEST/\~/$HOME} # Ensure the target directory exists mkdir -p "$(dirname "$DEST")" fi # Preserve the file, if it already exists [[ -e "$DEST" && ! -L "$DEST" ]] && { if [ ! -d "$HOME/.configfiles.bak" ] then mkdir -p "$HOME/.configfiles.bak" || exit 1 fi mv "$DEST" "$HOME/.configfiles.bak/" } # Skip the file, if it is already a link #[[ -e "$DEST" && -L "$DEST" ]] && continue [[ -e "$DEST" && -L "$DEST" ]] && rm -f $DEST # Create the symlink echo "Linking $DEST" ln -sf "$dir/$1/$file" "$DEST" done } [ -d "$(hostname)" ] && link_dir "$(hostname)" neovim_plugins () { curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim } link_dir neovim_plugins
97ce0b1cc730b76ae5095497c126df347a79ce29
[ "Markdown", "Shell" ]
4
Shell
bertinatto/dotfiles
bf8f4da097e57d8e8cb756685a0f7c093ca71fd4
ec194b91fd5cda7d04799569251c932cabc0e057
refs/heads/master
<file_sep>package com.qfedu.newhorizon.provider.user; import com.qfedu.newhorizon.common.result.RO; import com.qfedu.newhorizon.domain.user.UserDetail; import com.qfedu.newhorizon.mapper.user.UserDetailMapper; import com.qfedu.newhorizon.service.user.UserDetailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("userDetailServiceProvider") public class UserDetailProvider implements UserDetailService { @Autowired private UserDetailMapper userDetailMapper; @Override public RO save(UserDetail userDetail) { return RO.creat(userDetailMapper.insert(userDetail)); } @Override public UserDetail queryByUid(int uid) { return userDetailMapper.selectByUid(uid); } } <file_sep>package com.qfedu.newhorizon.mapper.news; import com.qfedu.newhorizon.common.result.PageVo; import com.qfedu.newhorizon.domain.news.New; import org.apache.ibatis.annotations.Param; import java.util.List; public interface NewMapper { List<New> selectByType(Integer type); PageVo selectByPage(@Param("page")Integer page,@Param("limit")Integer limit); New selectById(Integer id); }<file_sep>package com.qfedu.newhorizon.controller.user; import com.alibaba.fastjson.JSON; import com.qfedu.newhorizon.common.redis.RedisUtil; import com.qfedu.newhorizon.common.tools.TokenTool; import com.qfedu.newhorizon.domain.user.User; import com.qfedu.newhorizon.domain.user.UserAddr; import com.qfedu.newhorizon.domain.user.UserMain; import com.qfedu.newhorizon.service.user.UserAddrService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; @RestController public class UserAddrController { @Autowired private UserAddrService userAddrService; @Autowired private RedisUtil redisUtil; @RequestMapping("useraddrsave.do") public int save(UserAddr userAddr) { return userAddrService.save(userAddr); } @RequestMapping("useraddrupdate.do") public int update(HttpServletRequest request) { String tokren = TokenTool.getToken(request); String json = (String) redisUtil.get(tokren); User user = JSON.parseObject(json, UserMain.class); UserAddr userAddr = userAddrService.select(user.getUid()); return userAddrService.query(userAddr); } } <file_sep>package com.qfedu.newhorizon.controller.news; import com.qfedu.newhorizon.service.news.NewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; /** *    Create By Mr.Han *        ------ On 2018/9/18 17:04 */ @Controller public class NewsController { @Autowired private NewsService nw; } <file_sep>package com.qfedu.newhorizon.controller.user; import com.qfedu.newhorizon.domain.user.City; import com.qfedu.newhorizon.domain.user.Province; import com.qfedu.newhorizon.service.user.AddressService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.mail.Address; import java.util.List; @RestController public class AddressController { @Autowired private AddressService addressService; @RequestMapping("provincelist.do") public List<Province> queryAll() { return addressService.queryAll(); } @RequestMapping("citylist.do") public List<City> queryCity(int pid) { return addressService.queryByPid(pid); } }
d198f12486d7d3ca9ba251e7be2fa861417972ce
[ "Java" ]
5
Java
xingpenghui/NewHorizon
df003a222b8c28c2e56069f5c64683565c0de547
917931a27cac8d812e5d4c2052e714a30e63cf81
refs/heads/main
<repo_name>YuliiaHordiichuk/Portfolio<file_sep>/gulpfile.js 'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); var pug = require('gulp-pug'); // Portfolio gulp.task('potfolio_scss', () => { return gulp.src('./src/scss/*.scss') .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(concat('index.css')) .pipe(sourcemaps.write()) .pipe(gulp.dest('./build/')); }); gulp.task('portfolio_pug', () => { return gulp.src('./src/pages/*.pug') .pipe(pug({})) .pipe(gulp.dest('./build/')); }); gulp.task('portfolio_assets', () => { return gulp.src('./src/assets/*') .pipe(gulp.dest('./build/assets')); }); // AXIT gulp.task('axit_scss', () => { return gulp.src('./projects/axit/scss/*.scss') .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(concat('index.css')) .pipe(sourcemaps.write()) .pipe(gulp.dest('./build/projects/axit')); }); gulp.task('axit_pug', () => { return gulp.src('./projects/axit/pages/*.pug') .pipe(pug({})) .pipe(gulp.dest('./build/projects/axit')); }); gulp.task('axit_assets', () => { return gulp.src('./projects/axit/assets/*') .pipe(gulp.dest('./build/projects/axit/assets')); }); // DECO gulp.task('deco_scss', () => { return gulp.src('./projects/deco/scss/*.scss') .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(concat('index.css')) .pipe(sourcemaps.write()) .pipe(gulp.dest('./build/projects/deco')); }); gulp.task('deco_pug', () => { return gulp.src('./projects/deco/pages/*.pug') .pipe(pug({})) .pipe(gulp.dest('./build/projects/deco')); }); gulp.task('deco_assets', () => { return gulp.src('./projects/deco/assets/*') .pipe(gulp.dest('./build/projects/deco/assets')); }); gulp.task('watch', function() { gulp.watch('./src/scss/*.scss', gulp.series('potfolio_scss')); gulp.watch('./src/pages/**/*.pug', gulp.series('portfolio_pug')); gulp.watch('./src/assets/*', gulp.series('portfolio_assets')); gulp.watch('./projects/axit/scss/*.scss', gulp.series('axit_scss')); gulp.watch('./projects/axit/pages/**/*.pug', gulp.series('axit_pug')); gulp.watch('./projects/axit/assets/*', gulp.series('axit_assets')); gulp.watch('./projects/deco/scss/*.scss', gulp.series('deco_scss')); gulp.watch('./projects/deco/pages/**/*.pug', gulp.series('deco_pug')); gulp.watch('./projects/deco/assets/*', gulp.series('deco_assets')); }); gulp.task('default', gulp.series( 'potfolio_scss', 'portfolio_pug', 'portfolio_assets', 'axit_scss', 'axit_pug', 'axit_assets', 'deco_scss', 'deco_pug', 'deco_assets', 'watch') );
6bee9becc2a0c6a22e70b5418aee6940fecf59e0
[ "JavaScript" ]
1
JavaScript
YuliiaHordiichuk/Portfolio
f8e39764b9c0e544764b10c6c807ddb9b5e7fa7d
4a47c6e30d3058251138fdb85c79b489185d3a64
refs/heads/master
<repo_name>joshspicer/HexColors<file_sep>/README.md # HexColors HexColor is a simple iOS application written in Swift, written to introduce me to iOS development! <br><br> The user is provided multiple ways to manipulate 3 integer values representing an RGB color. The color entered (either by sliders or by number) is then displayed as the background of the app. <br><br> This was built out of necessity and curiousity while working on a graphics project. I thought an app like this would be useful to quickly test color combos. Similar apps on the App Store were paid, which inspired me to see if I could write such an application myself! <img src="HexColors/sliders.png" width="500"> <img src="HexColors/numpad.png" width="500"> <file_sep>/HexColors/HexColors/ViewController.swift // // ViewController.swift // HexColors // // Created by <NAME> on 8/24/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { // UI Slider outlets @IBOutlet weak var redSlider: UISlider! @IBOutlet weak var greenSlider: UISlider! @IBOutlet weak var blueSlider: UISlider! @IBOutlet var bg: UIView! // Number outlets @IBOutlet weak var redNum: UITextField! @IBOutlet weak var greenNum: UITextField! @IBOutlet weak var blueNum: UITextField! // RGB variables var red: CGFloat! = 255 var green: CGFloat! = 255 var blue: CGFloat! = 255 // Slider Actions @IBAction func redValueChanged(_ sender: UISlider) { red = CGFloat(redSlider.value) redNum.text = "\(Int(red))" updateAll() } @IBAction func greenValueChanged(_ sender: UISlider) { green = CGFloat(greenSlider.value) greenNum.text = "\(Int(green))" updateAll() } @IBAction func blueValueChanged(_ sender: UISlider) { blue = CGFloat(blueSlider.value) blueNum.text = "\(Int(blue))" updateAll() } // Number boxes actions @IBAction func rLabel(_ sender: UITextField) { print("before \(red)") if let label = Double(sender.text!) { red = checkRange(tempValue: CGFloat(label)) sender.text = "\(Int(red))" updateAll() } print("after \(red)") } @IBAction func gLabel(_ sender: UITextField) { if let label = Double(sender.text!) { green = checkRange(tempValue: CGFloat(label)) sender.text = "\(Int(green))" updateAll() } } @IBAction func bLabel(_ sender: UITextField) { if let label = Double(sender.text!) { blue = checkRange(tempValue: CGFloat(label)) sender.text = "\(Int(blue))" updateAll() } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // If you tap somewhere on the screen the number pad goes away! self.view.endEditing(true) // If user selects an number and leaves it blank, restore previous value. if(redNum.text == "") { redNum.text = "\(Int(red))" } if(greenNum.text == "") { greenNum.text = "\(Int(green))" } if(blueNum.text == "") { blueNum.text = "\(Int(blue))" } } override func viewDidLoad() { super.viewDidLoad() updateAll() } // If a change is made in one place, reflect that change everywhere func updateAll() { bg.backgroundColor = UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1) redSlider.value = Float(red) greenSlider.value = Float(green) blueSlider.value = Float(blue) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Makes sure number entered is correct func checkRange(tempValue:CGFloat) -> CGFloat { if tempValue < CGFloat(0) { return 0 } if tempValue > CGFloat(255.0) { return 255 } return tempValue } }
957ff04f5a928ea2abf022b15f0a78a2b1239d6e
[ "Markdown", "Swift" ]
2
Markdown
joshspicer/HexColors
5670a0e3bf7c401250bdda85506cff7f7c6d6227
9f0bbfec9a5a71552ffd0d28d65c2c377ebb92cf
refs/heads/master
<file_sep> <div class="slidewrap"> <div id="slider"> <div class="slide slides" style="height: 310px;"> <img src="/images/sc1.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 1;"> <img src="/images/ow1.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc2.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/ow2.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc3.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/ow3.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc4.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc5.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc6.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <div class="directionNav"> <a class="prevNav direction" id="prevbutton" onclick="carouselclick(-1)"></a> <a class="nextNav direction" onclick="carouselclick(+1)"></a> <div class="jumps"> <a class="jumpNav" onclick="carouselskip(1)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(2)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(3)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> <a class="jumpNav" onclick="carouselskip(4)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(5)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(6)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> <a class="jumpNav" onclick="carouselskip(7)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(8)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(9)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> </div> </div> </div> </div> </div> <div class="contentwrap"> <div class="sectionwrap" id="drizzt"> <div class="textwrap"> <h1>Drizzt Do'Urden Books</h1> <p>A great line of books written by <NAME> set in the Forgotten Realms universe. These books are about a Dark Elf who leaves the evil ways of his kin behind.</p> <p>They are really inspiration books based on individual struggle and freedom. While they aren't a social commentry they do reflect quite a lot on the problems in modern society such as discrimination and judging people, they are adventure books at heart.</p> <p>I'm trying not to say too much that might be spoliers in case anyone who hasn't read the series decides to read it, but it goes through Drizzt's struggles, as part as the Drow society which he strongly disagres with, when hes alone and when he finds a group of friends of all races who actually accept him for who he is instead of looking at him for the colour of his skin and the misdeeds of other members of his race.</p> <p>There are currently 33 books in the series and likely more coming.</p> </div> <div class="imagewrap"> <img src="/images/Fantasy-Novel-The-Crystal-Shard.jpg" /> </div> </div> <div class="sectionwrap" id="belgarion"> <div class="textwrap"> <h1>The Belgariad and The Malloreon</h1> <p>Two series of books from <NAME>, these are outstanding fantasy books which combine some of the best characters I've ever seen in fantasy books.</p> <p>They not only combine some great characters but also engage in politics, combat and writing. What makes these books so special is how real the characters feel, they have very real individual characters that continue to evolve as the characters continue their journey.</p> <p>Some of the major themes of these books are responsiblity and growing into your responsibilities and accepting them, which makes them great reading for younger people in particular.</p> <p>Both of the two series are five book long and well worth a read.</p> </div> <div class="imagewrap"> <img src="/images/2e4f23a4149e23c297087e37a769330e--book-images-anime-style.jpg" /> </div> </div> <div class="sectionwrap" id="discworld"> <div class="textwrap"> <h1>Discworld</h1> <p>I'm sure everyone has at least heard of the Discworld series. Set in a a satrical fantasy universe which is a flat earth carried on the back on four elephants which rides on the back of a giant turtle swimming through space.</p> <p>I love these books for <NAME>'s writing style. His characters are extremely humourous and full of life and in a world which is just as silly althrough sometimes it seems out to get them.</p> <p>There are several main characters in the various books:</p> <p>Rincewind - A wizard so inept that it is said when he dies, the average magical ability of the human race, which is basically zero, will increase on his death.</p> <p>The Witches - <NAME> and <NAME> are the two main witches of a small mountain town.</p> <p>Death - The grim reaper himself is the main character in quite a few novels, with his horse Binky.</p> <p><NAME> and the City Watch - The brave members of the Ankh-Morpork city watch (or not so brave in a few cases) as they seek to maintain some sembelence of order in Ankh-Morpork.</p> </div> <div class="imagewrap"> <img src="/images/original.jpg" /> </div> </div> <div class="sectionwrap" id="wildcards"> <div class="textwrap"> <h1>Wildcards</h1> <p>These books are very good series of book written by a whole series of collaborating authours edited by <NAME> and <NAME></p> <p>Many excellent authors have contributed to these books, I think this the fact that each of the authors have written just a few characters who can concentrate on each charcter gives them a lot of personality.</p> <p>Its basically very similar to a Marvel universe and is based on Superheros and Villians, althrough its a much more realistic universe than the marvel universe and has a greater degree of consistancy.</p> <p>It actually started as a roleplay game between several writers (<NAME>, Milan, <NAME>, <NAME> and <NAME>) with <NAME> as the games master.</p> <p>As a warning, it is very no-holds barred and features very adult concepts in many places. It does not shy away from any topic at all.</p> </div> <div class="imagewrap"> <img src="/images/Wild-Cards-625x350.jpg" /> </div> </div> <div class="sectionwrap" id="forgotten"> <div class="textwrap"> <h1>Forgotten Realms</h1> <p>The Forgotten Realms is a game world origionally created for the AD&amp;D roleplay game, but has since spawned hundreds of novels creating a vibrant world.</p> <p>Many of the takes have included iconic heroes in the world such as Eleminster, <NAME>, <NAME>, Dragonbait, <NAME>, Khelben "Blackstaff" Arunsun and <NAME>.</p> <p>Because all the books are set in a common universe they share many features and establish common features and locations as well as sharing common deities.</p> </div> <div class="imagewrap"> <img src="/images/821100-www.wallpapersfan.com.jpg" /> </div> </div> <div class="sectionwrap" id="dragonlance"> <div class="textwrap"> <h1>DragonLance</h1> <p>The DragonLance novels are novels by various different authors set in the DragonLance AD&amp;D universe. Like the forgotten realms novels they are all tied together by common locations and deities as well as a shared history that gives a sence of consistancy.</p> <p>The most famous novels in this series where written by <NAME> althrough many other authors have also written novels also based in the same universe.</p> <p>Some truely fascinating character tie them together, the most famous been the heroes of the Lance including: Tanis Half-Elven, Flint Fireforge, Caramon Majere, Raistlin Majere, Goldmoon, Sturm Brightblade and Tasslehoff Burrfoot</p> <p>Unique to the Dragonlance universe are the race of Kenders who are incapable of feeling fear, are insatibly curious and have an amazing childlike innocence, despite been consantly thieving (they always forget what they have stolen seconds later), which add a slightly more lighthearted tone to often incrediably serious moments.</p> </div> <div class="imagewrap"> <img src="/images/dragonlance_7_by_jprart.jpg" /> </div> </div> <div class="sectionwrap"> <div class="textwrap"> <h1>Others</h1> <p>Some other books/series I have loved over the years</p> <ul> <li>Dragonriders of Pern</li> <li>Lord of the Rings</li> <li>1984</li> <li>Dennis Wheatley Novels - Various</li> </ul> </div> </div> </div> <file_sep><?php abstract class BaseController { protected $urlvalues; protected $action; public function __construct($action, $urlvalues, $action2="", $action3="") { $this->action = $action; $this->urlvalues = $urlvalues; $this->action2 = $action2; $this->action3 = $action3; } public function ExecuteAction() { // echo("EA Action: " . $this->action . " URLVALUES: " . $this->urlvalues . " Action 2: " . $this->action2 . "\n"); return $this->{$this->action}($this->urlvalues, $this->action2, $this->action3); } } ?><file_sep><?php class Interpretor { private $controller; private $action; private $urlvalues; private $action2 = ""; private $action3 = ""; //store the URL values on object creation public function __construct($urlvalues) { $this->urlvalues = $urlvalues; // foreach ($urlvalues as $key => $value){ // echo("Key:" . $key . " Value: " . $value . "\n"); // } if ($this->urlvalues['controller'] == "") { // echo("No controller"); $this->controller = "show"; } //if no controller set in URL, default to show page else { $this->controller = $this->urlvalues['controller']; } if ($this->urlvalues['action'] == "") { // echo("No Action \n"); $this->action = "index"; } // if no action set, default to Index page else { $this->action = $this->urlvalues['action']; // Only want actions 2 and 3 set if action is set. $this->action2 = $this->urlvalues['action2']; $this->action3 = $this->urlvalues['action3']; } } //instantiate the requested controller as an object public function CreateController() { //does the class exist? if (class_exists($this->controller)) { // echo("Controller: " . $this->controller . "\n"); $parents = class_parents($this->controller); //does the class extend the controller class? if (in_array("BaseController",$parents)) { // echo("Action: " . $this->action . "\n"); //does the class contain the requested method? if (method_exists($this->controller,$this->controller)) { return new $this->controller($this->controller, $this->action, $this->action2, $this->action3); } //for this app, the controller and the action always have the same name else { // echo("Method does not exist"); return new $this->controller('show', '404'); } } else { // echo("Not in array \n"); return new $this->controller('show', '404'); } } else { // echo("Controller not found \n"); return new show('show', '404'); } //If anything isn't set right, return the 404 page } } ?><file_sep> <div class="slidewrap"> <div id="slider"> <div class="slide slides" style="height: 310px;"> <img src="/images/sc1.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 1;"> <img src="/images/ow1.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc2.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/ow2.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc3.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/ow3.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc4.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc5.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc6.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <div class="directionNav"> <a class="prevNav direction" id="prevbutton" onclick="carouselclick(-1)"></a> <a class="nextNav direction" onclick="carouselclick(+1)"></a> <div class="jumps"> <a class="jumpNav" onclick="carouselskip(1)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(2)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(3)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> <a class="jumpNav" onclick="carouselskip(4)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(5)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(6)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> <a class="jumpNav" onclick="carouselskip(7)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(8)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(9)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> </div> </div> </div> </div> </div> <div class="contentwrap"> <div class="sectionwrap"> <div class="textwrap"> <h1>What this site is about</h1> <p>Basically I decided to put this site together as part of my personal learning project to improve my PHP skills, (mainly with the <a href="/show/guncomparison/">Star Citizen Weapon Comparison Tool</a>)</p> <p>The whole site is a hand written custom MVC framework I've put together, while I could have done it much quicker using an existing MVC framework, I decided to build it from scratch in order to improve my understanding of how MVC frameworks operate from the ground up.</p> <p>The comparison page is actually a bit more complex than it might appear as it has to take into account quite a few factors for each stat it is comparing such as</p> <ul> <li>Is a zero stat representing Infinity (for example ammo)</li> <li>How should it represent multiple mounts? For example having a twin mount does double damage, but doesn't double projectile speed, but does kinda double rate of Fire but not really, so they all need representing and comparing differently.</li> <li>Is lower or higher good? Clearly in terms of damage, higher is better, but in terms of power consumption or heat generation, the less per shot is better!</li> <li>Several of the stats been compared don't actually exist in the source data so have to be calculated on the fly</li> </ul> <p>I've also tried to make the functions expandable for the future, for example the function that puts the comparison array together will accept more than two guns in it's input array and can contain more than two in it's output so later on I can make a seperate screen allowing a different type of comparison to be done comparing more than two selections.</p> <p>You'll have to excuse the graphics as I'm reliant on the free tools at the moment and am not exactly an expert in them, I'm also trying some CSS tricks and working out some CSS bugs to improve my HTML/CSS skills</p> <p>All the animations including the slide-show are done excelusively from css transitions, only the control/timing bits are done in Jquery which just changes classes about</p> <p>The entire site is custom built from hand-coded CMS/HTML/Jquery. No templates or frameworks have been used. The terrible design is entirely my fault :)</p> <p>If you'd like any of bits of code from the site, like the CSS slider, send me an e-mail via the contact page form and I can send you the template I built for it (no cost).</p> <p>Most of this site is based on me and things that I've loved over my 36 (and counting) years going back as far as I remember.</p> <p>Just in case anyone is intrested, I'm currently looking for work (I am currently employed) doing practically anything that is intresting and challenging as I've grown tired of working on CMS/HTML/CSS sites and would like to do something more challenging and rewarding, I'm mainly looking for PHP programming roles in Bournemouth at the moment but would consider anything challenging even if it meant relocating.</p> </div> <div class="imagewrap"> <img src="/images/me.jpg" /> </div> </div> </div><file_sep><?php class gunList extends baseController { public function __construct($action, $urlvalues, $action2="", $action3="") { $this->action = $action; $this->urlvalues = $urlvalues; $this->action2 = $action2; $this->action3 = $action3; } public function gunList() { $db = new Database; $querystring = "select gunid, name, size, maker, mass, rof, ((pdamage+edamage+ddamage)*rof) as dps, (heatpershot*rof/60) as hps, (powerpershot*rof) as pps from Guns"; if ($this ->action3 != "") { $filters = explode(":", $this->action3); $filternumber = 0; foreach($filters as $filter){ $filtervalue = explode("-", $filter); // echo("filter0: " . $filtervalue[0] . " filter1: " . $filtervalue[1] . "\n"); // echo("raw filter: " . $filter . "\n"); if ($filternumber == 0){ $querystring = $querystring . " where "; }else{ //first time needs where, afterwards needs and. $querystring = $querystring . " AND "; } $filternumber++; if (strcmp($filtervalue[0], "minsize") == 0){ // echo("MINSIZE"); $querystring = $querystring . " size >= " . $filtervalue[1]; } if (strcmp($filtervalue[0],"maxsize") == 0){ // echo("MAXSIZE"); $querystring = $querystring . "size <=" . $filtervalue[1]; } if (strcmp($filtervalue[0], "type") == 0){ $querystring = $querystring . "type = " . $filtervalue[1]; } // echo("Query: " . $querystring . "\n"); } } if ($this->action2 != ""){ if ($this->action2 == "dps"){ $querystring = $querystring . " order by ((pdamage+edamage+ddamage)*rof), name"; }elseif ($this->action2 == "hps"){ $querystring = $querystring . " order by (heatpershot*rof), name"; }elseif ($this->action2 == "pps"){ $querystring = $querystring . " order by (powerpershot*rof), name"; } else{ $querystring = $querystring . " order by " . $this->action2 . ",name"; } }else { $querystring = $querystring . " order by name"; } $results = $db -> select($querystring . ";"); if (is_array($results) ){ }else{ echo("<p>Show Urlvalue: " . $urlvalue . " thisurlvalue: " . $this->urlvalues . " thisaction: " . $this->action . "</p>" ); echo("<p>Action2: ". $this->action2 . "</p>"); echo("<p>Action3: ". $this->action3 . "</p>"); echo("<p>Query String: " . $querystring . "</p>"); echo("<p>Results: " . $results . "</p>"); } foreach ($results as $result){ echo("<div class='gunitem'> <h3>" . $result['name'] . "</h3> <p>Size: " . $result['size'] . "<br /> Manufactorer: " . $result['maker'] . "<br /> Mass: " . $result['mass'] . "<br /> DPS: " . $result['dps'] . "<br /> Heat Per Second: " . $result['hps'] . "<br /> Power Per Second: " . $result['pps'] . "</p> <div class='choices'> <div class='choice'><input type='radio' name='" . $this->urlvalues . "' value='" . $result['gunid'] . "-1'><p>Single Mount</p></input></div><br /> <div class='choice'><input type='radio' name='" . $this->urlvalues . "' value='" . $result['gunid'] . "-2'><p>Double Mount</p></input></div><br /> <div class='choice'><input type='radio' name='" . $this->urlvalues . "' value='" . $result['gunid'] . "-4'><p>Quad Mount</p></input></div><br /> </div> </div>"); } } } class gunComp extends baseController { public function __construct($action, $urlvalues) { $this->action = $action; $this->urlvalues = $urlvalues; } public function buildcomps($gunstats) { //Builds lists of stats to be compared as well as establishing needed values for processing // from the database listing of the guns (passed in $gunstats) // built up like this so it can do more than 2 if needed. $comps = array(); // $gun1stats[0]['tdamage'] = $gun1stats[0]['pdamage'] + $gun1stats[0]['edamage'] + $gun1stats[0]['ddamage']; // $gun2stats[0]['tdamage'] = $gun2stats[0]['pdamage'] + $gun2stats[0]['edamage'] + $gun2stats[0]['ddamage']; // Setting up definitions for the comparisons. Too arbitary to automate. $x=0; foreach($gunstats as $gun){ $comps['pspeed']['gun'][$x] = $gun['pspeed']; $x++; } $comps['pspeed']['inverse'] = 0; $comps['pspeed']['name'] = "Projectile Speed"; $comps['pspeed']['showmult'] = 0; /// 0 = No, 1 = Yes 2 = Yes but no Total $comps['pspeed']['zeroinfinite'] = 0; /// 0 = No, 1 = Yes, Mainly for ammo for energy weapons $x=0; foreach($gunstats as $gun){ $comps['pdamage']['gun'][$x] = $gun['pdamage']; $x++; } $comps['pdamage']['inverse'] = 0; $comps['pdamage']['name'] = "Physical Damage"; $comps['pdamage']['showmult'] = 1; $comps['pdamage']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['edamage']['gun'][$x] = $gun['edamage']; $x++; } $comps['edamage']['name'] = "Energy Damage"; $comps['edamage']['showmult']= 1; $comps['edamage']['inverse']= 0; $comps['edamage']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['ddamage']['gun'][$x] = $gun['ddamage']; $x++; } $comps['ddamage']['name'] = "Distortion Damage"; $comps['ddamage']['showmult'] = 1; $comps['ddamage']['inverse'] = 0; $comps['ddamage']['zeroinfinite'] = 0; $comps['tdamage']['name'] = "Total Damage"; $comps['tdamage']['showmult'] = 1; $comps['tdamage']['inverse'] = 0; $comps['tdamage']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['tdamage']['gun'][$x] = $gun['pdamage'] + $gun['edamage'] + $gun['ddamage']; $x++; } $comps['rof']['name'] = "Rate of Fire"; $comps['rof']['showmult'] = 2; $comps['rof']['inverse'] = 0; $x=0; foreach($gunstats as $gun){ $comps['rof']['gun'][$x] = $gun['rof']; $x++; } $comps['rof']['zeroinfinite'] = 0; $comps['dps']['name'] = "Damage per second"; $comps['dps']['showmult'] = 1; $comps['dps']['inverse'] = 0; $comps['dps']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['dps']['gun'][$x] = $comps['tdamage']['gun'][$x] * $comps['rof']['gun'][$x] /60; $x++; } $comps['projspeed']['name'] = "Projectile Speed"; $comps['projspeed']['showmult'] = 0; $comps['projspeed']['inverse'] = 0; $comps['projspeed']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['projspeed']['gun'][$x] = $gun['pspeed']; $x++; } $comps['maxrange']['name'] = "Max Range"; $comps['maxrange']['showmult'] = 0; $comps['maxrange']['inverse'] = 0; $comps['maxrange']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['maxrange']['gun'][$x] = $gun['maxrange']; $x++; } $comps['ammo']['name'] = "Ammo"; $comps['ammo']['showmult'] = 2; $comps['ammo']['inverse'] = 0; $comps['ammo']['zeroinfinite'] = 1; $x=0; foreach($gunstats as $gun){ $comps['ammo']['gun'][$x] = $gun['ammocount']; $x++; } $comps['mass']['name'] = "Total Weapon Mass"; $comps['mass']['showmult'] = 1; $comps['mass']['inverse'] = 1; $comps['mass']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['mass']['gun'][$x] = $gun['mass']; $x++; } $comps['hp']['name'] = "Hitpoints"; $comps['hp']['showmult'] = 1; $comps['hp']['inverse'] = 0; $comps['hp']['zeroinfinite'] = 0; $x=0; foreach($gunstats as $gun){ $comps['hp']['gun'][$x] = $gun['hp']; $x++; } return($comps); } private function comparestat($gun1stat, $gun2stat, $inverse, $zeroinfinite){ //inverse is where lower is better, so tilt bar towards lower value instead of higher. 0 = higher is better, 1 = lower is better if ($gun1stat+$gun2stat != 0){ //Both could be zero so avoid divide by zero error if ($zeroinfinite != 1){ $comp = $gun1stat / ($gun1stat+$gun2stat); if ($inverse == 1){ $comp = 1 - $comp; } }else{ if (($gun1stat == 0) && ($gun2stat == 0)){ $comp = 0.5; }elseif ($gun1stat == 0) { $comp = 1; }elseif ($gun2stat == 0){ $comp = 0; }else{ $comp = $gun1stat / ($gun1stat+$gun2stat); if ($inverse == 1){ $comp = 1 - $comp; } } } }else { $comp = 0.5; //If both are zero set the comparison to middle. } return($comp * 100); // Coverts 0 to 1 value to % } public function gunComp() { // echo("Show Urlvalue: " . $urlvalue . " thisurlvalue: " . $this->urlvalues . " thisaction: " . $this->action . "\n" ); // Action format should be gun1id-multiple:gun2id-multiple $db = new Database; $gun1 = substr($this->urlvalues, 0, strpos($this->urlvalues, ":")); $gun2 = substr($this->urlvalues, strpos($this->urlvalues, ":")+1); // echo("\n Gun 1: " . $gun1 . " Gun 2: " . $gun2 . "\n"); $gun1id = substr($gun1, 0, strpos($gun1, "-")); $gun1mult = substr($gun1, strpos($gun1, "-")+1); $gun2id = substr($gun2, 0, strpos($gun2, "-")); $gun2mult = substr($gun2, strpos($gun2, "-")+1); $gun1stats = $db -> select("select * from Guns where gunid = " . $gun1id . ";"); $gun2stats = $db -> select("select * from Guns where gunid = " . $gun2id . ";"); $guns[0] = $gun1stats[0]; $guns[1] = $gun2stats[0]; $comps = $this->buildcomps($guns); $gunhead = '<div class="comp"><div class="compsec"><div class="leftsec"><h3>' . $gun1stats[0]['name']; if ($gun1mult != 1) { $gunhead = $gunhead . " X" . $gun1mult; } $gunhead = $gunhead . '</h3></div><div class="midsec"></div><div class="rightsec"><h3>' . $gun2stats[0]['name']; if ($gun2mult != 1) { $gunhead = $gunhead . " X" . $gun2mult; } $gunhead = $gunhead . '</h3></div></div> '; echo $gunhead; //Should rework this bit to be a view and just pass values to it, but meh :) Maybe later foreach ($comps as $key => $value){ if ($value['showmult'] != 1){ $value['value'] = $this->comparestat($value['gun'][0], $value['gun'][1], $value['inverse'], $value['zeroinfinite']); }else { $value['value'] = $this->comparestat($value['gun'][0]*$gun1mult, $value['gun'][1]*$gun2mult, $value['inverse'], $value['zeroinfinite']); } echo('<div class="compsec"><div class="statname"><h3>' . $value['name'] . '</div>'); $gunstats = '<div class="leftsec"><h4>'; if (($value['zeroinfinite'] == 1) && ($value['gun'][0] == 0)){ $stat = "Infinite"; }else{ $stat = number_format($value['gun'][0], 2); } $gunstats = $gunstats . $stat; if (($gun1mult != 1) && ($value['showmult'] >= 1 )) { $gunstats = $gunstats . " X" . $gun1mult; if ($value['showmult'] == 1) { $gunstats = $gunstats . " (" . number_format($value['gun'][0]*$gun1mult, 2) . ")"; } } $gunstats = $gunstats . '</h4></div> <div class="midsec"><div class="midsecinner"><div class="leftbar" style="width:' . $value['value'] . '%"></div><div class="marker" style="left:' . $value['value'] . '%"></div><div class="rightbar" style="width:' . (100 - $value['value']) . '%"></div></div></div> <div class="rightsec"><h4>'; if (($value['zeroinfinite'] == 1) && ($value['gun'][1] == 0)){ $stat = "Infinite"; }else{ $stat = number_format($value['gun'][1], 2); } $gunstats = $gunstats . $stat; if ($gun2mult != 1 && $value['showmult'] >= 1) { $gunstats = $gunstats . " X" . $gun2mult; if ($value['showmult'] == 1) { $gunstats = $gunstats . " (" . number_format($value['gun'][1]*$gun2mult, 2) . ")"; } } $gunstats = $gunstats . '</h4></div></div>'; echo($gunstats); } echo('</div>'); } } ?><file_sep><?php /* Author <NAME> Basic Function allocater */ ini_set('display_errors',1); error_reporting(E_ALL); require("helperclasses/Interpreter.php"); require("helperclasses/MainController.php"); require("controllers/template.php"); require("models/static.php"); require("models/guncomp.php"); require("models/contact.php"); require_once("helperclasses/database.php"); $interpreter = new Interpretor($_GET); //foreach($_GET as $key => $value){ //echo($key . ": " . $value . "\n" ); //} $controller = $interpreter->CreateController(); $controller->ExecuteAction(); ?> <file_sep>$(document).ready(function() { $val1 = Math.floor((Math.random() * 10 ) + 1); $val2 = Math.floor((Math.random() * 10 ) + 1); $('input[name="antispam1"]').val($val1); $('input[name="antispam2"]').val($val2); $('.antispam1').text($val1); $('.antispam2').text($val2); $(".comparebutton").click(function(){ var comp1 = $("input:radio[name = 'left']:checked").val(); var comp2 = $("input:radio[name = 'right']:checked").val(); if ((comp1 == undefined) || (comp2 == undefined)){ alert("You need to select a gun from each column to compare! \n\n The website may be good but its not psychic!"); }else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200){ document.getElementById("comparebox").innerHTML = this.responseText; } } } xmlhttp.open("GET", "/guncomp/" + comp1 + ":" + comp2, true); xmlhttp.send(); }); $(".minsize, .maxsize, .selecttype, .guiderating, .sortby").change(function(){ var xmlhttp = new XMLHttpRequest(); var side; if($(this).parent().parent().is("#leftfilters")){ side="left"; } if($(this).parent().parent().is("#rightfilters")){ side="right"; } var sortstring = $(this).parent().parent().find('select.sortby').val(); typestring = ''; guidestring = ''; querystring = "minsize-"+ $(this).parent().parent().find('select.minsize').val(); querystring2 = ":maxsize-"+ $(this).parent().parent().find('select.maxsize').val(); querystring = querystring + querystring2; querystring2 = $(this).parent().parent().find('select.selecttype').val(); if (querystring2 != "1||2||3"){ querystring = querystring + ":type-" + querystring2; } xmlhttp.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200){ if(side == "left"){ document.getElementById("leftlist").innerHTML = this.responseText; } if(side == "right"){ document.getElementById("rightlist").innerHTML = this.responseText; } } }; // teststring = "/gunList/" + side + "/" + sortstring + "/" + querystring; // alert(teststring); xmlhttp.open("GET", "/gunList/" + side + "/" + sortstring + "/" + querystring, true); xmlhttp.send(); return xmlhttp; }); }); function loadDoc1(){ var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200){ document.getElementById("leftlist").innerHTML = this.responseText; } }; xmlhttp.open("GET", "/gunList/left", true); xmlhttp.send(); return xmlhttp; } function loadDoc2(){ var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200){ document.getElementById("rightlist").innerHTML = this.responseText; } }; xmlhttp.open("GET", "/gunList/right", true); xmlhttp.send(); return xmlhttp; } <file_sep><?php class Show extends BaseController { public function __construct($action, $urlvalues, $action2 = "", $action3 = "") { $this->action = $action; $this->urlvalues = $urlvalues; $this->action2 = $action2; $this->action3 = $action3; } private function Header($action) { $template= new Template(); $template->file = "views/templates/header.html"; $db = new Database; $querystring = "select * from Pages where url = '" . $action . "';"; // echo($querystring); $results = $db -> select($querystring . ";"); $template->vars = $results[0]; // foreach ($results[0] as $key => $value){ // echo("Key: " . $key . " Value: " . $value . "\n"); // } $template->display(); } private function MainSection($action) { $template= new Template(); $template->file = "views/templates/" . $action . ".html"; $template->display(); } private function Footer() { $template= new Template(); $template->file = "views/templates/footer.html"; $template->display(); } public function Show($urlvalue) { // echo("Show Urlvalue: " . $urlvalue . " thisurlvalue: " . $this->urlvalues . " thisaction: " . $this->action . "\n" ); Show::Header($urlvalue); Show::MainSection($urlvalue); Show::Footer(); } } ?><file_sep>$(document).ready(function() { var slideIndex = 0; var override = 0; var cycle = 49; carousel(); function carousel(n) { //control cycle for slides, run every 1/10 of a second // console.log("Starting"); var i; cycle++; if (cycle == 50 || override == 1) // change cycle to change duration seconds wanted * 10 { // console.log("Cycle: " + cycle + " Override: " + override); cycle = 0; var x = document.getElementsByClassName("mySlides"); for (i = 0; i < x.length; i++) { x[i].style.opacity = "0"; } if (x.length > 0){ if (override == 0){ slideIndex++; cycle = 0;}; // don't progress if this was a click if (slideIndex > x.length) {slideIndex = 1;}; if (slideIndex < 1) {slideIndex = x.length}; x[slideIndex-1].style.opacity = "1"; var jumpicon = "#jump" + slideIndex; // console.log(jumpicon); var y = document.getElementsByClassName("jumpNav"); var i2; for (i2 = 0; i2 < y.length; i2++){ y[i2].style.backgroundColor="#fff"; // console.log("Tried to set colour"); } y[slideIndex-1].style.backgroundColor = "green"; // changetext(slideIndex -1); //used to call an external function when the animation starts running // console.log("Next slide number" + slideIndex); override = 0; } } setTimeout(carousel, 100); // Change image every 2 seconds } window.carouselclick = function(n){ // console.log("Click detected, old slide index: " + slideIndex); override = 1; // this tells the control cycle to exit current sequence, change the image, then reset to 5 seconds slideIndex = slideIndex + n; } window.carouselskip = function(n){ override = 1; slideIndex = n; } $(window).load(function(){ var slideheight = $('.slides img').height(); // console.log("Slideheight: " + slideheight); $(".slide").css("height", slideheight); var overlayheight = $('.slideinner').height(); // overlayheight = overlayheight +15; $(".slideend").css("height", overlayheight ); }); }); $( window ).resize(function() { // console.log('test: ' + testme()); var slideheight = $('.slides img').height(); $(".slide").css("height", slideheight); var overlayheight = $('.slideinner').height(); // overlayheight = overlayheight +15; $(".slideend").css("height", overlayheight ); });<file_sep><?php //Database.php //require_once('config.php'); //Might add config file to pull this in from later class Database { protected static $connection; private function dbConnect() { $databaseName = 'lockeythings'; $serverName = 'localhost'; $databaseUser = 'lockey'; $databasePassword = '<PASSWORD>'; $databasePort = '3306'; // Not actual details! Placeholders! Leave my DB alone! :) self::$connection = mysqli_connect ($serverName, $databaseUser, $databasePassword, '<PASSWORD>'); // mysqli_set_charset('utf-8',self::$connection); if (self::$connection) { if (!mysqli_select_db (self::$connection, $databaseName)) { echo("DB Not Found"); throw new Exception('DB Not found'); } } else { echo("No DB connection"); throw new Exception('No DB Connection'); } return self::$connection; } public function query($query) { // Connect to the database $connection = $this -> dbConnect(); // Query the database $result = mysqli_query($connection, $query); return $result; } public function select($query) { $rows = array(); $result = $this -> query($query); if($result === false) { return false; } while ($row = $result -> fetch_assoc()) { $rows[] = $row; } // echo("should have worked"); return $rows; } } ?> <file_sep><?php class Template { public $file; public $vars=array(); public function set($key, $value) { $this->vars[$key] = $value; } public function display() { try { if(file_exists($this->file)) { $output = file_get_contents($this->file); } else { // echo("Trying to get: " . $this->file . "\n"); $this->$vars['title'] = 'Page not found'; $this->$vars['description'] = 'This page was not found!'; $output = file_get_contents("views/templates/404.html"); } foreach ($this->vars as $key => $value){ // echo("Key: " . $key . " Value: " . $value . "\n"); $entry = "/{" . $key . "}/"; // echo("Entry: " . $entry . "\n" ); $output = preg_replace($entry, $value, $output); } echo $output; } catch (Exception $e) { echo "Exception caught: " . $e->getMessage(); } } } ?><file_sep> <div class="slidewrap"> <div id="slider"> <div class="slide slides" style="height: 310px;"> <img src="/images/sc1.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 1;"> <img src="/images/ow1.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc2.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/ow2.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc3.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/ow3.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc4.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc5.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <img src="/images/sc6.jpg" alt="" width="1280" height="500" class="mySlides" style="opacity: 0;"> <div class="directionNav"> <a class="prevNav direction" id="prevbutton" onclick="carouselclick(-1)"></a> <a class="nextNav direction" onclick="carouselclick(+1)"></a> <div class="jumps"> <a class="jumpNav" onclick="carouselskip(1)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(2)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(3)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> <a class="jumpNav" onclick="carouselskip(4)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(5)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(6)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> <a class="jumpNav" onclick="carouselskip(7)" id="jump1" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(8)" id="jump2" style="background-color: rgb(255, 255, 255);"></a> <a class="jumpNav" onclick="carouselskip(9)" id="jump3" style="background-color: rgb(255, 255, 255)"></a> </div> </div> </div> </div> <div class="contentwrap"> <div class="sectionwrap" id="st"> <div class="textwrap"> <h1>Roleplaying</h1> <p>Roleplay is basically exactly what the word says, you play a role.</p> <p>This comes in many forms, but is mainly done either on tabletop (AD&amp;D for example) or Live.</p> </div> </div> <div class="sectionwrap"> <div class="textwrap"> <h1>Tabletop</h1> <p>In tabletop roleplay, you have 1 Gamesmaster(GM) and a group of players (3-6 normally) who each make characters or use characters defined by the GM.</p> <p>In this format, the GM is basically God of the universe in question and controls everything and everyone who is not one of the players, althrough it does to some degree also cover the players such as involuntary actions or anything else out of a character's direct control, fear been a good example of this</p> <p>Generally the players will build their own characters but sometimes the GM will provide them based on that particular game's rules which can vary from cavemen, WW1/WW2, Fantasy/Superhero or Sci-Fi or well, anything else you can think of. Almost every senario has been covered in various books and if it doesn't exist, there is nothing stopping you creating rules for it! There is even a book covering how to play a game as rabbits! (Bunnies and Burrows.... Its true, honest!)</p> <p>The "stats" of each character let the players know what their characters are capable of and how much they can do, but in all honesty the player's imagination is a much greater factor in been successful, althrough there is no real 'winning' in Roleplay, certainly not over the other players (in general), its more about co-operation and acting like your character would, althrough some characters do come into conflict, this is just part of the game rather than the goal of it.</p> <p>Its very much about the personality of each characters and staying "in role", hence the name, the point is to make your character act like they should in any given situation which can lead to very intresting (and amusing) adventures.</p> </div> <div class="imagewrap"> <img src="/images/Role-Playing-Session.jpg" /> </div> </div> <div class="sectionwrap"> <div class="textwrap"> <h1>Live Roleplay</h1> <p>Live roleplay is a little more 'fixed' than tabletop as you are constrained by reality to some degree.</p> <p>The basic concept is the same as tabletop roleplay, the main difference is that the players all get in costume and actually act out what they are doing instead of just describing it to the GM and rolling dice.</p> <p>Clearly this does mean you can't easily play a superhero who can leap 60' into the air or similar and hitting other players with real swords/axes is also generally frowned upon!, so there are rules to cover this and allow these sorts of actions which can vary to replacing these contests with Rock/Paper/Sissors or fighting with Latex weapons so as not to injury anyone.</p> <p>The Gathering is the major live roleplay event and happens in the UK once a year where thousands of people gather together at a single event althrough there are many smaller events held every year.</p> </div> <div class="imagewrap"> <img src="/images/battle1_Renewal_06.jpg" /> </div> </div> </div> </div>
52dafd4750d29d79697a8aa1c7860520ed2d0958
[ "JavaScript", "HTML", "PHP" ]
12
HTML
drenzul/lockeythings
9c1e0e69e8c624e291bd49372f60287daaa45c05
3e3006fec3753ce6d8b30147c9a5b20184057611
refs/heads/main
<file_sep>// import logo from './cool.png'; import { useState } from 'react' function App() { const [coolInput, setCoolInput] = useState() return ( <div className="flex flex-col w-screen h-screen justify-center"> <div className="self-center justify-center"> <img src="./cool.png" className="w-80 text-center " alt="logo" /> </div> <div className="text-center "> <p className="mb-4 text-gray-500">Skriv noget sejt</p> <input className="text-2xl border-b outline-none mb-4 " value={coolInput} onChange={(e) => setCoolInput(e.target.value)} /> </div> <p> {coolInput && coolInput !== "" && <p className="text-5xl font-extrabold text-center">Det er for vildt.. <span className="text-yellow-600">{coolInput}!!!</span></p>} </p> </div> ); } export default App;
43c0a085f8ce8194467dc56cacce43853e549ec7
[ "JavaScript" ]
1
JavaScript
mugpet/mtj-app
c3860a921c7f3a89863cf1367ee8509a2154501e
39e1d363442605b6bbe4cc5c1a051de7b651ea12
refs/heads/master
<file_sep># TEMPLATES **This repo contains diffrents foundation templates for starting web projects.** ## The templates - **.gitignore** Base gitignore template - **html.html** HTML base - **css.css** CSS base - **js.js** JavaScript base - **php.php** PHP base --- - **basic** Ultra basic template with index.html, css and js files. Ready to code !<file_sep><?php // PHP entry point phpinfo()
46e41bb8caa8bbb495a4cc837203d87b2c745c1f
[ "Markdown", "PHP" ]
2
Markdown
fuzoh/templates
f1e5caf32fd7dff6c679744fae9dd627a3ab57cc
2404ad2ccf380e94559f044b1fcea3b78f36125b
refs/heads/master
<file_sep><?php /* Plugin Name: Msv Woo Cart Optimization Plugin URI: http://chessmsv.ru/%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD-msv-woo-cart-optimization Description: оптимизация корзины интернет магазина, использующего плагин WooCommerce, по методике "Задачи потребителя" Author: <NAME> Version: 1.0.0 Author: http://chessmsv.ru/ */ /* Copyright 2019 <NAME> (email: <EMAIL>) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ if(is_admin() == TRUE){ register_activation_hook(__FILE__, function(){ global $user_ID; wp_insert_post(array( 'post_type' => 'page', 'post_title' => 'Оптимизация корзины', 'comment_status' => 'closed', 'post_status' => 'publish', 'ping_status' => 'closed', 'post_author' => $user_ID, 'post_name' => 'cart-in-cart', )); }); } require __DIR__.'/functions.php'; add_action('wp_enqueue_scripts','msv_cartoptimization_scripts'); register_activation_hook(__FILE__,'cartoptimization_install'); register_deactivation_hook(__FILE__,'cartoptimization_uninstall'); register_uninstall_hook(__FILE__,'cartoptimization_ondelete'); //add_action('admin_menu','cartoptimization_admin_menu'); // Включаем код для отладки и определяем объект require_once("PHPDebug.php"); //add_action('woocommerce_cart_contents', 'msv_add_button'); add_filter('the_content', 'pagesearch'); add_filter('the_content', 'msv_add_button'); add_action( 'wp_ajax_msvCart', 'newproducts_function' ); // wp_ajax_{ЗНАЧЕНИЕ ПАРАМЕТРА ACTION!!} add_action( 'wp_ajax_nopriv_msvCart', 'newproducts_function' ); // wp_ajax_{ЗНАЧЕНИЕ ПАРАМЕТРА ACTION!!} <file_sep># woo-cart-optimization ## Woo Cart Optimization Plugin ### Files |Name|Description| |------|------| |function.php|php file for plugin| |msv-woo-cart-optimization.php|php file for plugin| |css|style file for plugin| <file_sep>//цены товаров function arrPrice(selected_products) { var task_prices = []; jQuery.each(selected_products, function( key, value ) { task_prices.push(value.price); }); return task_prices; } //ID товаров function arrId(selected_products) { var task_prices = []; jQuery.each(selected_products, function( key, value ) { task_prices.push(value.id); }); return task_prices; } //скалярное произведение двух векторов function totalMultiple(arrPrice, arrCount){ if(!arrPrice.length) return; var res = 0; for(var i = 0; i < arrPrice.length; i++){ res += arrPrice[i] * arrCount[i]; } return res; }; //Проверка переменной принадлежности интервалу. Не входит -0 function checkProducts(selected_products, product_count){ if(!product_count.length) { return; }pr var key = 1; for(var i=0;i<selected_products.length;i++){ if (product_count[i]<selected_products[i].min_count || product_count[i]>selected_products[i].max_count) { key=0; } } return key; }; //Кэлтэй массив онорор. Все допустимые товары каждого вида. Хас табаар киирэрин. Браузертан ылар function arrCountProducts_for_cart(selected_products){ console.log("UUU selected_products.length="+selected_products.length); var arr= []; for(var i=0;i<selected_products.length;i++){ var lengt_pr=selected_products[i].max_count-selected_products[i].min_count+1; var arr1=[]; for(var j=0;j<lengt_pr;j++){ arr1[j]=parseInt(selected_products[i].min_count)+j; } arr[i]=arr1; console.log("UUU arr[i]="+arr[i]); } return arr; } //Декартово произведение. Массив тахсар. function cartesianProduct(arr){ console.log("Вход в Декарт "+arr); return arr.reduce(function(a,b){ return a.map(function(x){ return b.map(function(y){ return x.concat(y); }) }).reduce(function(a,b){ return a.concat(b) },[]) }, [[]]) } //Фильтрация наборов по бюджету function filterByBudget(selected_products,arrcartez,budget){ var filtered = []; for(var i = 0; i < arrcartez.length; i++){ var obj = arrcartez[i]; if(totalMultiple(arrPrice(selected_products),obj)<=budget){ filtered.push(obj); } } return filtered; } //key = 0 будет по стоимости key = 1 будет по полезности. Интерактивные таблицы буолаллар кэнники function createTable(selected_products, tableData, count, newColumnName, key,count_of_cat_products,arrNameNonFiltered) { let n=0; var table = document.createElement('table'); table.setAttribute("class", "table"); table.setAttribute("id", "tableSelected"+key ); var tableBody = document.createElement('tbody'); var row0=document.createElement('tr'); row0.setAttribute("id", "myTr"); tableBody.appendChild(row0); for(var i=0;i<arrNameNonFiltered.length;i++){ var y = document.createElement("th") y.setAttribute("id", "myTr"+i); var t = document.createTextNode(arrNameNonFiltered[i]); y.appendChild(t); row0.appendChild(y); } //Добавляю цену товаров t = document.createTextNode(newColumnName); var y = document.createElement("th") y.appendChild(t); row0.appendChild(y); tableData.forEach(function(rowData, index) { var row = document.createElement('tr'); row.setAttribute("id", "selectedTr"+key+index); var priceRow; rowData.forEach(function(cellData, index) { var cell = document.createElement('td'); cell.setAttribute("id", "td"+index); cell.appendChild(document.createTextNode(cellData)); row.appendChild(cell); // console.log("Это key = "+key); if(key=="0"){ priceRow=totalMultiple(rowData, arrPrice(selected_products)); //console.log("arrPrice(selected_products) "+arrPrice(selected_products)); } if(key=="1"){ //console.log("key 2 arrPreference=",selectedPreferenceProducts(selected_products)); priceRow=totalMultiple(rowData, selectedPreferenceProducts(selected_products)); } }); var cell = document.createElement('td'); cell.appendChild(document.createTextNode(priceRow)); row.appendChild(cell); if(n<count){ tableBody.appendChild(row); n++; } }); table.appendChild(tableBody); return table; } //Бары товардар таблицалара function createTableNotSorted(filteredPr, filteredPrices, filteredUtilities,count,arrNameNonFiltered){ let n=0; var table = document.createElement('table'); var tableBody = document.createElement('tbody'); var row0=document.createElement('tr'); tableBody.appendChild(row0); // Строка названий товаров for(var i=0;i<filteredPr[0].length;i++){ var y = document.createElement("th") var t = document.createTextNode(arrNameNonFiltered[i]); y.appendChild(t); row0.appendChild(y); } y = document.createElement("th"); t = document.createTextNode("Стоимость"); y.appendChild(t); row0.appendChild(y); y = document.createElement("th"); t = document.createTextNode("Полезность"); y.appendChild(t); row0.appendChild(y); //тело таблицы filteredPr.forEach(function(rowData, index) { var row = document.createElement('tr'); rowData.forEach(function(cellData, index) { var cell = document.createElement('td'); cell.appendChild(document.createTextNode(cellData)); row.appendChild(cell); }); var cell = document.createElement('td'); cell.appendChild(document.createTextNode(filteredPrices[index])); row.appendChild(cell); cell = document.createElement('td'); cell.appendChild(document.createTextNode(filteredUtilities[index]));//filteredUtilities[index])); row.appendChild(cell); if(n<count){ tableBody.appendChild(row); n++; } }); table.appendChild(tableBody); return table; } //Бу матрица В - товардар ханнык категорияларга киирэллэрин кордорор function createMatrixB(non_selected_products,selected_products, cat_ids) { //console.log("selected_products_non_sorted "+non_selected_products); //console.log("cat_ids "+cat_ids); var arrCatB=[]; for(var j=0;j<cat_ids.length;j++){ var arr1=[]; for(var i=0;i<selected_products.length;i++){ arr1[i]=0; if(cat_ids[j]==selected_products[i]['kat_id']){ // console.log("Нашел товар "+cat_ids[j]); //console.log("Сравниваю с "+selected_products[i]['kat_id']); arr1[i]=1; } else { for(var k=0;k<non_selected_products.length;k++){ if((cat_ids[j]==non_selected_products[k]['kat_id'])&&(selected_products[i]['id']==non_selected_products[k]['id'])){ arr1[i]=1; //console.log("Нашел повтор "+selected_products[i]['name']); } } } } arrCatB[j]=arr1; } return arrCatB; } //массивтан биир name столбесы оруур function arrName(selected_products) { var task_name = []; jQuery.each(selected_products, function( key, value ) { task_name.push(value.name); }); return task_name; } //массивтан биир preference столбесы оруур function arrPreference(selected_products) { var task_prices = []; jQuery.each(selected_products, function( key, value ) { console.log("20190827 Prefe "+value.preference) task_prices.push(value.preference); }); return task_prices; } //массивтан биир min_count столбесы оруур function arrMin_count(selected_products) { var task_prices = []; jQuery.each(selected_products, function( key, value ) { task_prices.push(value.min_count); }); return task_prices; } //массивтан биир max_count столбесы оруур function arrMax_count(selected_products) { var task_prices = []; jQuery.each(selected_products, function( key, value ) { task_prices.push(value.max_count); }); return task_prices; } //Браузерга тахсыбыт мин уонна мах продуктар киэнин булар function selectedMinMaxProducts(selected_products){ var arrCountMinMax=[]; //console.log("selected_products.length="+selected_products.length); for(var i0=0;i0<selected_products.length;i0++){ //console.log("selected_products[i0]="+selected_products[i0]); if(jQuery('select').is("#minabox"+i0)){ //console.log("Нашел minabox"+i0); //console.log("Нашел minabox val="+jQuery("#minabox"+i0).val()); arrCountMinMax.push(jQuery("#minabox"+i0).val()); }; if(jQuery('select').is("#maxabox"+i0)){ //console.log("Нашел maxabox"+i0); //console.log("Нашел maxabox val="+jQuery("#maxabox"+i0).val()); arrCountMinMax.push(jQuery("#maxabox"+i0).val()); } } //console.log("Новый arrCountMinMax"+arrCountMinMax); return arrCountMinMax; } //Браузерга тахсыбыт preference продуктар киэнин булар function selectedPreferenceProducts(selected_products){ var arr=[]; for(var i0=0;i0<selected_products.length;i0++){ if(jQuery('select').is("#prefe"+i0)){ arr.push(jQuery("#prefe"+i0).val()); //console.log("Нашел Префе"+i0+": "+jQuery("#prefe"+i0).val()); }; } return arr; } //Браузерга тахсыбыт категориялар мин мах киэнин булар function selectedMinMaxCategories(selected_products){ var arrCountMinMax=[]; for(var i0=0;i0<selected_products.length;i0++){ if(jQuery('select').is("#minCat"+i0)){ //console.log("Нашел minCat"+i0); //console.log("Нашел minCat val="+jQuery("#minCat"+i0).val()); arrCountMinMax.push(jQuery("#minCat"+i0).val()); }; if(jQuery('select').is("#maxCat"+i0)){ //console.log("Нашел maxCat"+i0); //console.log("Нашел maxCat val="+jQuery("#maxCat"+i0).val()); arrCountMinMax.push(jQuery("#maxCat"+i0).val()); } } return arrCountMinMax; } //Браузерга тахсыбыт Категорияларынан фильтдыыр function filterByMatrixB(cartesianPr,matrix_b,arrCountMinMaxCategories){ var arr=[]; var cartesianPr1=cartesianPr; var oddMinMaxCategories=arrCountMinMaxCategories.filter(function(item, number) { return number % 2 == 0; }); var evenMinMaxCategories=arrCountMinMaxCategories.filter(function(item, number) { return number % 2 != 0; }); for(var i=0;i<matrix_b.length;i++){ var filtered = cartesianPr1.filter(function(item, number) { return ((totalMultiple(item, matrix_b[i])>=oddMinMaxCategories[i])&&(totalMultiple(item, matrix_b[i])<=evenMinMaxCategories[i])); }); arr[i]=filtered; cartesianPr1=arr[i]; } return cartesianPr1; } //Браузерга тахсыбыт Max_count 0 буолбатах товардары фильтодыыр уонна уларытар function filtered_selected_products_arr(selected_products){ // console.log("НАШЕЛ selected_products Уларыйбыты Барыта= "+selected_products); // console.log("НАШЕЛ selected_products Уларыйбыты Барыта= "+selected_products.length); var arr=[]; jQuery(selected_products).each(function( idx, value ) { if(selected_products[idx].max_count>0){ // console.log("НАШЕЛ ПО [idx].id С браузера: "+selected_products[idx].id); // console.log("НАШЕЛ ПО [idx].name С браузера: "+selected_products[idx].name); // console.log("НАШЕЛ ПО [idx].preference С браузера: "+selected_products[idx].preference); // console.log("НАШЕЛ ПО [idx].price С браузера: "+selected_products[idx].price); // console.log("НАШЕЛ ПО [idx].min_count С браузера: "+selected_products[idx].min_count); // console.log("НАШЕЛ ПО [idx].max_count С браузера: "+selected_products[idx].max_count); // console.log("НАШЕЛ ПО [idx].kat_id С браузера: "+selected_products[idx].kat_id); arr.push(selected_products[idx]); } }); // console.log("Браузерга тахсыбыт Max_count 0 буолбатах " + // "товардары фильтодыыр уонна уларытар ",+arr.length); return arr; } //Браузерга тахсыбыт Preference max_count 0 буолбатах filtered_selected_products_arr угагын function filteredPreference(filtered_selected_products_arr){ arr=[]; jQuery(filtered_selected_products_arr).filter(function(idx) { console.log("НАШЕЛ ПО [idx] префе"+filtered_selected_products_arr[idx].preference); arr.push(filtered_selected_products_arr[idx].preference); return arr; }); } // Улахан массивтан arrBig кыра массивка arrSmall соп тубэсэр индексары сана массив онорор function indexOfarr1(arrBig, arrSmall){ arr=[]; for(var i=0; i<arrBig.length; i++){ if(arrSmall.indexOf(arrBig[i]) != -1) arr.push(i); } return arr; } //////////////////////////////////////////////////////////////////////////////////////// jQuery(document).ready(function() { jQuery(".buttonToggle").hide(); jQuery(".button25").click(function(){ var arrObjectsMin = []; // объявление массива var arrObjectsMax = []; // объявление массива let str=''; var budget = jQuery("#new_budget").val(); var arrCountMinMax=[]; var arrCountMinMaxCategories=[]; var arrPreferenceIn=[]; var arrPriceFiltered=[]; var filtered_selected_products=[]; var filtered_arrPreferenceIn=[]; var arrNameNonFiltered=[]; filtered_selected_products = selected_products; //count_of_cat_products бэрэбиэкэлиэххэ. Категорияга хас устуука товар баарын кордорор //console.log("НЕФИЛЬТРОВАННЫЙ count_of_cat_products "+count_of_cat_products); /*console.log("ФИЛЬТРОВАННЫЙ без повтора PHP кэлбит filtered_selected_products "); jQuery.each(filtered_selected_products, function( key, value ) { jQuery.each(value, function( key1, value1 ) { console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); }); });*/ //Бу манна бары товардар префеларын булар. Киирэр массивка хас категория аайы хас товар баарын укпутум arrPreferenceIn=selectedPreferenceProducts(selected_products); //console.log("arrPreferenceIn="+arrPreferenceIn); //Бу товардар ID корзинага киирбит //console.log("Бу товардар ID products_ids_array",products_ids_array); arrCountMinMax=selectedMinMaxProducts(selected_products); //console.log("НЕФИЛЬТРОВАННЫЙ arrCountMinMax "+arrCountMinMax); ///////////////////////////////// //count_of_cat_products бэрэбиэкэлиэххэ. Категорияга хас устуука товар баарын кордорор //console.log("НЕФИЛЬТРОВАННЫЙ count_of_cat_products "+count_of_cat_products); arrCountMinMaxCategories=selectedMinMaxCategories(count_of_cat_products); /* console.log("НЕФИЛЬТРОВАННЫЙ arrCountMinMaxCategories "+arrCountMinMaxCategories); jQuery.each(arrCountMinMaxCategories, function( key, value ) { jQuery.each(value, function( key1, value1 ) { console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); }); }); */ //Бу манна талылынна браузертан // for(var i1=0;i1<selected_products.length;i1++){ // selected_products[i1].min_count=arrCountMinMax[2*i1]; // selected_products[i1].max_count=arrCountMinMax[2*i1+1]; // } //Бу манна талылынна браузертан for(var i1=0;i1<filtered_selected_products.length;i1++){ filtered_selected_products[i1].min_count=arrCountMinMax[2*i1]; filtered_selected_products[i1].max_count=arrCountMinMax[2*i1+1]; } /*console.log("ФИЛЬТРОВАННЫЙ selected_products "+filtered_selected_products); jQuery.each(filtered_selected_products, function( key, value ) { jQuery.each(value, function( key1, value1 ) { console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); }); });*/ filtered_arrPreferenceIn=selectedPreferenceProducts(selected_products); //console.log("ФИЛЬТРОВАННЫЙ filtered_arrPreferenceIn"+filtered_arrPreferenceIn); arrPriceFiltered=arrPrice(filtered_selected_products); //console.log("ФИЛЬТРОВАННЫЙ arrPriceFiltered .length"+arrPriceFiltered.length); //товардар ааттара arrNameNonFiltered=arrName(filtered_selected_products); // console.log("ФИЛЬТРОВАННЫЙ arrNameNonFiltered "+arrNameNonFiltered); // console.log("ФИЛЬТРОВАННЫЙ arrNameNonFiltered[0] "+arrNameNonFiltered[0]); // console.log("ФИЛЬТРОВАННЫЙ arrNameNonFiltered[1] "+arrNameNonFiltered[1]); arrIdFiltered=arrId(filtered_selected_products); //console.log("ФИЛЬТРОВАННЫЙ arrIdFiltered "+arrIdFiltered); //console.log("arrPriceFiltered :"+arrPriceFiltered); //jQuery.each(arrPriceFiltered, function( key1, value1 ) { //console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); //}); //console.log("arrIdFiltered :"+arrIdFiltered); //jQuery.each(arrIdFiltered, function( key1, value1 ) { // console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); // }); //console.log("НЕФИЛЬТРОВАННЫЙ selected_products "+selected_products_non_sorted); /*jQuery.each(selected_products_non_sorted, function( key, value ) { jQuery.each(value, function( key1, value1 ) { console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); }); });*/ var arrCatB=createMatrixB(selected_products_non_sorted,filtered_selected_products, cats_ids_array); jQuery("#budget").html('<br /> Бюджет пользователя '+jQuery("#new_budget").val()); var arrcartez = []; arrcartez=arrCountProducts_for_cart(filtered_selected_products); /*console.log("UUU arrcartez= "+arrcartez); jQuery.each(arrcartez, function( key, value ) { jQuery.each(value, function( key1, value1 ) { console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); }); });*/ var cartesianPr = []; cartesianPr=cartesianProduct(arrcartez); console.log("arrcartez 2019 =", arrcartez);//20190606 console.log("cartesianPr 2019 =", cartesianPr);//20190606 //категорияларынан фильтрдаатым var filteredProducts = filterByMatrixB(cartesianPr,arrCatB,arrCountMinMaxCategories); var filteredPrices = []; // Массив цен неупорядаченный var filteredUtilities = []; // Массив полезностей неупорядаченный //категорияларынан уонна бюджетынан фильтрдаатым filteredProducts=filterByBudget(filtered_selected_products,filteredProducts,budget); jQuery.each(filtered_selected_products[0], function(index,value) { }); jQuery.each(filtered_selected_products,function(key,data) { jQuery.each(data, function(index,value) { }); }); str='Бюджет='+budget+'<br/>'; for (i=0;i<filteredProducts.length;i++) { for (j=0;j<filteredProducts[i].length;j++) { arrObjectsMin[i]={id:i, totalPrice: totalMultiple(arrPrice(filtered_selected_products),filteredProducts[i])} arrObjectsMax[i]={id:i, totalPrice: totalMultiple(filtered_arrPreferenceIn,filteredProducts[i])} str+=filteredProducts[i][j]+' '; } filteredPrices.push(totalMultiple(arrPrice(filtered_selected_products),filteredProducts[i])); filteredUtilities.push(totalMultiple(filtered_arrPreferenceIn,filteredProducts[i])); str+='Цена='+totalMultiple(arrPrice(filtered_selected_products),filteredProducts[i])+' '; str+='Полезность='+totalMultiple(filtered_arrPreferenceIn,filteredProducts[i])+'<br/>'; } console.log("filteredPr 2019 =", filteredProducts);//фильтеред иьигэр количестволар бааллар console.log("filteredPrices 2019 =", filteredPrices);//фильтеред иьигэр ценалара бааллар console.log("arrNameNonFiltered 2019 =", arrNameNonFiltered);//фильтрдамматах товардар ааттара console.log("filteredUtilities 2019 =", filteredUtilities);//фильтеред иьигэр туьата бааллар filtered_selected_products_without0 = filtered_selected_products_arr(selected_products); /*console.log("ФИЛЬТРОВАННЫЙ filtered_selected_products_without0 "); jQuery.each(filtered_selected_products_without0, function( key, value ) { jQuery.each(value, function( key1, value1 ) { console.log( 'Свойство: ' +key1 + '; Значение: ' + value1 ); }); });*/ filtered_selected_products_without0_names = filtered_selected_products_without0.map(o => o.name); console.log("ФИЛЬТРОВАННЫЙ filtered_selected_products_without0_names "+filtered_selected_products_without0_names); filtered_selected_products_without0_indexs =indexOfarr1(arrNameNonFiltered, filtered_selected_products_without0_names); console.log("Индексы filtered_selected_products_without0_indexs "+filtered_selected_products_without0_indexs); // удаляю из массива столбцы, состоящие из 0 // for(var i = 0 ; i < filteredProducts.length ; j++){ // for (var j = filtered_selected_products_without0_indexs.length -1; i >= 0; i--){ // filteredProducts[i].splice(filtered_selected_products_without0_indexs[j],1); // } // } for (var i = 0; i < filteredProducts.length; i++) { var temp = filteredProducts[i]; filteredProducts[i] = []; for(var j = 0 ; j < temp.length ; j++){ if(filtered_selected_products_without0_indexs.indexOf(j) != -1) // dont delete { filteredProducts[i].push(temp[j]); } } } console.log("filteredPr 2019 без 0 столбцов =", filteredProducts);//фильтеред иьигэр количестволар бааллар 0 // столбецтара суох arrNameNonFiltered=filtered_selected_products_without0_names; //Туттуллубат товардар ааттарын соттум //jQuery("#product_arr").html('<br /> Допустимые сочетания товаров. '+str ); jQuery("#product_arr_not_sorted").html(createTableNotSorted(filteredProducts, filteredPrices, filteredUtilities, 15,arrNameNonFiltered)); arrObjectsMin.sort(function(a, b){return a.totalPrice - b.totalPrice}); arrObjectsMax.sort(function(a, b){return b.totalPrice - a.totalPrice}); var sortedFilteredPrMin=[]; var sortedFilteredPrMax=[]; for (i=0;i<arrObjectsMin.length;i++) { sortedFilteredPrMin.push(filteredProducts[arrObjectsMin[i].id]); } for (i=0;i<arrObjectsMax.length;i++) { sortedFilteredPrMax.push(filteredProducts[arrObjectsMax[i].id]); } //Сана упорядоченный массива jQuery("#product_opt_all").html("Пока пусто"); jQuery("#product_opt_all").html(createTable(filtered_selected_products, sortedFilteredPrMin,5,"Стоимость", 0,count_of_cat_products,filtered_selected_products_without0_names)); jQuery("#product_preference_all").html("Пока пусто"); jQuery("#product_preference_all").html(createTable(filtered_selected_products, sortedFilteredPrMax,5, "Полезность", 1,count_of_cat_products,filtered_selected_products_without0_names)); //hover таблицы стоимостей jQuery("#tableSelected0 tbody tr:not(:first)").on("hover", function(e) { if(e.type == "mouseenter") { //console.log("over"); jQuery(this).css({'color':'blue'}).css("font-size","20px").css({'font-weight':'bold'}); //jQuery(this).css({'backgroundColor':'red'}); } else if (e.type == "mouseleave") { //console.log("out"); jQuery(this).css({'color':''}).css("font-size","").css({'font-weight':''}); // jQuery(this).css({'backgroundColor':''}); } }); //Таблица по стоимости var table0val=[]; for (var i=0; i<5;i++){ var arrTd=[]; var rowId="#selectedTr0"+i; var collectionTr=[]; if(jQuery(rowId).text()!=''){ //console.log("selectedTr"+jQuery(rowId).text()); for (var j=0; j<filtered_selected_products.length;j++){ var tdId="#td"+j; //манна селектор столбца. Онно товардар ааттара баар var prId="#myTr"+j; //манна продукталар ID //console.log("jQuery(prId).text() ", jQuery(prId).text()); //console.log("arrId(filtered_selected_products) ",arrId(filtered_selected_products)) ; arrTd[j]=jQuery(rowId).children(tdId).text(); } collectionTr.push(arrTd); collectionTr.push(arrId(filtered_selected_products)); //console.log("collectionTr.push(arrTd) ", collectionTr); table0val[i]=collectionTr; //table0val[i]=arrTd; } } // Таблица по полезности var table1val=[]; for (var i=0; i<5;i++){ var arrTd=[]; var rowId="#selectedTr1"+i; var collectionTr=[]; if(jQuery(rowId).text()!=''){ //console.log("selectedTr"+jQuery(rowId).text()); for (var j=0; j<filtered_selected_products.length;j++){ var tdId="#td"+j; //манна селектор столбца. Онно товардар ааттара баар var prId="#myTr"+j; //манна продукталар ID //console.log("jQuery(prId).text() ", jQuery(prId).text()); //console.log("arrId(filtered_selected_products) //",arrId(filtered_selected_products)) ; arrTd[j]=jQuery(rowId).children(tdId).text(); } collectionTr.push(arrTd); collectionTr.push(arrId(filtered_selected_products)); //console.log("collectionTr.push(arrTd) ", collectionTr); table1val[i]=collectionTr; //table1val[i]=arrTd; } } // Таблица стоимостей для отправки на сервер var isSendToCart; jQuery("#tableSelected0 tbody tr:not(:first)").on("click", function(e) { var str=jQuery(this).attr("id"); str=str.substring(11); //alert(jQuery(this).attr("id")+" Подстрока "+str); var arrTable0=table0val[str]; //alert("arrTable0 строка ="+table0val[str]) if(arrTable0.length > 0){ var arrj=JSON.stringify(arrTable0); //alert("JSON строка arrj="+arrj) isSendToCart = confirm("Заменить товары корзины?"); if(isSendToCart){ jQuery.ajax({ url: ajax_object.ajax_url, type: 'POST', dataType:'json', data:{ action: 'msvCart', newProducts:arrj, }, beforeSend: function( xhr ) { jQuery('#wait0').text('Загрузка, 5 сек...'); }, success: function( data ) { jQuery('#wait0').text(''); jQuery('.wrap').text('Поместил в корзине '+data+ ' товаров. Посмотрите корзину.'); } }); } } }); // Таблица полезностей для отправки на сервер jQuery("#tableSelected1 tbody tr:not(:first)").on("click", function(e) { var str=jQuery(this).attr("id"); str=str.substring(11); //alert(jQuery(this).attr("id")+" Подстрока "+str); var arrTable1=table1val[str]; //alert("arrTable1 строка ="+table1val[str]) if(arrTable1.length > 0){ var arrj=JSON.stringify(arrTable1); //alert("JSON строка arrj="+arrj) isSendToCart = confirm("Заменить товары корзины?"); if(isSendToCart){ jQuery.ajax({ url: ajax_object.ajax_url, type: 'POST', dataType:'json', data:{ action: 'msvCart', newProducts:arrj, }, beforeSend: function( xhr ) { jQuery('#wait1').text('Загрузка, 5 сек...'); }, success: function( data ) { jQuery('#wait1').text(''); jQuery('.wrap').text('Поместил в корзине '+data+ ' товаров. Посмотрите корзину.'); } }); } } }); //hover таблицы полезностей jQuery("#tableSelected1 tbody tr:not(:first)").on("hover", function(e) { if(e.type == "mouseenter") { //console.log("over"); jQuery(this).css({'color':'blue'}).css("font-size","20px").css({'font-weight':'bold'}); } else if (e.type == "mouseleave") { //console.log("out"); jQuery(this).css({'color':''}).css("font-size","").css({'font-weight':''}); } }); jQuery(".buttonToggle").show(); jQuery("#product_arr_not_sorted").hide(); jQuery(".buttonToggle").click(function(){ jQuery("#product_arr_not_sorted").toggle(); }); }); });<file_sep><?php global $sessionVar; global $count_of_categories; global $count_of_cat_products; global $selected_products_results; global $selected_products_non_sorted; global $products_ids_array; global $cats_ids_array; $sessionVar = 'hello'; $count_of_cat_products = array(); function cartoptimization_install(){ global $wpdb; $table_name=$wpdb->prefix. 'cartoptimization'; if($wpdb->get_var("SHOW TABLES LIKE $table_name") != $table_name){ $sql="CREATE TABLE IF NOT EXISTS `$table_name` ( `id_cartoptimation` int (11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `text` text NOT NULL, PRIMARY KEY (`id_cartoptimation`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;"; $wpdb->query($sql); } add_option('cartoptimization_alternative',6); } function cartoptimization_uninstall(){ global $wpdb; $table_name=$wpdb->prefix. 'cartoptimization'; $sql="DROP TABLE IF EXISTS $table_name"; $wpdb->query($sql); $sql1="DELETE FROM `wp_posts` WHERE `wp_posts`.`post_title`='Оптимизация корзины'"; $wpdb->query($sql1); delete_option('cartoptimization_alternative'); } function cartoptimization_ondelete(){ global $wpdb; $table_name=$wpdb->prefix. 'cartoptimization'; $sql="DROP TABLE IF EXISTS $table_name"; $wpdb->query($sql); $sql1="DELETE FROM `wp_posts` WHERE `wp_posts`.`post_title`='Оптимизация корзины'"; $wpdb->query($sql1); delete_option('cartoptimization_alternative'); } //global $newCart; function newproducts_function(){ if (isset($_POST['newProducts'])){ global $woocommerce; $newProducts=$_POST['newProducts']; $woocommerce->cart->empty_cart(); $newCart=json_decode(stripslashes($newProducts),false); $countj=0; $countNewCartPr=0; for($i=0;$i<count($newCart[1]);$i++){ $newCart0=$newCart[1][$i]; $countj=$newCart[0][$i]; $countNewCartPr+=$countj; for($j=0;$j<$countj;$j++){ $woocommerce->cart->add_to_cart($newCart0); } } $json_text=json_encode($newCart); $json_text0=json_encode($newCart0); $json_countj=json_encode($countNewCartPr); echo $json_countj; die(); } else { echo "Нет данных"; die(); } } function msv_cartoptimization_scripts(){ global $post; $my_page_title = 'Оптимизация корзины'; if (!($my_page_title==$post->post_title)) return; wp_enqueue_script('msv_cartoptimization_scripts', plugins_url('/js/msv-cartoptimization-scripts.js',__FILE__),array('jquery'),null); wp_enqueue_style('msv_cartoptimization_style', plugins_url('/css/msv-cartoptimization-style.css',__FILE__)); wp_localize_script( 'msv_cartoptimization_scripts', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) ); } function pagesearch($content){ global $sessionVar; global $selected_products_results; global $selected_products_non_sorted; global $post; global $count_of_cat_products; global $count_of_categories; global $wpdb; global $woocommerce; global $products_ids_array; global $cats_ids_array; echo get_template_directory(); $debug = new PHPDebug(); //$debug->debug("PHP: Очень простое сообщение на консоль с файла function.php"); $my_page_title = 'Оптимизация корзины'; if (!($my_page_title==$post->post_title)) return $content; $emptycart="Корзина пуста. Плагин работает с не пустой корзиной"; if (sizeof(WC()->cart->get_cart()) == 0){ echo $emptycart; } echo $content; echo '<h3>Товары в корзине</h3>'; //массивы id и количества товаров в корзине $products_ids_array = array(); $products_quantities_array = array(); $products_names_array = array(); foreach( WC()->cart->get_cart() as $cart_item ){ $products_ids_array[] = $cart_item['product_id']; } foreach( WC()->cart->get_cart() as $cart_item ){ $products_quantities_array[] = $cart_item['quantity']; } foreach( WC()->cart->get_cart() as $cart_item ){ $products_names_array[] = $cart_item['data']->name; } echo '<table class="widefat"> <thead> <tr> <th> ID </th> <th> Название </th> <th> Цена </th> <th> Категория </th> <th> Количество </th> </tr> </thead>'; $cat_array = array(); $sumcart=0; //Цикл Выводит в таблице Товары из корзине foreach( WC()->cart->get_cart() as $cart_item_key => $values ) { echo '<tr>'; $_product = $values['data']; $debug->debug("PHP: Cart data ", $_product->id); //echo "<pre>"; //print_r($_product); //echo "</pre>"; echo '<td>'.$_product->id.'</td>'; echo '<td>'.$_product->name.'</td>'; echo '<td>'.$_product->price.'</td>'; $sumcart+= $_product->price*$values['quantity']; echo '<td>'; for ($i = 0; $i < count($_product->category_ids); $i++) { $terms_catnames = $wpdb->get_results("SELECT name, term_id FROM wp_terms WHERE term_id=".$_product->category_ids[$i].""); for ($j = 0; $j < count($terms_catnames); $j++) { echo ' '.$terms_catnames[$j]->name.' '; echo '</br>'; $cat_array[] = $terms_catnames[$j]->term_id; } } echo '</td>'; echo '<td>'; echo $values['quantity']; echo '</td>'; echo '</tr>'; } echo '<tr><td>Итого</td><td></td><td>'.$sumcart.'</td><td></td></tr>'; echo '</table>'; $result = array_unique($cat_array); $cats_ids_array=$result; $debug->debug("PHP: Массив ID категорий в корзине $result:",$result ); $count_of_categories = count($result); echo '</br>'; echo '<h3>Категории, связанные с товарами в корзине. Настройка.</h3> Выберите Min и Max количество товаров данной категории для внесения изменений в корзине. Если Min=0 и Max=0, то все товары этой категории не попадут в корзину. В таблице ниже укажите свои предпочтения по товарам. При этом, если на товаре Min=Max, то такое количество товара включается в корзину. Если Min=0 и Max=0 для конкретного товара, то этот товар не попадет в корзину. Один товар может попасть в две и более категории. В этом случае количество категорий может отличаться от корзины.'; echo '<table id = "table_cat"><tr><th>N</th><th>Name</th><th>Min</th><th>Max</th></tr>'; $table_counter_cat = 0; foreach($result as $i => $id_cat){ $terms_aidyn = $wpdb->get_results("SELECT name FROM wp_terms WHERE term_id=".$result[$i].""); $numKat=$i+1; echo '<tr><td id='.$result[$i].'>'.$numKat.'</td><td>'.$terms_aidyn[0]->name .'</td>'; echo '<td>'; echo '<select id="minCat'.$table_counter_cat.'"> <option selected="selected" value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select>'; echo '</td>'; echo '<td>'; echo '<select id="maxCat'.$table_counter_cat.'"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option selected="selected" value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select>'; echo '</td>'; echo '</tr>'; $table_counter_cat++;//категорияляр индекстарын улаатыннарабын. } echo '</table>'; echo "КОЛИЧЕСТВО СВЯЗАННЫХ С КОРЗИНОЙ КАТЕГОРИЙ "; echo $count_of_categories.". Все товары этих категорий." ; ////echo '<table id = "table_products">'; //$table_counter счетчик таблиц категорий //$table_counter = 0; $product_counter=0; foreach($result as $i => $id_cat){ $catlist = $wpdb->get_results("SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id=".$result[$i].""); $terms_name = $wpdb->get_results("SELECT name FROM wp_terms WHERE term_id=".$result[$i].""); ////echo '<tr id = "cat_'.$i.'"><th>'.$terms_name[0]->name."</th><th>Цена</th><th>Предпочтение</th><th>Min</th><th>Max</th></tr>"; ////echo "<br/> "; $ii=0; $count_of_cat_products[] = count($catlist); for($j = 0;$j<count($catlist);$j++){ //базаттан товардар ааттарын талар $name_product_woo = $wpdb->get_row("SELECT post_title FROM wp_posts WHERE ID=".$catlist[$j]->object_id.""); //базаттан товардар ID талар $id_product_woo = $wpdb->get_row("SELECT ID FROM wp_posts WHERE ID=".$catlist[$j]->object_id.""); $product_regular_price = $wpdb->get_results("SELECT meta_value FROM wp_postmeta WHERE post_id=".$catlist[$j]->object_id." AND meta_key='_price'"); $selected_products[]= array("id" => $id_product_woo->ID,"name" => $name_product_woo->post_title,"price" => $product_regular_price[0]-> meta_value,"preference" =>"Высокое" ,"min_count" => 0, "max_count" => 7, "kat_id" => $result[$i]); //Категорияга уларыттым kat_id. Товардар категориялара $ii++; $itotal=$ii-1; ////echo '<tr id = "product_'.$table_counter.$j.'"><td id = "product_name_'.$table_counter.$j.'">'; $keydublicat=1; //проверка на дубликат ///for ($k = 0;$k<count($selected_products)-1;$k++) ////if(($i>0)&&($name_product_woo->post_title==$selected_products[$k]['name'])){ ////$keydublicat=0; ////unset($selected_products[$k]);//Удаляю все дубликаты для отправки в JS ////} ////echo $name_product_woo->post_title; ////echo '</td><td>'; ////echo $product_regular_price[0]->meta_value; ////echo '</td>'; ////echo '<td>'; if($keydublicat){ ////echo '<select id="prefe'.$table_counter.$j.'" style="width : 100px"> ////<option selected="selected" value="10">Высокое</option> ////<option value="5">Среднее</option> ////<option value="1">Низкое</option> ////</select>'; } ////echo '</td>'; /*$countInCart=0; //талыллыбыт продуктар ааттарын булабын $keyName=true; foreach($products_names_array as $num => $name){ if($name_product_woo->post_title==$name){ $countInCart=$products_quantities_array[$num]; //$countInCart='В корзине ('.$countInCart.')'; $keyName=false; } }*/ ////echo '<td>'; if($keydublicat){ ////echo '<select id="minabox'.$table_counter.$j.'" style="width : 30px"> ////<option selected value="0">0</option> ////<option value="1">1</option> ////<option value="2">2</option> ////<option value="3">3</option> ////<option value="4">4</option> ////<option value="5">5</option> ////</select>'; ////echo '</td>'; } ////echo '<td>'; $maxval = 'value ="'; $selected_text = ''; //браузерга анаан кодтарв дополнительно киллэрди /* if($keydublicat){ if(!$keyName){ echo '<select id="maxabox'.$table_counter.$j.'" style="width : 30px">'; for($l = 0; $l<6; $l++){ if($l==$countInCart)$selected_text = 'selected '; else $selected_text = ''; echo '<option '.$selected_text.'value="'.$l.'">'.$l.'</option>'; } echo '</select>'; /////// //$selected_products[$product_counter][kat_id]=99; } else { echo '<select id="maxabox'.$table_counter.$j.'" style="width : 30px"> <option selected="selected" value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select>'; } } */ ////echo '</td>'; //// echo '</tr>'; $product_counter++; } //$table_counter++; } // Удаляю дибликаты товаров, которые попали в разные категории // получаем уникальные ключи $uniqueKeys = array_keys( array_unique( array_map(function($item) { return $item['id']; }, $selected_products) ) ); // извлекаем в новый массив те ключи, которые были уникальными $uniqueArray = array_filter($selected_products, function($itemKey) use ($uniqueKeys){ return in_array($itemKey, $uniqueKeys); }); $selected_products_results =[]; // извлекаем в новый массив те ключи, которые были уникальными foreach($selected_products as $item => $val){ if (in_array($item, $uniqueKeys)) { array_push($selected_products_results, $val); } } global $cart_page_url; $cart_page_url = get_permalink(woocommerce_get_page_id( 'cart' )); // echo '<pre>'; // print_r($selected_products); // echo '</pre>'; $selected_products_non_sorted=$selected_products;//Старое оставил. Там несколько категорий у одного // товара может быть $selected_products=$selected_products_results;//Переопределил. Уже без повтора // echo '<pre>'; // print_r($selected_products_results); // echo '</pre>'; echo '<table id = "table_products">'; echo '<th>N</th><th>Название</th><th>Цена</th><th>Предпочтение</th><th>Min</th><th>Max</th>'; ////echo "<br/> ";; foreach($selected_products as $i => $vals){ $numb=$i+1; echo '<tr><td>'.$numb.'</td><td id=product_name_'.$i.'>'.$vals['name'].'</td><td>'.$vals['price'].'</td><td>'; echo '<select id="prefe'.$i.'" style="width : 100px"> <option selected="selected" value="10">Высокое</option> <option value="5">Среднее</option> <option value="1">Низкое</option> </select>'.'</td><td>'; echo '<select id="minabox'.$i.'" style="width : 30px"> <option selected value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select></td><td>'; echo '<select id="maxabox'.$i.'" style="width : 30px">'; for($l = 0; $l<6; $l++){ $countInCart=0; //талыллыбыт продуктар ааттарын булабын foreach($products_names_array as $num => $name){ if($vals['name']==$name){ $countInCart=$products_quantities_array[$num]; //$countInCart='В корзине ('.$countInCart.')'; $keyName=false; } } if($l==$countInCart) $selected_text = 'selected '; else $selected_text = ''; echo '<option '.$selected_text.'value="'.$l.'">'.$l.'</option>'; } echo '</select>'; /* echo '<select id="maxabox'.$i.'" style="width : 30px"> <option selected="selected" value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select>';*/ echo '</td></tr>'; } echo '</table>'; } function msv_add_button($content) { global $selected_products_results; global $selected_products_non_sorted; global $count_of_categories; global $count_of_cat_products; global $post; global $products_ids_array; global $cart_page_url; global $cats_ids_array; $my_page_title = 'Оптимизация корзины'; if (!($my_page_title==$post->post_title)) return $content; $button = 'Кнопка для jQuery'; for($i = 0; $i < count($selected_products_results); $i++){ $selected_products[$i]= array( "id" => $selected_products_results[$i][id], "name" => $selected_products_results[$i][name], "price" => $selected_products_results[$i][price], "preference" =>$selected_products_results[$i][preference], "min_count" => $selected_products_results[$i][min_count], "max_count" => $selected_products_results[$i][max_count], "kat_id" => $selected_products_results[$i][kat_id]); } $debug = new PHPDebug(); $debug->debug("PHP: Глобальный Массив selected_products_results:",$selected_products_results ); $debug->debug("PHP: Глобальный Массив selected_products_non_sorted:",$selected_products_non_sorted ); ?> <script type="text/javascript"> var count_of_categories = "<?php echo $count_of_categories;?>"; var button = "<?php echo $button; ?>"; var sumTotal=0; var selected_products = <?php echo json_encode($selected_products); ?>; var selected_products_non_sorted = <?php echo json_encode($selected_products_non_sorted); ?>; var count_of_cat_products = <?php echo json_encode($count_of_cat_products);?>; var products_ids_array = <?php echo json_encode($products_ids_array);?>; var cats_ids_array = <?php echo json_encode($cats_ids_array);?>; </script> <div class="wrap"> <h4> Вывод альтернативных вариантов корзины</h4> Для просмотра альтернативных, других вариантов корзины настройте выше свои предпочтения. Встроенный оптимизационный калькулятор решает задачу максимизации полезности при заданных предпочтениях. Сначала показывает полезность вашей корзины и дополнительно еще 5 альтернативных вариантов корзины. Количество альтернатив настраивается. Если хотите поменять корзину, то ставите галочку и нажимаете кнопку "Поменять товары корзины". <h2>Для оптимизации корзины введите бюджет и нажмите кнопку</h2> Бюджет: <input type="text" id="new_budget" /> <a class="button25" >Оптимизировать</a> <div id="budget"> </div> <a class="buttonToggle" >Показать/скрыть все варианты</a> <div id="all_table_show"></div> <div id="min_count"> </div> <div id="max_count"> </div> <div id="product_arr"> </div> <div style="overflow-x: auto;" id="product_arr_not_sorted"> </div> <h2>5 лучших вариантов по стоимости</h2> <div id="wait0"> </div> <div style="overflow-x: auto;" id="product_opt_all"> </div> <h2>5 лучших вариантов по полезности</h2> <div id="wait1"> </div> <div style="overflow-x: auto;" id="product_preference_all"> </div> </div> <form action="<?php echo $cart_page_url;?>"> <button class="buttonHidden" >Открыть корзину</button> </form> <?php }
fc54a767c142adabef8c6a4de18f6f09f1657683
[ "Markdown", "JavaScript", "PHP" ]
4
PHP
mestsv/woo-cart-optimization
5ae586782bf0a18337388bd0209d29154d808bfc
2ed79009fc857a5f3b01bd8b706063ddf1d5e9e2
refs/heads/master
<repo_name>tonykero/nomnoml2<file_sep>/tests/tests.ts import * as assert from 'assert' import {generateRailroads, parse} from '../build/parser.js' import * as fs from 'fs' import * as path from 'path' import * as util from 'util' import * as mocha from 'mocha' const log = function(res, opt){ let outPath = path.resolve(__dirname, "./") //console.log("consol opt :" +opt) //if(opt.dir){ // if (!path.existsSync(opt.dir)) { // // } outPath = path.join(outPath, opt.dir) console.log("consol path 1 :" + outPath) fs.mkdirSync(outPath) //} let tokens = util.inspect(res.tokens, false, null) let cst = util.inspect(res.cst, false, null) let ast = util.inspect(res.ast, false, null) let errors = util.inspect(res.errors, false, null) fs.writeFileSync(outPath + "/lexer_finish.txt", tokens) fs.writeFileSync(outPath + "/cst_finish.txt", cst) fs.writeFileSync(outPath + "/ast_finish.txt", ast) fs.writeFileSync(outPath + "/errors.txt", errors) } const html = generateRailroads() fs.writeFileSync("./railroads.html", html) describe('Compartments', function() { const tests = [ { name: "prout", text: "jambon"}/*, { name: "prout2", text: "jambon|jambon"}, { name: "simple", text: "[j]" }, { name: "simple2", text: "[ j ]" }, { name: "simple3", text: "[ 0 0]" }, { name: "simple4", text: "[ <j> jambon]"}, { name: "simple5", text: "[ 0 0]-->[jambon]" }, { name: "simple6", text: "[ 0 0]-->[jambon]\n [ 0 0]-->[jambon]" }*/ ] tests.forEach((el) => { const test = el it('should parse: ' + test.name, function(){ let opt = { "dir": "log" + test.name } const ret = parse(test.text) log(ret, opt) assert.equal(ret.errors.length, 0) }) }) })<file_sep>/src/parser.ts import { Parser, IToken, createSyntaxDiagramsCode } from "chevrotain" import { allTokens, LSquare, StringLiteral, RSquare, Arrow, tokenize, SpecialCharacter, WhiteSpace, Pipe, LAngle, RAngle } from "./lexer"; //import { CSTVisitor } from './visitor.js' class NomnomlParser extends Parser { constructor(input: IToken[]){ super(input, allTokens, {outputCst: true, maxLookahead: 10}) this.performSelfAnalysis() } public nomnoml = this.RULE("nomnoml", () => { this.MANY(()=>{ this.SUBRULE(this.object) }) }) private compartment = this.RULE("compartment", () => { this.CONSUME(LSquare) this.SUBRULE(this.title) this.AT_LEAST_ONE_SEP({ SEP: Pipe, DEF: () => { this.SUBRULE(this.compartmentContent) } }) this.CONSUME(RSquare) }) private content = this.RULE("content", () => { this.MANY(() => { this.SUBRULE(this.contentComposition) }) }) private contentComposition = this.RULE("contentComposition", () => { //this.OR([ // { ALT: () => this.SUBRULE(this.content1)}, // { ALT: () => this.CONSUME(StringLiteral)} //]) this.CONSUME(StringLiteral) }) private content1 = this.RULE("content1", () => { this.CONSUME(WhiteSpace) this.CONSUME(SpecialCharacter) }) private attribute = this.RULE("attribute", () => { this.CONSUME(LAngle) this.SUBRULE(this.content) this.CONSUME(RAngle) }) private title = this.RULE("title", () => { this.OPTION(()=>{ this.SUBRULE(this.attribute) }) this.SUBRULE(this.content) }) private compartmentContent = this.RULE("compartmentContent", () => { this.OR([ { ALT: () => this.SUBRULE(this.content)}, { ALT: () => this.SUBRULE(this.compartment)} ]) }) private link = this.RULE("link", () => { this.CONSUME(Arrow) }) private OneLinkOne = this.RULE("OneLinkOne", () => { this.SUBRULE(this.compartment) this.SUBRULE(this.link) this.SUBRULE2(this.compartment) }) private object = this.RULE("object", () => { this.OR([ { ALT: () => this.SUBRULE(this.compartment)}, { ALT: () => this.SUBRULE(this.OneLinkOne) } ]) }) } const parser = new NomnomlParser([]) const BaseNomnomlVisitor = parser.getBaseCstVisitorConstructor() class CSTVisitor extends BaseNomnomlVisitor { constructor(){ super() this.validateVisitor() } nomnoml(ctx){ let objs = [] ctx.object.forEach((el) => { objs.push(this.visit(el)) }) return { type: "NOMNOML", objects: objs } } compartment(ctx){ let objs = [] objs.push(this.visit(ctx.title)) ctx.compartmentContent.forEach((el) => { objs.push(this.visit(el)) }) return { type: "COMPARTMENT", content: objs } } content(ctx){ let objs = [] ctx.contentComposition.forEach((el) => { objs.push(this.visit(el)) }) return { type: "CONTENT", content: objs } } contentComposition(ctx){ const content = ctx.StringLiteral.image return { type: "CONTENT_COMPOSITION", content: content } } content1(ctx){ const ws = ctx.WhiteSpace.image const sc = ctx.SpecialCharacter.image return { type: "CONTENT1", ws: ws, sc: sc } } attribute(ctx){ const content = this.visit(ctx.content) return { type: "ATTRIBUTE", content: content } } title(ctx){ let attrib = undefined if(ctx.attribute) { attrib = this.visit(ctx.attribute) } const content = this.visit(ctx.content) return { type: "TITLE", attribute: attrib, content: content } } compartmentContent(ctx){ let content = undefined if(ctx.content){ content = this.visit(ctx.content) } else{ content = this.visit(ctx.compartment) } return { type: "COMPARTMENT_CONTENT", content: content } } link(ctx){ const link = ctx.link return { type: "LINK", link: link } } OneLinkOne(ctx){ const lhs = this.visit(ctx.compartment[0]) const link = this.visit(ctx.link) const rhs = this.visit(ctx.compartment[1]) return { type: "ONELINKONE", lhs: lhs, rhs: rhs } } object(ctx){ if(ctx.OneLinkOne){ return this.visit(ctx.OneLinkOne) } else { return this.visit(ctx.compartment) } } } export function parse(text) { let lexResult = tokenize(text) parser.input = lexResult.tokens const cst = parser.nomnoml() /* if (parser.errors.length > 0) { console.log(parser.errors) throw new Error("sad sad panda, Parsing errors detected") } */ const toAstVisitor = new CSTVisitor() const ast = toAstVisitor.visit(cst) return { ast: ast, cst: cst, tokens: lexResult.tokens, errors: parser.errors } } export function generateRailroads() { const serGrammar = parser.getSerializedGastProductions() return createSyntaxDiagramsCode(serGrammar) }<file_sep>/README.md # nomnoml2 nomnoml2 is an **WIP** attempt to rewrite [nomnoml](https://github.com/skanaar/nomnoml) from parser to renderer in an non-retrocompatible enhanced way # License [MIT License](/LICENSE)<file_sep>/gulpfile.js const gulp = require('gulp'); const ts = require('gulp-typescript'); const clean = require('gulp-clean'); gulp.task('build', function(){ return gulp.src(['src/**/*.ts','tests/**/*.ts']) .pipe(ts({ module: 'commonjs', moduleResolution: 'node' })) .pipe(gulp.dest('build')); }); gulp.task('clean', function(){ return gulp.src('build', {read: false}) .pipe(clean()); });<file_sep>/src/lexer.ts import { createToken, Lexer } from "chevrotain" const LSquare = createToken({ name: "LSquare", pattern: /\[/ }) const RSquare = createToken({ name: "RSquare", pattern: /\]/ }) const LAngle = createToken({ name: "LAngle", pattern: /</}) const RAngle = createToken({ name: "RAngle", pattern: />/}) const Pipe = createToken({ name: "Pipe", pattern: /\|/}) const StringLiteral = createToken({ name: "StringLiteral", pattern: /[a-zA-Z0-9]+/}) const SpecialCharacter = createToken({ name: "SpecialCharacter", pattern: /[-_.]+/}) const WhiteSpace = createToken({ name: "WhiteSpace", pattern: /[ \t\n]+/ , line_breaks: true}) const Arrow = createToken({ name: "Arrow", pattern: /-*>/ }) const allTokens = [ LSquare, RSquare, LAngle, RAngle, Arrow, StringLiteral, SpecialCharacter, WhiteSpace, Pipe ] const NomnomlLexer = new Lexer(allTokens) export { allTokens, LSquare, RSquare, Arrow, StringLiteral, SpecialCharacter, WhiteSpace, Pipe, LAngle, RAngle } export function tokenize(text) { return NomnomlLexer.tokenize(text) }
be095366a266720f1d2780f6279217b089105282
[ "Markdown", "TypeScript", "JavaScript" ]
5
TypeScript
tonykero/nomnoml2
a68992021cdc92be636f5b4969ae0a10a48e1b42
1f3edaac8e0898715853cca4c34e689444844053
refs/heads/master
<file_sep>#include "term.h" Term Term::operator+(Term & Lhs, Term& Rhs) { if (Lhs.get_power == Rhs.get_power) Term temp(Lhs.get_power(),Lhs.get_constant + Rhs.get_constant); else cout << " RUNTIME ERROR: Powers not equal when doing addition on two terms." << endl; return(temp); } // const correctness.. Term Term::operator * (Term & Lhs, Term & Rhs) { // power and constant // term temp(Lhs.get_power() + Rhs.get_power(),Lhs.get_constant() * Rhs.get_constant()); return (temp); } <file_sep>#include "polynomial.h" using namespace std; Polynomial::Polynomial(int power):high_power(power) { // initialize polynomial with the highest power, add +1 to the power since if x^0 we want 1 space and if x^1 we want two spaces ect... Poly.resize(high_power+1); } Polynomial::Polynomial(const Term & temp) { // initialize polynomial with the highest power, add +1 to the power since if x^0 we want 1 space and if x^1 we want two spaces ect... Poly.resize(temp.get_power()+1); Poly[temp.get_power()] = temp.get_constant(); } void Polynomial::add_term(Term temp) { if (temp.get_power() > Poly.size()) Poly.resize(temp.get_power()+1); Poly[temp.get_power()] = temp.get_constant(); } bool Polynomial::sort(const Term & Lhs, const Term & Rhs) { return Lhs.get_power() < Rhs.get_power(); } <file_sep>#include <vector> #include <iostream> #include <string> #include <math.h> using namespace std; enum State { Solid, Liquid, Gas, Aq, }; class Chemical_element { public: Chemical_element(int C_coef, string C_name, float C_conc, State C_state): concentration(C_conc),name(C_name),coef(C_coef),S_state(C_state) { } float get_concentration() const { return concentration;} string get_name() const {return name;} int get_coef() const {return coef;} State get_state() const {return S_state;} void set_concentration(float new_conc) { concentration = new_conc;} void set_coef(int new_coef) { coef = new_coef;} void set_state(State new_state) {S_state = new_state;} private: float concentration; string name; int coef; State S_state; }; float Determine_ReactionQ(vector <Chemical_element> & Reactants, vector<Chemical_element> & Products) { // determine the reaction quotient float rq; float p_products = 1; float p_reactants = 1; // find the product of the chemical products for (vector<Chemical_element>::const_iterator i = Products.begin(); i != Products.end(); ++i) { float temp = pow(i->get_concentration(),i->get_coef()); p_products = p_products * temp; } // find the product of the chemical reagents for (vector<Chemical_element>::const_iterator i = Reactants.begin(); i != Reactants.end(); ++i) { float temp = pow(i->get_concentration(),i->get_coef()); p_reactants = p_reactants * temp; } rq = (p_products/p_reactants); return (rq); } void Equalibriate (vector<Chemical_element> & Reactants, vector<Chemical_element>& Products, float konstant) { } int main() { float konstant; } <file_sep> #ifndef term_H #define term_H class Term { public: Term():power(0),constant(0){}; Term(const int &pow, const float & con):power(pow),constant(con){}; void set_power(const int & pow) { power = pow;} void set_constant(const float & con) { constant = con;} int get_power() const { return power;} float get_constant() const {return constant;} private: // if it's just a plain number just give it a power of 0 int power; float constant; }; #endif <file_sep>#ifndef polynomial_H #define polynomial_H #include <vector> #include "term.h" // make a sort command to sort all the terms that are added into here // sort it by the highest power to the lowest power // activate the sort command each time something new is inserted class Polynomial { public: // Initialize a empty polynomials with the power = to slots allocated Polynomial(int power); // Initialize a polynomial with a temp term Polynomial(const Term & temp); // better to make a copy of it rather than pass by refrence void add_term(const Term & temp); private: int high_power; std::vector<Term> Poly; }; #endif
dfbae0ad935a89010f10b2a04e375e312f913d0d
[ "C++" ]
5
C++
SudaneseCharm/Projects
c2885bc78f526baa76f31b522db14e63e0e31758
47b7ea1c677032da3b4c0b94217ce2f2e2a19c61
refs/heads/master
<repo_name>LeonardoReisAmorim/Language-CSharp<file_sep>/exercicio2/Aluno.cs namespace exercicio1 { public class Aluno { public int Matricula { get; set; } public string Primeiro_nome { get; set; } public string Sobrenome { get; set; } public int Nota1 { get; set; } public int Nota2 { get; set; } public int Nota3 { get; set; } public Aluno(int matricula, string primeiro_nome, string sobrenome, int nota1, int nota2, int nota3) { this.Matricula = matricula; this.Primeiro_nome = primeiro_nome; this.Sobrenome = sobrenome; this.Nota1 = nota1; this.Nota2 = nota2; this.Nota3 = nota3; } public Aluno(){ } public double media(){ return (this.Nota1+this.Nota2+this.Nota3)/3; } } }<file_sep>/README.md # Language CSharp Aprendizado, projetos e muito mais <file_sep>/exercicios/Program.cs using System; using System.Collections.Generic; using System.Linq; namespace exercicios { class Program { static void Main(string[] args) { Produto p1 = new Produto("a", "b", 10.0); Produto p2 = new Produto("c", "d", 20.0); Produto p3 = new Produto("e", "f", 30.0); Compra c1 = new Compra("leo", 001); c1.Produtos.Add(p1); c1.Produtos.Add(p2); c1.Produtos.Add(p3); } } } <file_sep>/prova/Program.cs using System; using System.Collections.Generic; namespace prova { class Program { static void Main(string[] args) { List<Veiculo> veiculos = new List<Veiculo>(); Veiculo v1 = new Veiculo("ford", "fordgt", 1990, "Amarelo", 13000.00); Veiculo v2 = new Veiculo("ferrari", "ferrarigt", 1852, "Verde", 15000.00); Veiculo v3 = new Veiculo("lamborguini", "veneno", 1987, "Azul", 17000.00); Veiculo v4 = new Veiculo("porshe", "cayman", 1990, "Branco", 11000.00); Veiculo v5 = new Veiculo("Chevrolet", "onix", 1981, "Preto", 19000.00); Veiculo v6 = new Veiculo("lamborguini", "veneno", 1995, "Branco", 20000.00); // Adicionar veiculo novo veiculos.Add(v1); veiculos.Add(v2); veiculos.Add(v3); veiculos.Add(v4); veiculos.Add(v5); veiculos.Add(v6); // Imprimir todos os veiculos da lista Console.WriteLine("Imprimindo todos os veiculos da lista"); foreach(Veiculo i in veiculos){ Console.WriteLine("Marca: "+i.Marca+"; Modelo: "+i.Modelo+"; Ano de fabricação: "+i.Ano_de_fabricacao+"; Cor: "+i.Cor+"; Valor: "+i.Valor); } Console.WriteLine("\n\n"); // Listar todos os dados dos veículos da lista de acordo com a marca solicitada Console.WriteLine("Listando todos os dados dos veículos da lista de acordo com a marca solicitada"); Console.WriteLine("digite a marca"); string marca_digitada = Console.ReadLine(); List<Veiculo> veiculosmarca = veiculos.FindAll(x => x.Marca.Equals(marca_digitada)); foreach(Veiculo i in veiculosmarca){ Console.WriteLine("Marca: "+i.Marca+"; Modelo: "+i.Modelo+"; Ano de fabricação: "+i.Ano_de_fabricacao+"; Cor: "+i.Cor+"; Valor: "+i.Valor); } Console.WriteLine("\n\n"); // Listar todos os dados dos veículos da lista de acordo com o ano de fabricação solicitado Console.WriteLine("Listando todos os dados dos veículos da lista de acordo com o ano de fabricação solicitado"); Console.WriteLine("digite o ano de fabricação"); int ano_fab_dig = int.Parse(Console.ReadLine()); List<Veiculo> veiculosano_fab = veiculos.FindAll(x => x.Ano_de_fabricacao == ano_fab_dig); foreach(Veiculo i in veiculosano_fab){ Console.WriteLine("Marca: "+i.Marca+"; Modelo: "+i.Modelo+"; Ano de fabricação: "+i.Ano_de_fabricacao+"; Cor: "+i.Cor+"; Valor: "+i.Valor); } Console.WriteLine("\n\n"); // Listar todos os veículos com valores menores que R$ 15000.00 Console.WriteLine("Listando todos os veículos com valores menores que R$ 15000.00"); List<Veiculo> veiculosmenores_val = veiculos.FindAll(x => x.Valor < 15000.00); foreach(Veiculo i in veiculosmenores_val){ Console.WriteLine("Marca: "+i.Marca+"; Modelo: "+i.Modelo+"; Ano de fabricação: "+i.Ano_de_fabricacao+"; Cor: "+i.Cor+"; Valor: "+i.Valor); } Console.WriteLine("\n\n"); // Listar todos os veículos de cor branca Console.WriteLine("Listando todos os veículos de cor branca"); List<Veiculo> veiculoscor_branca = veiculos.FindAll(x => x.Cor.Equals("Branco")); foreach(Veiculo i in veiculoscor_branca){ Console.WriteLine("Marca: "+i.Marca+"; Modelo: "+i.Modelo+"; Ano de fabricação: "+i.Ano_de_fabricacao+"; Cor: "+i.Cor+"; Valor: "+i.Valor); } Console.WriteLine("\n\n"); // Listar os dados dos veículos pelo modelo solicitado Console.WriteLine("Listando os dados dos veículos pelo modelo solicitado"); Console.WriteLine("digite o modelo"); string modelo_dig = Console.ReadLine(); List<Veiculo> veiculos_modelo = veiculos.FindAll(x => x.Modelo.Equals(modelo_dig)); foreach(Veiculo i in veiculos_modelo){ Console.WriteLine("Marca: "+i.Marca+"; Modelo: "+i.Modelo+"; Ano de fabricação: "+i.Ano_de_fabricacao+"; Cor: "+i.Cor+"; Valor: "+i.Valor); } Console.WriteLine("\n\n"); // Remover veículo da lista veiculos.Remove(v1); veiculos.Remove(v2); veiculos.Remove(v3); veiculos.Remove(v4); veiculos.Remove(v5); veiculos.Remove(v6); } } } <file_sep>/prova/Veiculo.cs namespace prova { public class Veiculo { public string Marca { get; set; } public string Modelo { get; set; } public int Ano_de_fabricacao { get; set; } public string Cor { get; set; } public double Valor { get; set; } public Veiculo(string marca, string modelo, int ano_de_fabricacao, string color, double valor) { this.Marca = marca; this.Modelo = modelo; this.Ano_de_fabricacao = ano_de_fabricacao; this.Cor = color; this.Valor = valor; } public Veiculo() {} } }<file_sep>/exercicio2/Program.cs using System; namespace exercicio1 { class Program { static void Main(string[] args) { Aluno a1 = new Aluno(333, "leo", "aa", 7,8,9); Aluno a2 = new Aluno(111, "caio", "ab", 6,5,3); Aluno a3 = new Aluno(222, "joao", "ac", 1,10,4); Turma turma = new Turma(1, "ds"); int j = 0; while(j==0){ Console.WriteLine("1 - Adicionar Aluno\n2 - Remover Aluno\n3 - Consultar todos os dados do aluno pela matricula\n4 - Mostrar nome dos alunos e suas notas\n5 - Mostrar media de um aluno especifico\n6 - Listar todos os alunos cadastrados e seus dados\n7 - sair"); int res = int.Parse(Console.ReadLine()); switch(res){ case 1: turma.AdicionarAluno(a1); turma.AdicionarAluno(a2); turma.AdicionarAluno(a3); Console.WriteLine("alunos adicionados"); break; case 2: Console.WriteLine("digite o primeiro nome do aluno que quer remover"); string n_aluno = Console.ReadLine(); int resultadore = turma.RemoverAluno(n_aluno); if(resultadore == 0){ Console.WriteLine("aluno não existe"); }else if(resultadore ==1){ Console.WriteLine("aluno removido"); } break; case 3: Console.WriteLine("digite a matricula do aluno"); int mat = int.Parse(Console.ReadLine()); Aluno resultado = turma.Consultar_matricula(mat); Console.WriteLine("matricula: "+resultado.Matricula+"; primeiro nome: "+resultado.Primeiro_nome+"; sobrenome: "+resultado.Sobrenome+"; primeira nota: "+resultado.Nota1+ "; segunda nota: "+resultado.Nota2+"; terceira nota: "+resultado.Nota3); break; case 4: Console.WriteLine(turma.Mostrar_nomes_e_notas_alunos()); break; case 5: Console.WriteLine("digite o nome do aluno para receber a media"); string n = Console.ReadLine(); double result = turma.Mostrar_media(n); Console.WriteLine("A media do aluno é: "+result); break; case 6: Console.WriteLine(turma.Todos_alunos_cadastrados()); break; case 7: j = 1; break; default: Console.WriteLine("digite um valor valido"); break; } } //Console.WriteLine(turma.Mostrar_nomes_e_notas_alunos()); //Console.WriteLine(turma.Todos_alunos_cadastrados()); } } } <file_sep>/exercicioum/Consulta.cs namespace exercicioum { public class Consulta { public int Cpf { get; set; } public string Nome { get; set; } public string Sobrenome { get; set; } public int Idade { get; set; } public char Sexo { get; set; } public int Tipo_exame { get; set; } public string Nome_medico { get; set; } public Consulta(int cpf, string nome, string sobrenome, int idade, char sexo, string nome_medico) { this.Cpf = cpf; this.Nome = nome; this.Sobrenome = sobrenome; this.Idade = idade; this.Sexo = sexo; this.Nome_medico = nome_medico; } public Consulta(){} } }<file_sep>/exercicios/Compra.cs using System.Collections.Generic; using System.Linq; namespace exercicios { public class Compra { public string Comprador { get; set; } public int Codigo { get; set; } public List<Produto> Produtos { get; set; } public Compra(string comprador, int codigo) { this.Comprador = comprador; this.Codigo = codigo; Produtos = new List<Produto>(); } } }<file_sep>/exercicios/Produto.cs namespace exercicios { public class Produto { public string Marca { get; set; } public string Modelo { get; set; } public double Valor { get; set; } public Produto(string marca, string modelo, double valor) { this.Marca = marca; this.Modelo = modelo; this.Valor = valor; } public Produto(){ } } }<file_sep>/exercicio2/Turma.cs using System.Collections.Generic; using System.Linq; namespace exercicio1 { public class Turma { public int N_turma { get; set; } public string Nome_turma { get; set; } public List<Aluno> Alunos { get; set; } public Turma(int n_turma, string nome_turma) { this.N_turma = n_turma; this.Nome_turma = nome_turma; Alunos = new List<Aluno>(); } public void AdicionarAluno(Aluno x){ this.Alunos.Add(x); } /* public void RemoverAluno(Aluno x){ this.Alunos.Remove(x); } */ public int RemoverAluno(string n){ int achei = 0; Aluno res = this.Alunos.Find(x => x.Primeiro_nome.Equals(n)); if(res != null){ this.Alunos.Remove(res); achei = 1; } return achei; } /* public string Listar(){ string strValores = ""; foreach (Aluno i in this.Alunos) { strValores += "\n" + i.ToString(); } return strValores; } */ public Aluno Consultar_matricula(int m){ Aluno res = this.Alunos.Find(x => x.Matricula == m); return res; } public double Mostrar_media(string nome){ Aluno res = this.Alunos.Find(x => x.Primeiro_nome.Equals(nome)); return res.media(); } public string Mostrar_nomes_e_notas_alunos(){ string res = ""; foreach(Aluno i in Alunos){ res += "Primeiro nome: "+i.Primeiro_nome+"; Sobrenome: "+i.Sobrenome+"; primeira nota: "+i.Nota1+ "; segunda nota: "+i.Nota2+"; terceira nota: "+i.Nota3+"\n"; } return res; } public string Todos_alunos_cadastrados(){ string res = ""; foreach(Aluno i in Alunos){ res += "Primeiro nome: "+i.Primeiro_nome+"; Sobrenome: "+i.Sobrenome+"; Matricula: "+i.Matricula+"; primeira nota: "+i.Nota1+ "; segunda nota: "+i.Nota2+"; terceira nota: "+i.Nota3+"\n"; } return res; } } }<file_sep>/exercicioum/Program.cs using System; using System.Collections.Generic; namespace exercicioum { class Program { static void Main(string[] args) { List<Consulta> list = new List<Consulta>(); Consulta c1 = new Consulta(); c1.Cpf = 111; c1.Idade = 18; c1.Nome = "leo"; c1.Nome_medico = "deive"; c1.Sexo = 'm'; c1.Sobrenome = "reis"; Console.WriteLine("digite o tipo de exame que deseja fazer"); int te1 = int.Parse(Console.ReadLine()); c1.Tipo_exame = te1; list.Add(c1); Consulta c2 = new Consulta(); c2.Cpf = 222; c2.Idade = 36; c2.Nome = "antonia"; c2.Nome_medico = "beta"; c2.Sexo = 'f'; c2.Sobrenome = "lingard"; Console.WriteLine("digite o tipo de exame que deseja fazer"); int te2 = int.Parse(Console.ReadLine()); c2.Tipo_exame = te2; list.Add(c2); Consulta c3 = new Consulta(); c3.Cpf = 333; c3.Idade = 56; c3.Nome = "pogba"; c3.Nome_medico = "messi"; c3.Sexo = 'm'; c3.Sobrenome = "dab"; Console.WriteLine("digite o tipo de exame que deseja fazer"); int te3 = int.Parse(Console.ReadLine()); c3.Tipo_exame = te3; list.Add(c3); //buscando paciente por cpf Console.WriteLine("digite o cpf do paciente que deseja pesquisar no sistema"); int cpf = int.Parse(Console.ReadLine()); Consulta rescpf = list.Find(x => x.Cpf == cpf); switch(rescpf.Tipo_exame){ case 1: Console.WriteLine("CPF: "+rescpf.Cpf+" Idade: "+rescpf.Idade+" Nome: "+rescpf.Nome+" Sobrenome: "+rescpf.Sobrenome+ " Nome do medico: "+rescpf.Nome_medico+ " Sexo: "+rescpf.Sexo+ " tipo de exame: raio-x"); break; case 2: Console.WriteLine("CPF: "+rescpf.Cpf+" Idade: "+rescpf.Idade+" Nome: "+rescpf.Nome+" Sobrenome: "+rescpf.Sobrenome+ " Nome do medico: "+rescpf.Nome_medico+ " Sexo: "+rescpf.Sexo+ " tipo de exame: mamografia"); break; case 3: Console.WriteLine("CPF: "+rescpf.Cpf+" Idade: "+rescpf.Idade+" Nome: "+rescpf.Nome+" Sobrenome: "+rescpf.Sobrenome+ " Nome do medico: "+rescpf.Nome_medico+ " Sexo: "+rescpf.Sexo+ " tipo de exame: ultrassonografia"); break; case 4: Console.WriteLine("CPF: "+rescpf.Cpf+" Idade: "+rescpf.Idade+" Nome: "+rescpf.Nome+" Sobrenome: "+rescpf.Sobrenome+ " Nome do medico: "+rescpf.Nome_medico+ " Sexo: "+rescpf.Sexo+ " tipo de exame: ressonancia"); break; default: Console.WriteLine("codigo invalido"); break; } Console.WriteLine("\n\n\n"); //mostrar dados das pessoas maiores que 30 anos List<Consulta> listm30 = list.FindAll(x => x.Idade>30); foreach(Consulta i in listm30){ Console.WriteLine("dados das pessoas maiores que 30 anos"); switch(i.Tipo_exame){ case 1: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: raio-x"); break; case 2: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: mamografia"); break; case 3: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: ultrassonografia"); break; case 4: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: ressonancia"); break; default: Console.WriteLine("codigo invalido"); break; } } Console.WriteLine("\n\n\n"); //mostrar exames marcados para mamografia List<Consulta> listmamografia = list.FindAll(x => x.Tipo_exame == 2); foreach(Consulta i in listmamografia){ Console.WriteLine("dados dos exames para pacientes de mamografia"); switch(i.Tipo_exame){ case 1: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: raio-x"); break; case 2: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: mamografia"); break; case 3: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: ultrassonografia"); break; case 4: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: ressonancia"); break; default: Console.WriteLine("codigo invalido"); break; } } Console.WriteLine("\n\n\n"); //mostrar nome dos pacientes que marcaram exames de raio x List<Consulta> listnraiox = list.FindAll(x => x.Tipo_exame == 1); foreach(Consulta i in listnraiox){ Console.WriteLine("nome dos pacientes que marcaram exames de raio x"); Console.WriteLine(" Nome: "+i.Nome); } Console.WriteLine("\n\n\n"); //excluir exame marcado do cliente Console.WriteLine("digite o nome do cliente que deseja excluir"); string nome_excluir = Console.ReadLine(); Consulta resnomeexcluir = list.Find(x => x.Nome.Equals(nome_excluir)); list.Remove(resnomeexcluir); foreach(Consulta i in list){ Console.WriteLine("dados atualizados"); switch(i.Tipo_exame){ case 1: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: raio-x"); break; case 2: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: mamografia"); break; case 3: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: ultrassonografia"); break; case 4: Console.WriteLine("CPF: "+i.Cpf+" Idade: "+i.Idade+" Nome: "+i.Nome+" Sobrenome: "+i.Sobrenome+ " Nome do medico: "+i.Nome_medico+ " Sexo: "+i.Sexo+ " tipo de exame: ressonancia"); break; default: Console.WriteLine("codigo invalido"); break; } } } } }
96f2b0da104dbe321b9bf1cb74cfb1c963aad15a
[ "Markdown", "C#" ]
11
C#
LeonardoReisAmorim/Language-CSharp
dde2dc8a01a88d96ea37f8c4d01077ee795d1012
69b1371c46877f2098228802cee5f22352b61752
refs/heads/master
<file_sep>package com.yanqiu.oa; import com.yanqiu.oa.bean.OADepartment; import com.yanqiu.oa.bean.OAUser; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; public class MyBatisTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void init(){ //加载mybatis核心配置文件 InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream("mybatis.cfg.xml"); } catch (IOException e) { e.printStackTrace(); } // 解析mybatis.cfg.xml文档,并且初始化MyBatis(连接池、缓存) sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void test1(){ //获取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); List<OAUser> userList = sqlSession.selectList("com.yanqiu.oa.bean.userMapper.queryUser"); for (OAUser user:userList){ System.out.println(user.getUsername()); } } @Test public void test3(){ SqlSession sqlSession = sqlSessionFactory.openSession(); List<OADepartment> departments = sqlSession.selectList("com.yanqiu.oa.bean.departmentMapper.selectDepartment"); for (OADepartment oaDepartment:departments){ System.out.println(oaDepartment.getDepartmentName()); } } @Test public void test2(){ SqlSession sqlSession = sqlSessionFactory.openSession(); OADepartment department = sqlSession.selectOne("com.yanqiu.oa.bean.departmentMapper.selectId", 1); List<OAUser> userList = department.getOaUserList(); for (OAUser user:userList){ System.out.println(user.getUsername()); } } @Test public void test5(){ SqlSession sqlSession = sqlSessionFactory.openSession(); //参数1:查询语句的id 参数2:入参 // Map<String, Object> map = new HashMap<String, Object>(); // map.put("username","2 or 1=1"); List<OAUser> userList = sqlSession.selectList("com.yanqiu.oa.bean.userMapper.queryUserById"); for (OAUser user:userList){ System.out.println(user.getUsername()); } sqlSession.close(); } }
652026720b82f3cd271df6b6c9a1ada6d396e9fa
[ "Java" ]
1
Java
xiaoxiannvyanqiu/mybatis1
9fc9ff0d03f216f148486fed5324cddc385dddee
0a679e2c008e7ac5d78c11467daef20df035ea3f
refs/heads/master
<repo_name>kasimok/mockOCSP<file_sep>/src/main/java/Controllers/OCSPController.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package Controllers; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.ocsp.*; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Controller; 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.ResponseBody; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; import java.security.PrivateKey; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Created by evilisn(<EMAIL>)) on 2016/6/6. */ @Controller @ComponentScan ({"CA"}) public class OCSPController { private static Logger LOG = LoggerFactory.getLogger(OCSPController.class); private boolean bRequireNonce = true; private enum OCSP_PROCESS_MODE { AUTO(0, "AUTO"), GOOD(1, "GOOD"), REVOKED(2, "REVOKED"), UNKNOWN(3, "UNKNOWN"); private final int MODE; private final String DISP; OCSP_PROCESS_MODE(int mode, String disp) { this.MODE = mode; DISP = disp; } public static OCSP_PROCESS_MODE getOCSP_PROCESS_MODE(int ocsp_process_mode) { for (OCSP_PROCESS_MODE mode : OCSP_PROCESS_MODE.values()) { if (mode.MODE == ocsp_process_mode) return mode; } throw new IllegalArgumentException("Mode not supported."); } @Override public String toString() { return "OCSP_PROCESS_MODE{" + "MODE=" + MODE + ", DISP='" + DISP + '\'' + '}'; } } public static void setOcsp_process_mode(OCSP_PROCESS_MODE iocsp_process_mode) { ocsp_process_mode = iocsp_process_mode; } private static OCSP_PROCESS_MODE ocsp_process_mode = OCSP_PROCESS_MODE.GOOD; /** * OCSP Signer's cert. */ private static X509CertificateHolder x509CertificateHolder; /** * OCSP Signer's private keys. */ private static PrivateKey privateKey; @Autowired public void setX509CertificateHolder(X509CertificateHolder x509CertificateHolder) { this.x509CertificateHolder = x509CertificateHolder; } @Autowired public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; } /** * Method to deal with a ocsp query request. The OCSP request method can be GET or POST. * * @return a valid OCSP response. */ @RequestMapping (value = "/verify-mocked-auto", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/ocsp-response") @ResponseBody public byte[] doOCSPAuto(HttpServletRequest httpServletRequest) throws IOException { InputStream inputStream = httpServletRequest.getInputStream(); byte[] requestBytes = new byte[10000]; int requestSize = inputStream.read(requestBytes); LOG.info("Received OCSP request, size: " + requestSize); byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.AUTO); return responseBytes; } /** * Mocked method to deal with a ocsp query request. The OCSP request method can be GET or POST. * * @return a valid OCSP response to tell the client OCSP is <b>Good</b>! */ @RequestMapping (value = "/verify-mocked-good", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/ocsp-response") @ResponseBody public byte[] doOCSPGood(HttpServletRequest httpServletRequest) throws IOException { InputStream inputStream = httpServletRequest.getInputStream(); byte[] requestBytes = new byte[10000]; int requestSize = inputStream.read(requestBytes); LOG.info("Received OCSP request, size: " + requestSize); byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.GOOD); return responseBytes; } /** * Mocked method to deal with a ocsp query request. The OCSP request method can be GET or POST. * * @return a valid OCSP response to tell the client OCSP is <b>Revoked</b>! */ @RequestMapping (value = "/verify-mocked-revoked", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/ocsp-response") @ResponseBody public byte[] doOCSPRevoked(HttpServletRequest httpServletRequest) throws IOException { InputStream inputStream = httpServletRequest.getInputStream(); byte[] requestBytes = new byte[10000]; int requestSize = inputStream.read(requestBytes); LOG.info("Received OCSP request, size: " + requestSize); byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.REVOKED); return responseBytes; } /** * Mocked method to deal with a ocsp query request. The OCSP request method can be GET or POST. * * @return a valid OCSP response to tell the client OCSP is <b>Unknown</b>! */ @RequestMapping (value = "/verify-mocked-unknown", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/ocsp-response") @ResponseBody public byte[] doOCSPUnknown(HttpServletRequest httpServletRequest) throws IOException { InputStream inputStream = httpServletRequest.getInputStream(); byte[] requestBytes = new byte[10000]; int requestSize = inputStream.read(requestBytes); LOG.info("Received OCSP request, size: " + requestSize); byte[] responseBytes = processOcspRequest(requestBytes, OCSP_PROCESS_MODE.UNKNOWN); return responseBytes; } /** * Manually set the OCSP response mode for testing purpose. * * @return */ @RequestMapping (value = "/set-response-mode", method = {RequestMethod.GET}) @ResponseBody public String doSetMode(@RequestParam (value = "mode", defaultValue = "0") String mode) { try { final int iOcspMode = Integer.valueOf(mode); OCSP_PROCESS_MODE MODE = OCSP_PROCESS_MODE.getOCSP_PROCESS_MODE(iOcspMode); setOcsp_process_mode(MODE); String string = String.format("Server mode has been changed to [%s].", MODE); LOG.warn(string); return string; } catch (IllegalArgumentException e) { LOG.error(String.format("Illegal mode:[%s]", mode)); return "Illegal mode."; } } /** * Forwarding request to certain according to current set mode. * * @return */ @RequestMapping ({"/"}) public String execute() { LOG.info(String.format("System ocsp mode:[%s]", ocsp_process_mode)); switch (ocsp_process_mode) { case GOOD: return "forward:/verify-mocked-good"; case REVOKED: return "forward:/verify-mocked-revoked"; case UNKNOWN: return "forward:/verify-mocked-unknown"; case AUTO: return "forward:/verify-mocked-auto"; default: return "forward:/verify-mocked-good"; } } /** * Method to do OCSP response to client. * * @param requestBytes * @param mode * * @return * * @throws NotImplementedException */ private byte[] processOcspRequest(byte[] requestBytes, OCSP_PROCESS_MODE mode) throws NotImplementedException { try { // get request info OCSPReq ocspRequest = new OCSPReq(requestBytes); X509CertificateHolder[] requestCerts = ocspRequest.getCerts(); Req[] requestList = ocspRequest.getRequestList(); // setup response BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(new RespID(x509CertificateHolder.getSubject())); LOG.info("OCSP request version: " + ocspRequest.getVersionNumber() + ", Requester name: " + ocspRequest.getRequestorName() + ", is signed: " + ocspRequest.isSigned() + ", has extensions: " + ocspRequest.hasExtensions() + ", number of additional certificates: " + requestCerts.length + ", number of certificate ids to verify: " + requestList.length); int ocspResult = OCSPRespBuilder.SUCCESSFUL; switch (mode) { case AUTO: LOG.error("Auto OCSP server is not implemented in this version."); throw new NotImplementedException(); case GOOD: LOG.warn("Mocked mode, server will always return Good ocsp response"); for (Req req : requestList) { CertificateID certId = req.getCertID(); String serialNumber = "0x" + certId.getSerialNumber().toString(16); LOG.debug(String.format("Processing request for cert serial number:[%s]", serialNumber)); CertificateStatus certificateStatus = CertificateStatus.GOOD; Calendar thisUpdate = new GregorianCalendar(); Date now = thisUpdate.getTime(); thisUpdate.add(Calendar.DAY_OF_MONTH, 7); Date nexUpdate = thisUpdate.getTime(); responseBuilder.addResponse(certId, certificateStatus, now, nexUpdate, null); } break; case REVOKED: LOG.warn("Mocked mode, server will always return REVOKED ocsp response"); for (Req req : requestList) { CertificateID certId = req.getCertID(); String serialNumber = "0x" + certId.getSerialNumber().toString(16); LOG.debug(String.format("Processing request for cert serial number:[%s]", serialNumber)); Calendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, -7);//Set revoked 7 days ago. CertificateStatus certificateStatus = new RevokedStatus(cal.getTime(), 16); Calendar thisUpdate = new GregorianCalendar(); Date now = thisUpdate.getTime(); thisUpdate.add(Calendar.DAY_OF_MONTH, 7); Date nexUpdate = thisUpdate.getTime(); responseBuilder.addResponse(certId, certificateStatus, now, nexUpdate, null); } break; case UNKNOWN: LOG.warn("Mocked mode, server will always return Known ocsp response"); for (Req req : requestList) { CertificateID certId = req.getCertID(); String serialNumber = "0x" + certId.getSerialNumber().toString(16); LOG.debug(String.format("Processing request for cert serial number:[%s]", serialNumber)); CertificateStatus certificateStatus = new UnknownStatus(); Calendar thisUpdate = new GregorianCalendar(); Date now = thisUpdate.getTime(); thisUpdate.add(Calendar.DAY_OF_MONTH, 7); Date nexUpdate = thisUpdate.getTime(); responseBuilder.addResponse(certId, certificateStatus, now, nexUpdate, null); } break; } // process nonce Extension extNonce = ocspRequest.getExtension(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.2")); if (extNonce != null) { LOG.debug("Nonce is present in the request"); responseBuilder.setResponseExtensions(new Extensions(extNonce)); } else { LOG.info("Nonce is not present in the request"); if (bRequireNonce) { LOG.info("Nonce is required, fail the request"); ocspResult = OCSPRespBuilder.UNAUTHORIZED; } } X509CertificateHolder[] chain = {x509CertificateHolder}; ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey); BasicOCSPResp ocspResponse = responseBuilder.build(signer, chain, Calendar.getInstance().getTime()); OCSPRespBuilder ocspResponseBuilder = new OCSPRespBuilder(); byte[] encoded = ocspResponseBuilder.build(ocspResult, ocspResponse).getEncoded(); LOG.info("Sending OCSP response to client, size: " + encoded.length); return encoded; } catch (Exception e) { LOG.error("Exception during processing OCSP request: " + e.getMessage()); e.printStackTrace(); } return null; } } <file_sep>/src/main/java/CA/InternalCA.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package CA; import org.apache.commons.io.IOUtils; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Security; import java.security.spec.PKCS8EncodedKeySpec; /** * Created by evilisn(<EMAIL>)) on 2016/6/5. */ @Configuration public class InternalCA { private static Logger LOG = LoggerFactory.getLogger(InternalCA.class); public InternalCA() { // initialize BouncyCastle Security.addProvider(new BouncyCastleProvider()); LOG.info("Initialized BouncyCastle..."); } /** * Method to read private key from file. * * @param inputStream * * @return */ private PrivateKey readPrivateKey(InputStream inputStream) { try { PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(inputStream)); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey privKey = kf.generatePrivate(kspec); return privKey; } catch (Exception e) { LOG.info("Cannot load private key: " + e.getMessage()); return null; } } /** * Method to read cert from file. * * @param inputStream * * @return */ private X509CertificateHolder readCert(InputStream inputStream) { X509CertificateHolder x509CertificateHolder; try { x509CertificateHolder = new X509CertificateHolder(IOUtils.toByteArray(inputStream)); } catch (Exception e) { LOG.info("Cannot parse Internal CA certificate: " + e.getMessage()); return null; } return x509CertificateHolder; } @Bean public X509CertificateHolder x509CertificateHolder() throws IOException { //Get file from resources folder Resource resource = new ClassPathResource("certs/root/ca.cer.der"); return readCert(resource.getInputStream()); } @Bean public PrivateKey privateKey() throws IOException { //Get file from resources folder Resource resource = new ClassPathResource("certs/root/ca-key.pkcs8"); return readPrivateKey(resource.getInputStream()); } } <file_sep>/src/test/java/CA/InternalCATest.java package CA; import org.hamcrest.MatcherAssert; import org.junit.Before; import org.junit.Test; import static org.hamcrest.core.IsNull.notNullValue; /** * Created by evilisn(<EMAIL>)) on 2016/6/5. */ public class InternalCATest { InternalCA internalCA; @Before public void setUp() throws Exception { internalCA = new InternalCA(); } @Test public void readCert() throws Exception { MatcherAssert.assertThat(internalCA.x509CertificateHolder(), notNullValue()); } @Test public void readPrivateKey() throws Exception { MatcherAssert.assertThat(internalCA.privateKey(),notNullValue()); } }
7b3faf49df31e87a27f4e768f838fb0b84733fc1
[ "Java" ]
3
Java
kasimok/mockOCSP
de0a3ba21535e7ec5e1396fee467c9c4df13a94d
5db2230955d93275c0599d13c8d3a2d7ff9f3d98
refs/heads/master
<repo_name>mlg2434s/PyCharmProjects<file_sep>/找电缆EXCEL处理2.0新版/处理已导入的模板数据.py # 打开一个excel import xlrd import os import time import pymysql import xlwt def find_data_from_table(where_solution): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,full_text,price from zhaodianlan_price_update "+where_solution print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_type_detail(excel_name,full_type_name): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select gb,structure,material,lev_zr,type from type_name_detail where excel_name='%s' and full_type_name='%s'" %(excel_name,full_type_name) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_status(id): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update zhaodianlan_price_update set status=1 where table_id='%s'" %id try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() # 从excel中获取url的列表数据 def get_data_from_excel(path): # excel_name=r"D:\BI\找电缆\2017年12月红本出厂价《产品价格目录》\1712出厂价/201712 架空线出厂价-国标.xls" print(path) excel_name=path[path.rindex("/")+1:1000] #print(excel_name) data=xlrd.open_workbook(path) #打开excel sheetName = data.sheet_names()[0] # print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[0] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] # print(sheetName) #上一条数据的型号 last_type="" try: # 经过检验,数据的结构相同 # 类目、型号、规格、电压、价格 for i in range(1, nrows): ss = table.row_values(i) # 获取一行的所有值,每一列的值以列表项存在 # print(len(ss)) cate_name = ss[0] full_type_name = ss[1] specification = ss[2] voltage = ss[3] factory = ss[4] brand_name = ss[5] providence = ss[6] city = ss[7] price = ss[8] useful_date = ss[9] is_sale = ss[10] day = ss[11] average_calc = ss[12] attribute = ss[13] stock = ss[14] print(excel_name, full_type_name) insert_template(excel_name,cate_name,full_type_name,specification,voltage,factory,brand_name,providence,city,price,useful_date,is_sale,day ,average_calc,attribute,stock) except IndexError as e: print(e) def insert_template(excel_name,cate_name,full_type_name,specification,voltage,factory,brand_name,providence,city,price,useful_date,is_sale,day ,average_calc,attribute,stock): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into zhaodianlan_template (excel_name,cate_name,type_name,specification,voltage,factory,brand_name,"\ "providence,city,price,useful_date,is_sale,day,average_calc,attribute,stock) "\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" %(excel_name,cate_name,full_type_name,specification,voltage,factory,brand_name,providence,city,price,useful_date,is_sale,day ,average_calc,attribute,stock) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() #读取所有文件夹中的xls文件 def read_xls(path, type2): #遍历路径文件夹 for file in os.walk(path): for each_list in file[2]: file_path=file[0]+"/"+each_list #os.walk()函数返回三个参数:路径,子文件夹,路径下的文件,利用字符串拼接file[0]和file[2]得到文件的路径 name.append(file_path) if __name__ == "__main__": xpath = r"D:\BI\找电缆\yuandong" xtype = "xls" name = [] read_xls(xpath, xtype) print("%s个文件"%str(len(name))) for i in range (len(name)): excel_name = name[i] get_data_from_excel(excel_name) time.sleep(1) <file_sep>/TAOBAO/列表页数据获取/列表页销量评价获取.py import pymysql from bs4 import BeautifulSoup from selenium import webdriver import time import re def get_useful_data(html): soup=BeautifulSoup(html,'html.parser') prt_divs=soup.find_all('div',attrs={'class':re.compile('item J_MouserOnverReq ')}) print("current page have %s records"%str(len(prt_divs))) for prt_div in prt_divs: prt_price=prt_div.find('div',attrs={'class':'price g_price g_price-highlight'}).text print("prt_price",prt_price) prt_title = prt_div.find('div', attrs={'class': 'row row-2 title'}).find('a').text print("prt_title", prt_title) prt_url = prt_div.find('div', attrs={'class': 'row row-2 title'}).find('a').get('href') print("prt_url", prt_url) #//detail.tmall.com/item.htm?id=524785657239&skuId=3573590028479&areaId=320200&user_id=923873351&cat_id=50067923&is_b=1&rn=a36346c54fc20f2a4d2dbed860331aa9 prt_id = prt_div.find('div', attrs={'class': 'row row-2 title'}).find('a').get('id') prt_id=prt_id.replace("J_Itemlist_TLink_","") print("prt_id", prt_id) #print("prt_id",prt_id) prt_shop = prt_div.find('div', attrs={'class': 'shop'}).find('a').text print("prt_shop", prt_shop) prt_sales = prt_div.find('div', attrs={'class': 'deal-cnt'}).text #prt_evaluations = prt_div.find('p', attrs={'class': 'productStatus'}).find_all('span')[1].text print("prt_sales", prt_sales) insert_prt_lists_data(prt_id, prt_url, prt_title, prt_price, prt_shop, prt_sales, "") def insert_prt_lists_data(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations): prt_title=prt_title.replace("\n","") prt_shop=prt_shop.replace("\n","") db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_lists_info (prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) values('%s','%s','%s','%s','%s','%s','%s')" \ %(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_prt_lists_data--------Error------Message--------:' + str(err)) cursor.close() db.close() def next_page(num): pages=driver.find_elements_by_xpath("//li[@class='item']/a[@class='J_Ajax J_Pager link icon-tag']") cnt=len(pages) if cnt==1: pages[0].click() else: pages[1].click() time.sleep(3) try: page_num=driver.find_element_by_class_name("ui-page-s-len").text print(page_num) page_num=page_num.split("/")[0] current_page=num+2 if current_page==page_num: print("success") except: temp = input("tmp") if __name__=="__main__": url="https://s.taobao.com/search?q=%E7%BD%97%E6%A0%BC%E6%9C%97&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20180306&ie=utf8" #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) temp = input("tmp") #将html带入到函数进行分析 for i in range(100): html = driver.page_source get_useful_data(html) next_page(i) temp=input("tmp") <file_sep>/untitled/Selenium/test1.py import datetime now=datetime.datetime.now() now=now.strftime('%y%m%d%H%M') print(now)<file_sep>/MMBAO/图片筛选(从文件夹筛选复制).py import os import urllib.request import pymysql import sys import shutil import time def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select good_id from goods_lists_info where is_full=1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #复制图片 def copy_dir(prt_id): #暂时不加异常捕捉机制,试运行 old_path='D:/BI/德力西商品导入—zyd/去水印(2017年11月6日)/'+prt_id new_path='D:/BI/德力西商品导入—zyd/filter/'+prt_id shutil.copytree(old_path,new_path) if __name__=="__main__": data = get_prt_data() for i in range (149): prt_id = data[i][0] print(prt_id) #getAndSaveImg(prt_id) try: copy_dir(prt_id) except FileNotFoundError as e: pass except FileExistsError as x: pass time.sleep(1) #status=1 #update_state(prt_id,url,status)<file_sep>/漫画大业/test-jiemi.py import rsa def dologin(request): username=request.POST.get('username','') en_password=request.POST.get('password','') priv_key = request.session.get('privkey') request.session['privkey'] = None ##清除私钥 try: ##使用私钥解密得到明文密码 password = rsa.decrypt(en_password.decode('hex'),priv_key) except Exception as error: password = None ##这里省略密码验证500字<file_sep>/Scrapy/zyd/zyd/spiders/get_detail_table.py from scrapy.spiders import Spider from scrapy.selector import Selector class SteamUrls(Spider): name = "stack_spider" start_urls = ['https://stackoverflow.com/'] headers = { "host": "cdn.sstatic.net", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.5", "Connection": "keep-alive", "Content-Type": " application/x-www-form-urlencoded; charset=UTF-8", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0" } # 重写了爬虫类的方法, 实现了自定义请求, 运行成功后会调用callback回调函数 def start_requests(self): return [Request("https://stackoverflow.com/users/login", meta={ # 'dont_redirect': True, # 'handle_httpstatus_list': [302], 'cookiejar': 1}, callback=self.post_login)] # 添加了meta # FormRequeset def post_login(self, response): # 请求网页后返回网页中的_xsrf字段的文字, 用于成功提交表单 fkey = Selector(response).xpath('//input[@name="fkey"]/@value').extract()[0] ssrc = Selector(response).xpath('//input[@name="ssrc"]/@value').extract()[0] print (fkey) print (ssrc) # FormRequeset.from_response是Scrapy提供的一个函数, 用于post表单 # 登陆成功后, 会调用after_login回调函数 return [FormRequest.from_response(response, meta={ # 'dont_redirect': True, # 'handle_httpstatus_list': [302], 'cookiejar': response.meta['cookiejar']}, # 注意这里cookie的获取 headers=self.headers, formdata={ "fkey": fkey, "ssrc": ssrc, "email": "<EMAIL>", "password": "<PASSWORD>", "oauth_version": "", "oauth_server": "", "openid_username": "", "openid_identifier": "" }, callback=self.after_login, dont_filter=True )] def after_login(self, response): filename = "1.html" with open(filename, 'wb') as fp: fp.write(response.body)<file_sep>/untitled/Selenium/西域网/Xiyu-2.0.py #coding=utf-8 import random import time import bs4 import pymysql from selenium import webdriver def s(a,b): rand=random.randint(a,b) time.sleep(rand) def get_category(): pass def get_data(): d_prt_name = driver.find_elements_by_xpath( "//div[@class='showArea listMode']/div[@class='product']/div[@class='productName']/a/span") d_type1 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[1]") d_type2 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[2]") d_type3 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[3]") d_type4 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[4]") d_type5 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[5]") d_type6 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[6]") d_type7 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[7]") d_type8 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[8]") d_price = driver.find_elements_by_xpath("//ul[@class='product-parameter']/li/span[@class='now_money']") print(str(len(d_prt_name)) + " " + str(len(d_type1)) + " " + str(len(d_price))) for j in range(len(d_prt_name)): prt_name = d_prt_name[j].text type1 = d_type1[j].text type2 = d_type2[j].text type3 = d_type3[j].text type4 = d_type4[j].text type5 = d_type5[j].text type6 = d_type6[j].text type7 = d_type7[j].text type8 = d_type8[j].text price = d_price[j].get_attribute('title') #print(prt_name + "// " + type1 + "// " + type2 + "// " + type3 + "// " + type4 + "// " + type5 + "// " + type6 + "// " + type7 + "// " + type8 + "// " + price + "// ") mysql_insert(str(prt_name), str(type1), str(type2), str(type3), str(type4), str(type5), str(type6), str(type7),str(type8), str(price)) def next_page(j): driver.find_element_by_xpath("//div[@class='pagintion']/li[@class='pg-next']/a").click() s(4,5) if __name__=='__main__': #定义一系列数组 category_list=['http://www.ehsy.com/category-1228?k=%E5%85%AC%E7%89%9B', 'http://www.ehsy.com/category-811?k=%E5%85%AC%E7%89%9B', 'http://www.ehsy.com/category-17022?k=%E5%85%AC%E7%89%9B', 'http://www.ehsy.com/category-809?k=%E5%85%AC%E7%89%9B', 'http://www.ehsy.com/category-935?k=%E5%85%AC%E7%89%9B', 'http://www.ehsy.com/category-2701?k=%E5%85%AC%E7%89%9B' ] para_brand='公牛' url='http://www.ehsy.com/search?k='+para_brand driver=webdriver.Firefox() driver.get(url) s(3,5) #获取分类,返回category_list get_category() for i in range (len(category_list)): driver.get(category_list[i]) s(4, 5) for j in range(14): get_data() try: next_page(j) except: print("没有下一页") break <file_sep>/Scrapy/ScrapyDemo1/ScrapyDemo1/spiders/xb_spider.py #coding=utf-8 from scrapy import Spider from ScrapyDemo1.items import XBItem from scrapy.selector import Selector __author__ = 'Daemon' class XBSpider(Spider): name='xb' #必须 #allowed_domains = ["qiushibaike.com"] #必须 start_urls=[ 'http://www.qiushibaike.com/8hr/page/1' ] #必须 def parse(self, response): sel=Selector(response) sites=sel.xpath('//div[@class="content"]') # # filename = 'xbdata' # open(filename, 'w+').write(len(sites)) items=[] for site in sites: item=XBItem() item['content']=site.xpath('text()').extract() print (items.append(item)) return items<file_sep>/untitled/代理/代理1.1.py import urllib.request import random from selenium import webdriver url = 'http://www.whatismyip.com.tw/' iplist = ['192.168.3.11:80'] proxy_support = urllib.request.ProxyHandler({'http':random.choice(iplist)}) opener = urllib.request.build_opener(proxy_support) opener.addheaders = [('User-Agent','Test_Proxy_Python3.5_maminyao')] urllib.request.install_opener(opener) response = urllib.request.urlopen(url) html = response.read().decode('utf-8') print(html) response = urllib.request.urlopen(u"http://www.dq123.com") html = response.read().decode('utf-8') print(html)<file_sep>/untitled/Selenium/获取本地页面上的DQ123系列列表.py import pymysql import time from selenium import webdriver def insert_mysql(id,title,class_): db = pymysql.connect("localhost", "root", "1<PASSWORD>6", "dq123") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into tmp_series values('%s','%s','%s')" %(id,title,class_) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() if __name__=="__main__": driver=webdriver.Firefox() driver.get("file:///C:/Users/Administrator/Desktop/dq123-cat .html") time.sleep(5) a_all=driver.find_elements_by_xpath("//a[contains(@id,'classtreeele_')]") for i in range(len(a_all)): id=a_all[i].get_attribute("id") title=a_all[i].get_attribute("title") class_=a_all[i].get_attribute("class") insert_mysql(id,title,class_) print(id+"|"+title+"|"+class_+"\n") <file_sep>/MMBAO.COM遍历URL筛选404链接-1.1/层级遍历-V1.2.py #参数,层级 #使用request进行操作 import urllib.request import requests from bs4 import BeautifulSoup import re import pymysql from selenium import webdriver import time import socket class get_data(): # 获取html函数,参数:url def getHtml(self,url): driver.get(url) #time.sleep(5) html=driver.page_source return html def bak_getHtml(self,url): headers={'user-agent':"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/47.0"} r=requests.get(url,headers=headers) html=r.text #print(html) return html # 获取所有<a>标签中的href属性 def getHref_1(self,url, html): hrefs = [] try: url = url[0:url.index("/", 7)] #将url截断,拼href except ValueError as e: pass soup = BeautifulSoup(html, 'html.parser') a_s = soup.find_all('a') for a in a_s: a_href = a.get('href') #print(a_href) if a_href != None: if a_href != '': if 'http' not in a_href: if 'javascript:' not in a_href: href = url + a_href hrefs.append(href) #print(url+a_href) else: hrefs.append(a_href) return hrefs def getHref_2(self,html): hrefs = [] hrefs_2 = re.findall('"((http)s?://.*?)"', html) for href in hrefs_2: # print(href[0]) if 'mmbao' in href[0]: hrefs.append(href[0]) return hrefs def insert_data2(floor,href1,hrefs2,codes): db = pymysql.connect("localhost", "root", "123456", "tmp", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() for i in range(len(hrefs2)): # 使用 execute() 方法执行 SQL 查询 sql="insert into floor_2 " \ " (floor,href_up,href_current,code)" \ " values('%d','%s','%s','%s')" \ % (floor,href1,hrefs2[i],codes[i]) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def insert_data(floor, href1, href2, code): db = pymysql.connect("localhost", "root", "123456", "tmp", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") # 使用 execute() 方法执行 SQL 查询 sql = "insert into floor_2 " \ " (floor,href_up,href_current,code)" \ " values('%d','%s','%s','%s')" \ % (floor, href1, href2, code) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def get_status(url): try: r = requests.get(url, allow_redirects = False,timeout=5) return r.status_code except requests.exceptions.ConnectTimeout: NETWORK_STATUS = False code='405' return code def get_url(): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select href_current from floor_2 where status=0 limit 1" try: execute = cursor.execute(sql) url = cursor.fetchmany(execute) url=str(url).replace("(('", "").replace("',),)", "") return url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def excute_def(floor,url): hrefs=[] hrefs_2=[] codes=[] print(url+"_____________________________________________________________") if 'jpg' in url: pass elif 'png' in url: pass elif 'mmbao' in url: data = get_data() html = data.getHtml(url) hrefs = data.getHref_1(url, html) hrefs_2 = data.getHref_2(html) for href in hrefs_2: # print(href) hrefs.append(href) for href in hrefs: #code = get_status(href) code = "waiting" #判断是否有.js加持,有的话跳过 if '.js' in href: continue if '.css' in href: continue #print(href) # codes.append(code) #为了防止数据量过多,所以需要在此添加判断机制,将重复的数据过滤掉 is_exist_data=filter_same_data(href) is_exist=int(is_exist_data[0][0]) #print(is_exist) if is_exist==0: insert_data(floor, url, href, code) # insert_data2(floor,url,hrefs,codes) else: pass def filter_same_data(href): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select count(href_current) as cnt from floor_2 where href_current='%s' " %href try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def get_cnt(floor): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor floor=floor-1 cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select count(href_current) as cnt from floor_2 where status=0 and floor='%d'" %(floor) try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) cnt=str(cnt).replace("((", "").replace(",),)", "") return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_log(url,status): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") # 使用 execute() 方法执行 SQL 查询 sql="update floor_2 set status='%s' where href_current='%s' " %(status,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() if __name__=="__main__": driver=webdriver.PhantomJS() floors=5 for i in range (2,floors): floor=i if floor==1: urls=["http://search.mmbao.com/shopList/index.html?shopId=107"] #urls=["http://www.mmbao.com/", "http://search.mmbao.com/", "http://trade.mmbao.com/", "http://dianlan.mmbao.com/", "http://dianqi.mmbao.com/", "http://fujian.mmbao.com/", "http://toutiao.mmbao.com/", "http://baike.mmbao.com/", "http://my.mmbao.com/", "http://dingzhi.mmbao.com/"] for url in urls: excute_def(floor, url) else: cnt=get_cnt(floor) print("还有%s要处理"%cnt) for j in range(int(cnt)): url = get_url() #print(url) try: excute_def(floor, url) status=1 update_status_to_log(url, status) except IndexError as e: status=2 update_status_to_log(url, status) <file_sep>/工品汇/工品汇大版本更新——requests/大版本更新-列表页数据获取.py from urllib import request from bs4 import BeautifulSoup import time def getHtml(url): #print("正在打开网页并获取....") try: headers = { 'Host': 'www.vipmro.com', #'Connection': 'keep-alive', #'Cache-Control': 'max-age=0', #'Accept': 'text/html, */*; q=0.01', #'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0', #'DNT': '1', #'Cookie':'searchshistory1=3287; searchshistory2=3292; _pk_id.1.0aa1=bbf5c91a20434919.1491801107.4.1506132768.1499327581.; Hm_lvt_0d4eb179db6174f7994d97d77594484e=1506132763,1506297666; ASP.NET_SessionId=1hnzbvzsotch0z2wphfu5doe; Hm_lpvt_0d4eb179db6174f7994d97d77594484e=1506304176', #'Referer': 'http://www.doutula.com/article/list?page=1', #'Accept-Encoding': 'gzip, deflate, br', #'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' } data=None req=request.Request(url,data,headers) response = request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") print(Html) while 1==1: try: soup = BeautifulSoup(Html, 'html.parser') cnt = soup.find('div', attrs={'class': 'list-main-total J_t_html'}).find('span').text print(cnt) if '商品' in cnt: break time.sleep(1) except(AttributeError): print("AttributeError") time.sleep(1) except: print("获取html异常!") Html="" return Html class get_data(): def get_category_1(self,html): soup=BeautifulSoup(html,'html.parser') lis=soup.find('div',attrs={'class':'in-ul'}).find('ul').find_all('li',attrs={'class':'J_lb'}) for li in lis: category_name=li.find('a').text category_url = li.find('a').get('href') category_id_tmp=category_url[category_url.rindex("&")+1:100] category_id=category_id_tmp.replace("categoryId=","") print(category_id,category_name) if __name__=="__main__": url='http://www.vipmro.com/search/?ram=0.42325034835106246&keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&categoryId=501011' html=getHtml(url) data=get_data() data.get_category_1(html) <file_sep>/TMALL/施耐德电气/获取tmall旗舰店列表页内容.py import requests from bs4 import BeautifulSoup if __name__=="__main__": url='https://schneiderelectric.tmall.com/p/rd218966.htm?spm=a1z10.1-b-s.w5001-17285251683.4.35d47a58rnMNkP&scene=taobao_shop' s=requests.get(url) content=s.content.decode('gbk') soup=BeautifulSoup(content,'html.parser') href_data=soup.find_all('a') for i in range (len(href_data)): url=href_data[i].get('href') try: text=href_data[i].text except: text="" print(url,"@",text) <file_sep>/MMBAO.COM遍历URL筛选404链接-1.1/获取URL返回状态-V1.0.py import requests import pymysql def get_status(url): try: r = requests.get(url, allow_redirects = False,timeout=5) return r.status_code except requests.exceptions.ConnectTimeout: NETWORK_STATUS = False code='405' return code def get_cnt(): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select count(href_current) as cnt from url_code where code is null " try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) cnt=str(cnt).replace("((", "").replace(",),)", "") return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def get_url(): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select href_current from url_code where code is null limit 1" try: execute = cursor.execute(sql) url = cursor.fetchmany(execute) url=str(url).replace("(('", "").replace("',),)", "") return url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_code(url,code): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql = "update url_code set code='%s' where href_current='%s' " % (code,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": cnt=get_cnt() print("共计%s条数据"%cnt) for i in range (int(cnt)): url=get_url() print(url) code=get_status(url) update_code(url,code)<file_sep>/JD后台/VC后台/新增商品-家装V1.1.py import pymysql import time import random import logging import pyperclip from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.select import Select logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #判断是否登陆成功 name = input("Go?") print(name) #获取mysql表中的待导入数据 data=self.get_upload_data() for i in range (len(data)): #哪里需要填写数据,再进行赋值 driver.get("https://vcp.jd.com/sub_item/item/initAddCategory") self.s(2,3) driver.find_elements_by_css_selector(".datagrid-cell.datagrid-cell-c1-name")[1].click() self.s(1, 1) driver.find_elements_by_css_selector(".datagrid-cell.datagrid-cell-c2-name")[1].click() self.s(1, 1) #选择3级类目 cate3_name=data[i][3] logger.info("cate3_name: "+cate3_name) cate3_data=driver.find_elements_by_css_selector(".datagrid-cell.datagrid-cell-c3-name") for cate3 in cate3_data: logger.info(cate3.text) if cate3_name == cate3.text: cate3.click() logger.info(cate3.text + " clicked") self.s(1, 2) #跳转页面 driver.find_element_by_id("cid3Submit").click() self.s(2,4) ''' driver.find_element_by_css_selector(".combo-text.validatebox-text").clear() brand_name = data[i][4] driver.find_element_by_css_selector(".combo-text.validatebox-text").send_keys(brand_name) cnBrand=data[i][5] driver.find_element_by_id("zhBrand").send_keys(cnBrand) enBrand=data[i][6] driver.find_element_by_id("enBrand").send_keys(enBrand) ''' #Select(driver.find_element_by_id('brandId')).select_by_value("60487") #品牌下拉框 driver.find_element_by_class_name("combo-arrow").click() #s=driver.find_elements_by_xpath("//div[@class='combobox-item' ]") #选择远东电缆品牌 #driver.find_element_by_xpath("//div[@class='combobox-item' ]").click() driver.find_element_by_xpath("//div[@value='60487' ]").click() spuModel=data[i][7] logger.info(spuModel) pyperclip.copy(spuModel) driver.find_element_by_id("modelShow").send_keys(spuModel) #self.s(1,1) #商品名称切换到自定义模式 driver.find_element_by_id("changeToCustmerMode").click() self.s(1,1) driver.find_element_by_id("custmerName").clear() custmerName=data[i][8] print(str(len(custmerName))) #if len(custmerName)>66: #custmerName=custmerName.replace("(FAR EAST CABLE)"," ") driver.find_element_by_id("custmerName").send_keys(custmerName) weight=data[i][12] driver.find_element_by_id("weight").send_keys(weight) length=data[i][13] driver.find_element_by_id("length").send_keys(length) width=data[i][14] driver.find_element_by_id("width").send_keys(width) height=data[i][15] driver.find_element_by_id("height").send_keys(height) marketPrice=data[i][16] driver.find_element_by_id("marketPrice").send_keys(marketPrice) memberPrice=data[i][17] driver.find_element_by_id("memberPrice").send_keys(memberPrice) purchasePrice=data[i][18] driver.find_element_by_id("purchasePrice").send_keys(purchasePrice) #特殊属性,普通商品 #self.s(1,2) pack_Type = data[i][19] logger.info(pack_Type) #pt=driver.find_element_by_id('packType') #print(pt.text) Select(driver.find_element_by_id('packType')).select_by_value("1") #packType.select_by_value("1") #packType.select_by_visible_text(pack_Type) #packType=driver.find_element_by_id("packType") #packType.find_element_by_xpath("//option[@value='1']").click() #包装清单 pkgInfo = data[i][20] driver.find_element_by_id("pkgInfo").send_keys(pkgInfo) #销售单位 sku_Unit = data[i][22] logger.info(sku_Unit) skuUnit = Select(driver.find_element_by_id('skuUnit')) #packType.select_by_value("1") skuUnit.select_by_visible_text(sku_Unit) #s1=input("Go") #print(s1) #确认信息 driver.find_element_by_id('unAuditedSubmit').click() try: self.s(1, 2) driver.find_elements_by_xpath("//div[@id='system_confirm']/div/button")[0].click() print("超出正常范围") except Exception as e: pass self.s(3,4) dianya = data[i][28] logger.info("额定电压%s"%dianya) driver.find_elements_by_xpath("//td[@class='col2']/input")[0].send_keys(dianya) gonglv=data[i][29] driver.find_elements_by_xpath("//td[@class='col2']/input")[1].send_keys(gonglv) brand=data[i][30] driver.find_elements_by_xpath("//td[@class='col2']/input")[11].send_keys(brand) spu_model2 = data[i][31] driver.find_elements_by_xpath("//td[@class='col2']/input")[12].send_keys(spu_model2) #leibie leibie=data[i][32] logger.info(leibie) driver.find_elements_by_class_name("combo-arrow")[0].click() #driver.find_element_by_xpath("//div[@value='632990' ]").click() if leibie=="单芯线": leibie_xpath="//div[@value='632990' ]" driver.find_element_by_xpath(leibie_xpath).click() elif leibie == "电缆线": leibie_xpath = "//div[@value='632992' ]" driver.find_element_by_xpath(leibie_xpath).click() mishu = data[i][35] driver.find_elements_by_class_name("combo-arrow")[1].click() if mishu == "100": mishu_xpath = "//div[@value='441635' ]" driver.find_element_by_xpath(mishu_xpath).click() #类别 driver.find_elements_by_class_name("combo-arrow")[2].click() if leibie=="单芯线": leibie_xpath="//div[@value='441425' ]" driver.find_element_by_xpath(leibie_xpath).click() elif leibie=="电缆线": leibie_xpath = "//div[@value='441461' ]" driver.find_element_by_xpath(leibie_xpath).click() yanse = data[i][33] driver.find_elements_by_class_name("combo-arrow")[3].click() if yanse == "红色": yanse_xpath = "//div[@value='441630' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "黄色": yanse_xpath = "//div[@value='441646' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "蓝色": yanse_xpath = "//div[@value='441662' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "绿色": yanse_xpath = "//div[@value='441677' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "双色": yanse_xpath = "//div[@value='441692' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "黑色": yanse_xpath = "//div[@value='441722' ]" driver.find_element_by_xpath(yanse_xpath).click() xinghao2 = data[i][34] driver.find_elements_by_class_name("combo-arrow")[4].click() if xinghao2 == "BV": xinghao2_xpath = "//div[@value='632979' ]" driver.find_element_by_xpath(xinghao2_xpath).click() elif xinghao2 == "BVR": xinghao2_xpath = "//div[@value='632984' ]" driver.find_element_by_xpath(xinghao2_xpath).click() elif xinghao2 == "YJV": xinghao2_xpath = "//div[@value='698971' ]" driver.find_element_by_xpath(xinghao2_xpath).click() elif xinghao2 == "YJY": xinghao2_xpath = "//div[@value='632988' ]" driver.find_element_by_xpath(xinghao2_xpath).click() #s1=input("Go") #print(s1) self.s(1,2) #跳转下一页,代码页 driver.find_element_by_id('categoryAttrSubmitNew').click() self.s(2, 3) #s2=input("Go") #print(s2) #进入装吧 driver.find_element_by_id('goPCDecorationImg').click() self.s(4,6) ''' driver.find_element_by_xpath("//div[@openpanelid='J_templateManage']").click() self.s(4, 6) driver.find_elements_by_xpath("//div[@class='zb-switch-radio J_templateRadio']/label")[1].click() self.s(1, 2) driver.find_elements_by_css_selector(".zb-normal-red-btn.J_applyTemplateBtn")[0].click() self.s(3, 3) #mobile driver.find_element_by_id("mobile-port").click() self.s(3, 3) driver.find_elements_by_xpath("//div[@class='zb-menu-item J_menuItem']")[1].click() self.s(4, 6) driver.find_elements_by_xpath("//div[@class='zb-switch-radio J_templateRadio']/label")[1].click() self.s(1, 2) driver.find_elements_by_css_selector(".zb-normal-red-btn.J_applyTemplateBtn")[1].click() self.s(3, 3) driver.find_element_by_css_selector(".zb-red-btn.btn-save").click() self.s(2,3) driver.find_element_by_id("decoration-span-close").click() self.s(2, 3) ''' s2=input("Go") print(s2) driver.find_element_by_id('createApply').click() self.s(2,3) driver.find_element_by_id('toApplyList').click() self.s(2, 4) table_id=data[i][0] logger.info(table_id) self.update_status(table_id) def update_status(self,table_id): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update upload_prt_basic_info set status=1 where table_id='%s'" %table_id print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_upload_data(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select * from upload_prt_basic_info where status=0 and 一级分类='家装建材' order by table_id" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/MMBAO/搜索词产品数量打分/搜索词获取网站上的搜索结果数量信息.py import pymysql from selenium import webdriver import time def get_mysql_data(): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,search_keyword from search_keywords_content where status=0" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_status(table_id,prt_count,status,content): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update search_keywords_content set status='%d',content='%s',count='%s' where table_id='%s'" %(status,content,prt_count,table_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #打开买卖宝网站,http://search.mmbao.com/ url="http://search.mmbao.com/" driver=webdriver.Firefox() driver.get(url) data=get_mysql_data() for i in range (len(data)): table_id=data[i][0] search_key=data[i][1] print(search_key) #打开了源网站,定位到搜索框 driver.find_element_by_id("searchBarText").clear() driver.find_element_by_id("searchBarText").send_keys(search_key) driver.find_element_by_id("Button1").click() time.sleep(1) try: prt_count=driver.find_element_by_xpath("//div[@class='fl']/span[2]").text print(prt_count) status=1 content="" count = prt_count[prt_count.rindex("商品") + 2:100] print(prt_count, count) except Exception as e: url=driver.current_url print(e,url) if 'dianlan.mmbao.com' in url: print("跳转到了找电缆") new_url="http://search.mmbao.com/?keywords="+search_key+"&searchSource=1" driver.get(new_url) time.sleep(1) prt_count = driver.find_element_by_xpath("//div[@class='fl']/span[2]").text content="跳转到了找电缆" status=1 count=prt_count[prt_count.rindex("商品")+2:100] print(prt_count,count) else: content="invaild error" prt_count='0' status=2 count=prt_count[prt_count.rindex("商品")+2:100] print(prt_count,count) update_status(table_id,count,status,content) time.sleep(1) <file_sep>/untitled/Requests/千库网素材下载V1.0.py #首先分为几大模块 #1. 登录,只有登录了才能下载 #2. 下载模块,每天只能下载20张图 #2. 图片检索模块,包括搜索关键字,跳过已下载过的图片 import urllib.request import urllib.error from bs4 import BeautifulSoup from lxml import etree import re import os def getHtml(url): #print("正在打开网页并获取....") headers = { 'Host': 'static.doutula.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Accept': 'text/html, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0', 'DNT': '1', 'Cookie':'UM_distinctid=15b9383310948-0002cb8d0502a88-1262694a-1fa400-15b9383310a307; _ga=GA1.2.26294925.1492828501; _gid=GA1.2.2135841525.1498612877; _gat=1', 'Referer': 'http://www.doutula.com/article/list?page=1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' } data=None req=urllib.request.Request(url,data) response = urllib.request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") print(Html) if __name__=="__main__": url = "http://588ku.com/" html = getHtml(url) <file_sep>/待自动化运行脚本/数据备份计划任务.py import pymysql def bak_payment_info(): db = pymysql.connect("localhost", "root", "123456", "invoicing_management_sys") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into balance_of_payment_bak (table_id,user_id,content,account_payable,actual_payment,time_consuming,transaction_date,creation_date,status,bak_content)" \ " select * from balance_of_payment" # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_prt_data-------Error------Message--------:' + str(err)) cursor.close() db.close() def bak_car_owner(): db = pymysql.connect("localhost", "root", "123456", "invoicing_management_sys") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into car_owner_info_bak (user_id,plate_number,owners_name,car_type,phone_number)" \ " select * from car_owner_info " # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_prt_data-------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": bak_payment_info() bak_car_owner() <file_sep>/untitled/JSON/test-dq123表单.py #code=utf-8 import urllib.request import urllib.parse from urllib import request from bs4 import BeautifulSoup import time from selenium import webdriver def getHtml(url): req = request.Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0") req.add_header("Host", "www.dq123.com") response = request.urlopen(req) html = response.read().decode('utf-8') # print(html) return html def get_Value(html): soup=BeautifulSoup(html,'html.parser') _csrf_scripts=soup.findAll('script') for _csrf_script in _csrf_scripts: #print(_csrf_script) _csrf_script=str(_csrf_script) if '_csrf' in str(_csrf_script): #print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<") #print(_csrf_script) script_data=_csrf_script.split('var ') print(script_data) initpagesize=script_data[2].replace("initpagesize = ","").replace(";\r\n ","") print("initpagesize:",initpagesize) s_kw=script_data[3].replace("s_kw = '","").replace("';\r\n ","") print("s_kw:",s_kw) _csrf=script_data[7].replace("_csrf = '","").replace("';\r\n ","") print("_csrf:",_csrf) ver=script_data[8].replace("ver = '","").replace("';\r\n ","") print("ver:",ver) return initpagesize,s_kw,_csrf,ver if __name__=="__main__": kw='IZMB5-A1600-CW' url="http://www.dq123.com/price/index.php?kw="+kw time.sleep(15) html=getHtml(url) #print(html) #返回各项表单参数 initpagesize, s_kw, _csrf,ver=get_Value(html) #把要发送的数据写成字典 value={ 'v':ver, '_csrf':_csrf, 'factoryid':'', 'catrgoryid':'', 'classid':'', 'keywordstr':s_kw, 'pageindex':'1', 'initpagesize':initpagesize } ''' data=urllib.parse.urlencode(value).encode('utf-8')#对value进行编码,转换为标准编码# print(data) header_dict={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0'} url2='http://www.dq123.com/price/getpricelistjson.php' req=urllib.request.Request(url='%s%s%s'%(url2,'?',data),headers=header_dict) res=urllib.request.urlopen(req) res=res.read().decode('utf-8') print(res) ''' <file_sep>/untitled/Selenium/工品汇/工品汇2.0/工品汇-前置类目获取V1.0.py import random import re import time import bs4 import xlrd import xlsxwriter from selenium import webdriver import pymysql def company_info(): company_name="德力西" return company_name def s(a,b): rand=random.randint(a,b) time.sleep(rand) def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) def get_category_1(): cate_1_list=[] s(4,6) list_a=driver.find_elements_by_xpath("//label[@class='J_cate']/a") print("一级类目共"+str(len(list_a))+"条") for i in range(len(list_a)): cate_1_url=list_a[i].get_attribute("href") cate_1_list.append(cate_1_url) return cate_1_list #获取二级类目 def get_category_2(cate_1_url): cate_2_list=[] driver.get(cate_1_url) s(3,5) list_a = driver.find_elements_by_xpath("//label[@class='J_cate']/a") print("二级类目共" + str(len(list_a)) + "条") if len(list_a) == 0: print("没有二级类目") cate_2_list.append(cate_1_url) else: for i in range(len(list_a)): cate_2_url = list_a[i].get_attribute("href") cate_2_list.append(cate_2_url) print(cate_2_list) return cate_2_list def insert_category(url): company_name=company_info() #再导入数据表之前,还需要拼个url存着 db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into vipmro_url " \ " (company_name,category_url)" \ " values('%s','%s')" \ % (company_name,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() if __name__=="__main__": cate_1_list=[] cate_2_list=[] driver=webdriver.Firefox() url = "http://www.vipmro.com/search?keyword=%25E8%2589%25AF%25E4%25BF%25A1&brandId=232" driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) driver.get("http://www.vipmro.com/search?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&brandId=104") s(3,5) driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() s(3,5) cate_1_list=get_category_1() #print(cate_1_list) #print(len(cate_1_list)) for i in range (len(cate_1_list)): cate_1_url=cate_1_list[i] #print(cate_1_url) cate_2_list=get_category_2(cate_1_url) for j in range (len(cate_2_list)): print(cate_2_list[j]) insert_category(cate_2_list[j]) print("-----------------------------------") <file_sep>/JD后台/VC后台/获取后台的、采购价.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) driver.get('https://vcp.jd.com/sub_item/price/initPriceListPage') self.s(3, 4) prt_data=self.get_sku_id() for i in range (len(prt_data)): sku_id=prt_data[i][0] print(sku_id) driver.find_element_by_id('wareId').clear() driver.find_element_by_id('wareId').send_keys(sku_id) self.s(1,2) driver.find_element_by_css_selector('.btn.btn-primary').click() self.s(2,3) caigou_price = driver.find_element_by_id('td_priceVo').text print(caigou_price) self.update_caigou_price(sku_id,caigou_price) def get_sku_id(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 主商品编号 from jiazhuang_caigoujia where 采购价=''" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_caigou_price(self,sku_id,caigou_price): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update jiazhuang_caigoujia set 采购价='%s' where 主商品编号 ='%s'" %(caigou_price,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/TMALL/罗格朗/判断把所有详情图放在一个文件夹的可行性.py import pymysql import xlwt def get_img_info(): db = pymysql.connect("localhost", "root", "123456", "legrand") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select img_url,download_status from legrand_prt_img where img_type='desc_img'" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(prt_id): db = pymysql.connect("localhost", "root", "123456", "legrand") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_desc set status=1 where prt_id ='%s'" %prt_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": wbk = xlwt.Workbook() sheet1 = wbk.add_sheet('sheet 1') try: data = get_img_info() for i in range (len(data)): img_url=data[i][0] download_status=data[i][1] print(img_url,download_status) img_name=img_url[img_url.rindex("/")+1:1000] sheet1.write(i, 0, img_name) sheet1.write(i,1,img_url) sheet1.write(i,2,download_status) #update_status(prt_id) wbk.save('图片查重.xls') except IndexError as e: print(e) wbk.save('图片查重.xls') <file_sep>/MMBAO.COM遍历URL筛选404链接-1.1/筛选数据表批量url的404等商品未找到异常-V1.2.py import urllib.request import urllib.error from bs4 import BeautifulSoup import re import os import pymysql import xlrd def insert_data(url,sheetName,info,state): db = pymysql.connect("localhost", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into MMB_URL_FILTER(url,sheet_name,info,state)"\ "values('%s','%s','%s','%s')"\ %(url,sheetName,info,state) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def getHtml(url): #print("正在打开网页并获取....") try: headers = { 'Host': 'static.doutula.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Accept': 'text/html, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0', 'DNT': '1', 'Cookie':'UM_distinctid=15b9383310948-0002cb8d0502a88-1262694a-1fa400-15b9383310a307; _ga=GA1.2.26294925.1492828501; _gid=GA1.2.2135841525.1498612877; _gat=1', 'Referer': 'http://www.doutula.com/article/list?page=1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' } data=None req=urllib.request.Request(url,data) response = urllib.request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") #print(Html) except: Html="" return Html def filter_url_1(html,sheet_name): try: soup=BeautifulSoup(html,"html.parser") error_1=soup.find("div",attrs={"class":"s1"}).text error_1_msg=error_1.replace("\n","").replace(" ","") print(error_1_msg) state=1 insert_data(url,sheet_name, error_1_msg, state) return state except: print("pass the first fliter solution") state=0 return state def filter_url_2(html,state,sheet_name): if state==0: try: soup=BeautifulSoup(html,"html.parser") error_1=soup.find("div",attrs={"class":"good_list clearfix"}).find('div').find('span').text print(error_1.replace("\n","")) if "没有您搜索的商品哦" in error_1: error_1_msg=error_1.replace("\n","") #print(error_1_msg) state = 2 insert_data(url,sheet_name, error_1_msg, state) else: print("pass the second fliter solution") state = 0 #insert_data(url, error_1, state) return state except: print("pass the second fliter solution") state=0 return state else: return state def filter_url_3(html, state,sheet_name): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"class": "no-search"}).find('p').text print(error_1) if error_1 == "您搜索的电缆暂无报价,赶紧试试": error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,sheet_name, error_1_msg, state) else: print("pass the third fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the third fliter solution") state = 0 return state else: return state def filter_url_4(html, state,sheet_name): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"class": "search-none clearfix yahei mt20 cry-icon"}).find('h2').text print(error_1) if "非常抱歉!没有找到与" in error_1: error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,sheet_name, error_1_msg, state) else: print("pass the third fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the third fliter solution") state = 0 return state else: return state def filter_url_5(html, state,sheet_name): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"class": "search-none clearfix yahei mt20 cry-icon"}).find('h2').text print(error_1) if "非常抱歉!没有找到" in error_1: error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,sheet_name, error_1_msg, state) else: print("pass the fourth fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the fourth fliter solution") state = 0 return state else: return state def filter_url_6(html,sheet_name, state): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"id": "SD_content"}).text print(error_1) if "您查看的店铺已关闭或暂时无商品" in error_1: error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,sheet_name, error_1_msg, state) else: print("pass the fifth fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the fifth fliter solution") state = 0 return state else: return state #从excel中获取url的列表数据 def get_data_from_excel(sheet_num): data=xlrd.open_workbook(r"D:\BI\关键词筛选\竞价URL.xlsx") #打开excel sheetName = data.sheet_names()[sheet_num] table=data.sheets()[sheet_num] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 url_lists=[] print(sheetName) for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss url_lists.append(ss) return url_lists,sheetName if __name__=="__main__": #url来自数据库,或者excel都可以 for x in range (5): sheet_num=x url_lists,sheetName=get_data_from_excel(sheet_num) for i in range(len(url_lists)): url=url_lists[i] url=url[0] #url='http://trade.mmbao.com/s_2017071400096566.html' print(i+1,url) # url='http://search.mmbao.com/0_0_0.html?keywords=YJHLV' html = getHtml(url) if html=="": state='error' insert_data(url, sheetName, "", state) else: # 分析一波html state = filter_url_1(html, sheetName) state = filter_url_2(html, state, sheetName) state = filter_url_3(html, state, sheetName) state = filter_url_4(html, state, sheetName) state = filter_url_5(html, state, sheetName) if state == 0: info = "" insert_data(url, sheetName, info, state) <file_sep>/untitled/Selenium/dq123/dq123数据获取-20170831/DQ123-工品汇&DQ123数据匹配.py #遍历vipmro的商品数据,到dq123中进行匹配 import pymysql def get_vipmro_prt_info(): db = pymysql.connect("localhost", "root", "123456", "vipmro") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,prt_type from prt_main_info where is_sale=1 and link_status=0 limit 1 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def check_the_same_data(prt_type): db = pymysql.connect("localhost", "root", "123456", "yidun") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_no,prt_name from yidun_prt_lists where prt_name like '%"+prt_type+"%' " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_link_info(prt_id,prt_type,dq_prt_no): db = pymysql.connect("localhost", "root", "123456", "vipmro") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_link_info (prt_id,prt_type,dq_prt_no) values('%s','%s','%s')" %(prt_id,prt_type,dq_prt_no) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(prt_id,prt_type_original,link_status): db = pymysql.connect("localhost", "root", "123456", "vipmro") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update prt_main_info set link_status='%d' where prt_id='%s' and prt_type ='%s'" %(link_status,prt_id,prt_type_original) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #获取商品型号,prt_id,prt_type for i in range(2000): data=get_vipmro_prt_info() prt_id=data[0][0] prt_type_original = data[0][1] prt_type=prt_type_original.replace("商品型号","") print("待匹配数据",prt_id,prt_type) dq_datas=check_the_same_data(prt_type) print("=>相似数据共%s条"%str(len(dq_datas))) status=0 for dq_data in dq_datas: dq_prt_no=dq_data[0] dq_prt_name=dq_data[1] print("==>",dq_prt_no,dq_prt_name) if dq_prt_name==prt_type: print(">>>>完全匹配",dq_prt_name) insert_link_info(prt_id,prt_type,dq_prt_no) status=1 if status==1: link_status=1 else: print("没有完全相同的数据") link_status = 2 update_status(prt_id,prt_type_original,link_status) <file_sep>/HTML处理/保存html内容到excel.py import pymysql import xlwt def get_html(): db = pymysql.connect("localhost", "root", "123456", "mmbao") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") #sql = "select prt_id,prt_desc from legrand_prt_desc where prt_id in ( select spu_id from spu表) group by prt_id,prt_desc" sql = "select prt_id,prt_title,series,pc_content,content_table from mmbao_prt_pc_content where pc_content not like '%bgcolor=%' " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(prt_id): db = pymysql.connect("localhost", "root", "123456", "legrand") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_desc set status=1 where prt_id ='%s'" %prt_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_new_desc(series): db = pymysql.connect("localhost", "root", "123456", "mmbao") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") #sql = "select prt_id,prt_desc from legrand_prt_desc where prt_id in ( select spu_id from spu表) group by prt_id,prt_desc" sql = "select series,prt_desc,new_prt_desc from mmbao_prt_new_desc where series='%s' " %series try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": wbk = xlwt.Workbook() sheet1 = wbk.add_sheet('sheet 1') sheet1.write(0, 0, 'prt_id') sheet1.write(0, 1, 'prt_title') sheet1.write(0, 2, 'series') sheet1.write(0, 3, 'prt_desc') data = get_html() for i in range(0, len(data)): try: prt_id = data[i][0] prt_title = data[i][1] series = data[i][2] pc_content = data[i][3] prt_desc = data[i][4] # print(prt_id,prt_desc) new_desc_data = find_new_desc(series) #print(new_desc_data) new_prt_desc = new_desc_data[0][2] img_desc = pc_content.split('</table>')[1] print(img_desc) new_pc_content = str(new_prt_desc) + img_desc # print(new_pc_content) sheet1.write(i + 1, 0, prt_id) sheet1.write(i + 1, 1, prt_title) sheet1.write(i + 1, 2, series) sheet1.write(i + 1, 3, new_pc_content) # update_status(prt_id) except IndexError as e: pass wbk.save('html.xls') <file_sep>/JD后台/图片上传-商品主图上传/商品主图上传V0726-2.py import pymysql import time import random import logging import win32gui import win32con from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.select import Select logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #判断是否登陆成功 name = input("Go?") print(name) #通过url,找到需要修改图片的商品 #sku_id='7952991' sku_data=self.get_sku_id() for i in range(len(sku_data)): sku_id = sku_data[i][0] try: init_img_url="https://vcp.jd.com/sub_item/itemPic/initEditItemPicInfo?wareId=%s&saleState=1&isProEdit=true"%sku_id driver.get(init_img_url) print(init_img_url) self.s(2,3) del_imgs=driver.find_elements_by_class_name("delete-img") for x in range(len(del_imgs)-1): driver.find_element_by_class_name("delete-img").click() self.s(1,2) #删除完当前的图片后,使用win32gui去上传图片 driver.find_element_by_id("img-plus-id").click() self.s(1,2) #获取句柄 # win32gui dialog = win32gui.FindWindow('#32770', u'打开') # 对话框 ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮Button img_path=sku_data[i][5] first_img=sku_data[i][6] first_img_path='"%s"'%first_img print(first_img_path) win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, first_img) # 往输入框输入绝对地址 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) # 按button n=0 while 1==1: try: if n>20: break driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() break except Exception as e: print("waitting") self.s(3, 4) n+=1 #上传完成第一张主图后,还有后面的四张,按照数据表吧,先调通整个流程 #设置首图 driver.find_element_by_xpath("//div[@id='img-widget-1']/div[@class='img-bar-div']/img[@class='heart-img']").click() self.s(1,2) driver.find_element_by_id("img-plus-id").click() self.s(1,2) # win32gui dialog = win32gui.FindWindow('#32770', u'打开') # 对话框 ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮Button second=sku_data[i][7] third=sku_data[i][8] forth=sku_data[i][9] fifth=sku_data[i][10] other_path='"%s" "%s" "%s" "%s"'%(second,third,forth,fifth) print(other_path) win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None,other_path ) # 往输入框输入绝对地址 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) # 按button self.s(4,8) n = 0 while 1 == 1: try: if n > 20: break driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() break except Exception as e: print("waitting") self.s(2, 4) n += 1 driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() self.s(1, 2) #切换到透明图 driver.find_elements_by_xpath("//ul[@class='tabs']/li")[1].click() self.s(1,2) try: driver.find_element_by_xpath("//div[@class='img-bar-div-lucency']/img[@class='delete-img']").click() except Exception as e: print(e) self.s(2, 3) # 删除完当前的图片后,使用win32gui去上传图片 driver.find_element_by_id("img-plus-id-lucency").click() self.s(2, 3) #chrome://settings/content/flash # 获取句柄 # win32gui dialog = win32gui.FindWindow('#32770', u'打开') # 对话框 ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮Button lucency_img=sku_data[i][11] win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, lucency_img) # 往输入框输入绝对地址 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) # 按button n = 0 while 1 == 1: try: if n > 20: break driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() break except Exception as e: print("waitting") self.s(2, 4) n += 1 self.s(2, 4) #到以上,已经完成整个商品的图片上传 #提交任务 #name = input("Go?") #print(name) driver.find_element_by_id("mySubmitLucency").click() self.upload_status(sku_id,1) self.s(3,4) except: self.upload_status(sku_id,2) #凤鸣 def get_sku_id(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select * from update_img_for_count where status=0 and vc_shop='家装' " #print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def upload_status(self,sku_id,status): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update update_img_for_count set status='%d' where sku_id='%s' " %(status,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('----------upload_status-----Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/ZYDMALL/zydmall产品价格调整监控/商品价格及其他信息匹配.py import pymysql import time def get_prt_id(): db = pymysql.connect("localhost", "root", "123456", "zydmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select zyd_prt_id,mmbao_sku_id from zyd_mmb_prt_link where status=0" #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_zyd_prt_data(zyd_prt_id): db = pymysql.connect("localhost", "root", "123456", "zydmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,po_number,prt_url,prt_type,face_price,weight from prt_data where prt_id='%s' and status=1 " %zyd_prt_id #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_mmb_prt_data(mmbao_sku_id): db = pymysql.connect("localhost", "root", "123456", "mmbao") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select sku_id,prt_id,po_number,sku_title,old_price,weight from t_prt_sku where sku_id='%s' " % mmbao_sku_id #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def check_same_data(check_a,check_b): #print("-----",check_a,check_b) if check_a==check_b: status=0 else: if round(float(check_b) - float(check_a), 2)==0: status=0 else: status = 1 # #print("tmp2",check_a + "//" + check_b,str(data)) #print("tmp3", check_a + "//" + check_b) return status def insert_data(zyd_prt_id,mmbao_sku_id,mmb_po_number,attribute_name,old_value,new_value): db = pymysql.connect("localhost", "root", "123456", "mmbao") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into value_check (zyd_prt_id,mmbao_sku_id,mmb_po_number,attribute_name,old_value,new_value) values('%s','%s','%s','%s','%s','%s')" \ %(zyd_prt_id,mmbao_sku_id,mmb_po_number,attribute_name,old_value,new_value) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_data---------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(zyd_prt_id): db = pymysql.connect("localhost", "root", "123456", "zydmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update zyd_mmb_prt_link set status=1 where zyd_prt_id='%s' " %zyd_prt_id # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_data---------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #将两个平台的id数据取出来 data=get_prt_id() #print(data) for i in range (len(data)): zyd_prt_id=data[i][0] mmbao_sku_id = data[i][1] #zyd_prt_id='301612' #mmbao_sku_id='2017070500088035' #分为两块,分别去查询id对应的商品信息 #查询zyd的商品记录 print(mmbao_sku_id,zyd_prt_id) zyd_data = find_zyd_prt_data(zyd_prt_id) print(zyd_data) #查询mmb的商品记录 mmb_data = find_mmb_prt_data(mmbao_sku_id) #print(mmb_data) #分别将两边查询到的数据,相同的字段值进行匹配 #zyd try: zyd_prt_id=zyd_data[0][0] zyd_po_number=zyd_data[0][1] zyd_prt_url=zyd_data[0][2] zyd_prt_type=zyd_data[0][3] zyd_face_price=zyd_data[0][4] zyd_weight=zyd_data[0][5] zyd_face_price=zyd_face_price.replace("¥","") zyd_prt_type=zyd_prt_type.upper() #print(zyd_face_price) mmb_sku_id=mmb_data[0][0] mmb_prt_id=mmb_data[0][1] mmb_po_number=mmb_data[0][2] mmb_sku_title=mmb_data[0][3] mmb_old_price=mmb_data[0][4] mmb_old_price=str(round(float(mmb_old_price),2)) #print(mmb_old_price) mmb_weight=mmb_data[0][5] try: mmb_weight=str(int(float(mmb_weight)*1000)) except ValueError as e: mmb_weight='' try: mmb_prt_type=mmb_sku_title.split(";")[-1] except ValueError as e: mmb_prt_type='' mmb_prt_type=mmb_prt_type.upper() status1=check_same_data(zyd_po_number,mmb_po_number) if status1==1: #print("po_number: ",zyd_po_number,"…",mmb_po_number) pass #print("---------",zyd_face_price, mmb_old_price) status2 = check_same_data(zyd_face_price, mmb_old_price) print("face_price: ", zyd_face_price, "…", mmb_old_price, zyd_prt_id, mmbao_sku_id) insert_data(zyd_prt_id, mmbao_sku_id, mmb_po_number, "face_price", mmb_old_price, zyd_face_price) ''' status3 = check_same_data(zyd_weight, mmb_weight) if status3==1: #print("weight: ",zyd_weight,"…", mmb_weight) pass status4 = check_same_data(zyd_prt_type, mmb_prt_type) if status4==1: #print("prt_type: ",zyd_prt_type,"…", mmb_prt_type) pass #time.sleep(10) ''' update_status(zyd_prt_id) except IndexError as e: update_status(zyd_prt_id) <file_sep>/日常工作/华为ppt.py from selenium import webdriver from bs4 import BeautifulSoup import os import urllib.request import time def find_imgs(html): soup=BeautifulSoup(html,"html.parser") imgs_data=soup.find_all('p') print(len(imgs_data)) for i in range (len(imgs_data)): try: img_url=imgs_data[i].find('img').get('src') img_name=str(i+1)+".png" img_url="https"+img_url.split("https")[1] print(img_name,img_url) getAndSaveImg(img_url, img_name) except AttributeError as e: pass #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(img_url, img_name): if (len(img_url) != 0): fileName = img_name file_path=u"D:\\BI\\HUAWEI\\img" urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) if __name__=="__main__": #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() url="http://www.hroot.com/d-9367999.hr?%E9%87%8D%E7%A3%85%EF%BC%9A%E5%8D%8E%E4%B8%BA%E4%BA%BA%E5%8A%9B%E8%B5%84%E6%BA%90%E7%AE%A1%E7%90%86%E7%BA%B2%E8%A6%812.0%EF%BC%8C87%E9%A1%B5PPT%E5%85%A8%E6%8F%AD%E7%A7%98%EF%BC%81-HR360%E5%B7%A5%E5%9D%8A-hr" driver.get(url) time.sleep(5) html=driver.page_source find_imgs(html)<file_sep>/TMALL/获取整个不规则列表页的所有url/获取tmall-delixi列表页内容.py import requests from bs4 import BeautifulSoup if __name__=="__main__": #url='https://abb.tmall.com/category-1365452982.htm?spm=a1z10.5-b-s.w4011-15436620852.36.7f946473CX76JZ&tsearch=y#TmshopSrchNav' url='https://abb.tmall.com/category-1365452981.htm?spm=a1z10.5-b-s.w4011-15436620852.33.7f946473CX76JZ&tsearch=y#TmshopSrchNav' s=requests.get(url) content=s.content.decode('gbk') soup=BeautifulSoup(content,'html.parser') href_data=soup.find_all('a') for i in range (len(href_data)): url=href_data[i].get('href') print(url) <file_sep>/TMALL/罗格朗/将详情url调整链接.py import pymysql def get_prt_img(): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select prt_id,img_url,download_status from legrand_prt_img " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_prt_desc(prt_id,img_url,new_img_url): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update legrand_prt_desc set prt_desc=replace(prt_desc,'%s','%s') where prt_id='%s'" %(img_url,new_img_url,prt_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_prt_desc_tmp(img_url,new_img_url): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update legrand_prt_desc set prt_desc=replace(prt_desc,'%s','%s')" %(img_url,new_img_url) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc_tmp-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": data_imgs=get_prt_img() for i in range (len(data_imgs)): prt_id=data_imgs[i][0] img_url=data_imgs[i][1] download_status=data_imgs[i][2] print(prt_id,img_url,download_status) if download_status==1: new_img_url = "/upload/prt/legrand/" + prt_id + "/" + img_url[img_url.rindex("/") + 1:1000] print(prt_id,new_img_url) else: new_img_url = "" print(prt_id,new_img_url) update_prt_desc(prt_id,img_url, new_img_url) #img_url='data-ks-lazyload' #new_img_url="src" #update_prt_desc_tmp(img_url,new_img_url) <file_sep>/untitled/工具/sql&excel关键字数据筛选保存.py import pymysql import xlrd import xlsxwriter def print_xls(): data=xlrd.open_workbook(r"C:\Users\Administrator\Desktop\test_info.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 Company_Name=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss Company_Name.append(ss) return Company_Name def save_excel(fin_result1,fin_result2,fin_result3,fin_result4): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\test1.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result1)): tmp.write(i, 0, fin_result1[i]) tmp.write(i, 1, fin_result2[i]) tmp.write(i, 2, fin_result3[i]) tmp.write(i, 3, fin_result4[i]) def insert_mysql(id,prt_name,price,company,issuedate,cate1,cate2,series,detail): db = pymysql.connect("192.168.180.147", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into DQ123PRTINFO" \ " (PRT_ID,PRT_NAME,PRICE,COMPANY,RELEASE_DATE,CATE1,CATE2,SERIES,TYPE1,VALUE1,TYPE2,VALUE2,TYPE3,VALUE3,TYPE4,VALUE4,TYPE5,VALUE5,TYPE6,VALUE6,TYPE7,VALUE7,TYPE8,VALUE8,TYPE9,VALUE9,TYPE10,VALUE10,TYPE11,VALUE11,TYPE12,VALUE12,TYPE13,VALUE13,TYPE14,VALUE14,TYPE15,VALUE15,TYPE16,VALUE16,TYPE17,VALUE17)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (id,prt_name,price,company,issuedate,cate1,cate2,series,tmp0,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9,tmp10,tmp11,tmp12,tmp13,tmp14,tmp15,tmp16,tmp17,tmp18,tmp19,tmp20,tmp21,tmp22,tmp23,tmp24,tmp25,tmp26,tmp27,tmp28,tmp29,tmp30,tmp31,tmp32,tmp33) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() if __name__=="__main__": type=["以电线结尾"] <file_sep>/Scrapy/jiandan/jiandan/items.py # -*- coding: utf-8 -*- import scrapy class JiandanItem(scrapy.Item): # define the fields for your item here like: image_urls = scrapy.Field() # 图片的链接<file_sep>/JD/JD-德力西开关/将图片名称拼接成详情内容HTML.py import pymysql import time def get_prt_id(): db = pymysql.connect("localhost", "root", "123456", "delixi_diangong", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select prt_id from prt_img_info group by prt_id order by table_id" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_prt_imgs(prt_id): db = pymysql.connect("localhost", "root", "123456", "delixi_diangong", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select prt_id,img_name,img_src,img_num from prt_img_info where prt_id='%s' and img_type='img_desc'" %prt_id try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_into_prt_desc(prt_id,prt_content): db = pymysql.connect("localhost", "root", "123456", "delixi_diangong", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into prt_desc (prt_id,prt_desc) values('%s','%s')" %(prt_id,prt_content) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #抓出所有的prt_id data=get_prt_id() #遍历所有的prt_id print("有%s条待处理"%str(len(data))) for i in range(len(data)): prt_id=data[i][0] print(prt_id) #反查img_info表,取出prt_id下,所有的详情图片 data2=get_prt_imgs(prt_id) print("当前prt_Id下,有%s张图片需要拼接"%str(len(data2))) div_begin = '<div id="J-detail-content">' br = '<br/>' div_end = '</div>' prt_content=div_begin+br for x in range (len(data2)): prt_id=data2[x][0] img_id=data2[x][1] img_url=data2[x][2] #三块组成 #正式环境下,需要用服务器上的图片地址 img_url="/upload/prt/dlx/"+prt_id+"/"+img_id img='<img alt="" style="width:100%" id="'+img_id+'" src="'+img_url+'"/>' prt_content+=img+br prt_content+=div_end print(prt_content) insert_into_prt_desc(prt_id,prt_content) #time.sleep(1) <file_sep>/untitled/Selenium/dq123/public_proxy_func.py #输入:url参数 #输出:html import urllib.request import pymysql import random from bs4 import BeautifulSoup ip_list=[] def get_data(): try: conn = pymysql.connect("192.168.180.147", "root", "<PASSWORD>", "<PASSWORD>") cursor = conn.cursor() #count获取的是满足查询条件的数量 count=cursor.execute('select ip_address from proxy_info') ## 或者使用fetchmany(),打印表中的多少数据 ##info = cursor.fetchmany(count) #for循环count次,使用fetchone()将游标中的值遍历 for i in range (int(count)): list=cursor.fetchone() list=str(list).replace("('","").replace("',)","") ip_list.append(list) #print(list) conn.close() except: return get_data() def request_url(url): print('尝试访问'+url) response = urllib.request.urlopen(url) #print(response.info()) html = response.read().decode('utf-8') return html def check_ip(url,ip_list): try: #将参数随机化,从数据表获取 rand_1=random.randint(1,len(ip_list)) ip_address=ip_list[rand_1] proxy_support=urllib.request.ProxyHandler({'http':ip_address}) opener=urllib.request.build_opener(proxy_support) opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0')] urllib.request.install_opener(opener) html=request_url(url) return html except: print('IP访问异常-check_ip()') return check_ip(url,ip_list) def main(url): #url = "http://www.whatismyip.com.tw" get_data() print(ip_list) html=check_ip(url,ip_list) return html <file_sep>/untitled/代理/proxy_eg.py import urllib.request url="http://www.whatismyip.com.tw" proxy_support=urllib.request.ProxyHandler({'http':'192.168.127.12:8090'}) opener=urllib.request.build_opener(proxy_support) opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0')] urllib.request.install_opener(opener) response=urllib.request.urlopen(url) html=response.read().decode('utf-8') print(html) <file_sep>/tornado/tornado模板.py #通用tornado模板 from tornado import httpserver,web,ioloop class MainPageHandler(web.RequestHandler): def get(self,*args,**kwargs): self.write("hello world!") application = web.Application([ (r"/", MainPageHandler), ]) if __name__=="__main__": http_server = httpserver.HTTPServer(application) http_server.listen(8085) ioloop.IOLoop.current().start()<file_sep>/untitled/Funny/ascii.py from PIL import Image class pictureToStr(): def __init__(self): self.width = 80 self.height = 80 self.charList = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") #self.charList = list(".#") self.txt="" # 将256灰度映射到70个字符上 #主要就是这个函数的结构,值得深思 def get_char(self,r, g, b, alpha=256): if alpha == 0: return ' ' length = len(self.charList) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (256.0 + 1) / length return self.charList[int(gray / unit)] #重置图片尺寸 # PIL.Image.NEAREST:最低质量, PIL.Image.BILINEAR:双线性,PIL.Image.BICUBIC:三次样条插值,Image.ANTIALIAS:最高质量 def convert(self,openFileName): #打开图片,返回一个image对象 image = Image.open(openFileName) image = image.resize((self.width, self.height), Image.ANTIALIAS) for i in range(self.height): for j in range(self.width): #遍历每一个像素,使用闭包函数get_char() #*image.getpixel((j,i)),*的意思是动态参数(参数个数不定) #对应RGBA a=image.getpixel((i,j)) #print(a) self.txt += self.get_char(*image.getpixel((j, i))) self.txt +='\n' def saveStr(self,saveFileName): with open(saveFileName,"w") as f : f.write(self.txt) def start(self): openFileName="ascii_dora.png" #openFileName = input("请输入需要打印图片的名称,并加上后缀名:") print("开始将图片转化为字符!") self.convert(openFileName) saveFileName="123.txt" #saveFileName = input("请输入文件保存名称,并加上后缀名:") print("正在保存文件到本地!") self.saveStr(saveFileName) p = pictureToStr() p.start()<file_sep>/Scrapy/ScrapyDemo1/ScrapyDemo1/main.py from scrapy import cmdline cmdline.execute("scrapy crawl xb -o xbjson.json -t json".split())<file_sep>/untitled/Selenium/工品汇/伊顿电气-20170831/图片筛选-美工图片还原操作.py import os import urllib.request import pymysql import sys import shutil #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_id,img_name,original_url,img_path from prt_img_info where state=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #复制图片 def copy_Img(prt_id_exist,prt_id,img_name): #暂时不加异常捕捉机制,试运行 src="D:\\BI\\Upload\\IMG\\"+prt_id_exist+"\\"+img_name dst="D:\\BI\\Upload\\IMG\\"+prt_id+"\\"+img_name print("waiting for "+src+" =>=>=>=>=>=> "+dst) file_path = u"D:\\BI\\Upload\\IMG\\" + prt_id createFileWithFileName(file_path, img_name) shutil.copyfile(src,dst) print("复制成功") def update_state(prt_id,url,status): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update prt_img_info set state='%d' where prt_id='%s' and original_url='%s'" %(status,prt_id,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def is_existed(img_name,url): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,original_url,img_path from prt_img_info where img_name='%s' and original_url='%s' and is_repeat=0 limit 1" %(img_name,url) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_path(status,prt_id_exist, prt_id,url, img_path_exist): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update prt_img_info set state='%d',img_path='%s' where prt_id='%s' and original_url='%s'" %(status,img_path_exist,prt_id,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": for i in range (5244): data=get_prt_data() prt_id=data[0][0] img_name=data[0][1] url=data[0][2] img_path=data[0][3] print(prt_id,img_name,url,img_path) data2=is_existed(img_name,url) if len(data2)==0: print("不存在相同的耶") print("放屁") state=3 #update_state(prt_id,url,state,is_repeat,"") else: prt_id_exist=data2[0][0] img_path_exist=data2[0][3] print("已存在相同的数据prt_id=%s"%prt_id_exist,img_path_exist) if prt_id_exist==prt_id: print("the same file") state=5 else: try: #copy_Img(prt_id_exist, prt_id, img_name) # 返回状态更新,以及path更新 state = 4 update_path(state,prt_id_exist, prt_id, url,img_path_exist) except: state=6 #update_state(prt_id,url,state,is_repeat,"") #copy_Img(prt_id,img_name) update_state(prt_id,url,state)<file_sep>/TMALL/数据分析架构模式化/tmall商品图片筛选下载/MD5校验查重.py #3个文件夹,需要进行遍历, #1. 将每张图片都反向的从文件夹中读取 #2. 获取该图片的MD5串码 #3. 将串码、文件名称、路径都保存到新的数据表 #4. 将prt_img和新MD5表联结查询 #5. 判断,进行数据筛选 import pymysql import os import shutil import re from PIL import Image import hashlib def foreach(rootDir): files_img = [] for root, dirs, files in os.walk(rootDir): for file in files: file_name = os.path.join(root, file) files_img.append(file_name) for dir in dirs: foreach(dir) return files_img def get_excel_data(): excel_dir = "D:\BI\TMALL\\upload\prt" path = os.path.abspath(excel_dir) #print(path) files_img = foreach(path) # print(files_excel) for file_name in files_img: #excel_name=r"..\input\33-006(1).xlsx" #if 'jpg' not in file_name: #print(file_name) status=get_img_size(file_name) if status==1: #只有当图片尺寸验证通过,才需要进行后续的MD5校验 md5_value=calc_md5_value(file_name) #更新md5值到数据表 img_type = file_name.split('\\')[-2] img_name = file_name.split('\\')[-1] img_path = "/upload/prt/" + img_type + "/" + img_name # print(img_path) update_md5_value(img_path, md5_value) def get_img_size(file_name): try: im=Image.open(file_name) size=im.size #print(size) if "(1, 1)" in str(size): disabled_imgs(file_name) status=0 #两步,删除图片,然后到数据表将图片状态置为无效 else: #执行后续工作 status=1 except OSError as e: #print("打不开文件",e) #打不开的文件,就需要删除 disabled_imgs(file_name) status=0 return status def disabled_imgs(file_name): #移除本地路径下的这张图片 #os.remove(file_name) #取file_name后面两位的数据 img_type=file_name.split('\\')[-2] img_name=file_name.split('\\')[-1] img_path="/upload/prt/"+img_type+"/"+img_name #print(img_path) find_img_in_mysql(img_path) def find_img_in_mysql(img_path): db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") #sql="select * from prt_img where img_path='%s' " %img_path sql="update prt_img set is_use=0 where img_path='%s' " %img_path #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def calc_md5_value(file_name): image_file=open(file_name,'rb').read() #print(image_file) checkcode1_md5=hashlib.md5(image_file).hexdigest() checkcode1_sha1=hashlib.sha1(image_file).hexdigest() #print(checkcode1_md5) return checkcode1_md5 def update_md5_value(img_path,md5_value): db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") #sql="select * from prt_img where img_path='%s' " %img_path sql="update prt_img set md5='%s' where img_path='%s' " %(md5_value,img_path) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() class md5_filter(): def get_mysql_data(self): db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") # sql="select * from prt_img where img_path='%s' " %img_path sql = "select md5 from prt_img where download_status=1 and is_use=1 group by md5" # print(sql) try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_md5_imgs_data(self,md5_value): db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") # sql="select * from prt_img where img_path='%s' " %img_path sql = "select img_path from prt_img where download_status=1 and is_use=1 and md5='%s' " %md5_value #print(sql) try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('--------get_md5_imgs_data-------Error------Message--------:' + str(err)) cursor.close() db.close() def update_img_path(self,md5_value, default_img_path): db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") # sql="select * from prt_img where img_path='%s' " %img_path sql = "update prt_img set img_path='%s' where md5='%s' " % (default_img_path,md5_value) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------update_img_path--------Error------Message--------:' + str(err)) cursor.close() db.close() def mycopyfile(str,srcfile,dstfile): if not os.path.isfile(srcfile): print ("%s not exist!"%(srcfile)) else: fpath,fname=os.path.split(dstfile) #分离文件名和路径 if not os.path.exists(fpath): os.makedirs(fpath) #创建路径 shutil.copyfile(srcfile,dstfile) #复制文件 print ("copy %s -> %s"%( srcfile,dstfile)) if __name__=="__main__": get_excel_data() #上述,是完成了无效图片的筛选,以及md5的补录 #后面就是查重了 md5_info=md5_filter() md5_data=md5_info.get_mysql_data() for i in range (len(md5_data)): md5_value=md5_data[i][0] #将md5重新带入到mysql查询 path_data=md5_info.get_md5_imgs_data(md5_value) default_img_path=path_data[0][0] md5_info.update_img_path(md5_value, default_img_path) #将default_img_path图片复制到其他文件夹 original_img_dir= "D:/BI/TMALL" + str(default_img_path) filtered_img_dir = "D:/BI/TMALL_FILTERED" + str(default_img_path) md5_info.mycopyfile(original_img_dir,filtered_img_dir) for x in range(1,len(path_data)): img_path=path_data[x][0] img_dir="D:/BI/TMALL"+img_path print(img_dir) #os.remove(img_dir) <file_sep>/untitled/Selenium/dq123/dq123代理/DQ123-代理篇1.0.py import urllib.request import pymysql import random from bs4 import BeautifulSoup import public_proxy_func def find_info(html): soup = BeautifulSoup(html, 'lxml') ip_name = soup.find('h1') ip_address = soup.find('h2') print(str(ip_name.text) + ":<" + str(ip_address.text)+">") if __name__=="__main__": url="http://www.whatismyip.com.tw" html=public_proxy_func.main(url) print(html) #find_info(html) <file_sep>/JD后台/VC后台/新增商品.py import pymysql import time import random import logging import pyperclip from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.select import Select logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 #options.add_argument('--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome() else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #判断是否登陆成功 name = input("Go?") print(name) #获取mysql表中的待导入数据 data=self.get_upload_data() for i in range (len(data)): #哪里需要填写数据,再进行赋值 driver.get("https://vcp.jd.com/sub_item/item/initAddCategory") self.s(2,3) driver.find_elements_by_css_selector(".datagrid-cell.datagrid-cell-c1-name")[1].click() self.s(1, 1) driver.find_elements_by_css_selector(".datagrid-cell.datagrid-cell-c2-name")[1].click() self.s(1, 1) #选择3级类目 cate3_name=data[i][3] logger.info("cate3_name: "+cate3_name) cate3_data=driver.find_elements_by_css_selector(".datagrid-cell.datagrid-cell-c3-name") for cate3 in cate3_data: logger.info(cate3.text) if cate3_name == cate3.text: cate3.click() logger.info(cate3.text + " clicked") self.s(1, 2) #跳转页面 driver.find_element_by_id("cid3Submit").click() #self.s(3,4) ''' driver.find_element_by_css_selector(".combo-text.validatebox-text").clear() brand_name = data[i][4] driver.find_element_by_css_selector(".combo-text.validatebox-text").send_keys(brand_name) cnBrand=data[i][5] driver.find_element_by_id("zhBrand").send_keys(cnBrand) enBrand=data[i][6] driver.find_element_by_id("enBrand").send_keys(enBrand) ''' #driver.find_element_by_class_name("combo-arrow").click() #driver.find_element_by_xpath("//div[@class='combobox-item' and value='60487']").click() s1=input("Go") print(s1) spuModel=data[i][7] logger.info(spuModel) pyperclip.copy(spuModel) driver.find_element_by_id("modelShow").send_keys(spuModel) #self.s(1,1) #商品名称切换到自定义模式 driver.find_element_by_id("changeToCustmerMode").click() self.s(1,1) driver.find_element_by_id("custmerName").clear() custmerName=data[i][8] print(str(len(custmerName))) if len(custmerName)>66: custmerName=custmerName.replace("(FAR EAST CABLE)"," ") driver.find_element_by_id("custmerName").send_keys(custmerName) weight=data[i][12] driver.find_element_by_id("weight").send_keys(weight) length=data[i][13] driver.find_element_by_id("length").send_keys(length) width=data[i][14] driver.find_element_by_id("width").send_keys(width) height=data[i][15] driver.find_element_by_id("height").send_keys(height) marketPrice=data[i][16] driver.find_element_by_id("marketPrice").send_keys(marketPrice) memberPrice=data[i][17] driver.find_element_by_id("memberPrice").send_keys(memberPrice) purchasePrice=data[i][18] driver.find_element_by_id("purchasePrice").send_keys(purchasePrice) #特殊属性,普通商品 self.s(1,2) pack_Type = data[i][19] logger.info(pack_Type) #pt=driver.find_element_by_id('packType') #print(pt.text) Select(driver.find_element_by_id('packType')).select_by_value("1") #packType.select_by_value("1") #packType.select_by_visible_text(pack_Type) #packType=driver.find_element_by_id("packType") #packType.find_element_by_xpath("//option[@value='1']").click() #包装清单 pkgInfo = data[i][20] driver.find_element_by_id("pkgInfo").send_keys(pkgInfo) #销售单位 sku_Unit = data[i][22] logger.info(sku_Unit) skuUnit = Select(driver.find_element_by_id('skuUnit')) #packType.select_by_value("1") skuUnit.select_by_visible_text(sku_Unit) #skuUnit = driver.find_element_by_id('skuUnit').click() #driver.find_element_by_xpath("//select[@id='skuUnit']/option[@value='卷']").click() s1=input("Go") print(s1) #self.s(3, 5) #跳转下一页 driver.find_element_by_id('unAuditedSubmit').click() self.s(3, 5) wreadme=data[i][23] driver.find_element_by_id("wreadme").send_keys(wreadme) caizhi = data[i][24] logger.info(caizhi) #driver.find_element_by_css_selector(".combo-text.validatebox-text").clear() #driver.find_element_by_css_selector(".combo-text.validatebox-text").send_keys(caizhi) s1 = input("Go") print(s1) self.s(1,2) #跳转下一页,代码页 driver.find_element_by_id('categoryAttrSubmitNew').click() self.s(2, 3) driver.find_element_by_id('pc_intro').click() driver.find_element_by_xpath("//a[@href='#pc_html']").click() self.s(1, 2) pc_text=data[i][25] driver.find_element_by_id("introHtml").send_keys(pc_text) driver.find_element_by_id('mobile_intro').click() driver.find_element_by_xpath("//a[@href='#mobile_html']").click() self.s(2, 3) app_text=data[i][26] driver.find_element_by_id("introMobile").send_keys(app_text) #s2=input("Go") #print(s2) driver.find_element_by_id('createApply').click() self.s(2,3) driver.find_element_by_id('toApplyList').click() self.s(2, 4) table_id=data[i][0] self.update_status(table_id) def update_status(self,table_id): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update upload_prt_basic_info set status=1 where table_id='%s'" %table_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_upload_data(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select * from upload_prt_basic_info where status=0" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/untitled/Selenium/众业达/众业达2.0/zydmall-V2.2-weight补充.py #首先, 数据获取的方式,通过商品详情的url直接跳转到详情,获取其中的相关内容 #http://www.zydmall.com/detail/product_14321.html #数据源分为4块 #1. 类目,包括一级二级三级(四级)类目 #2. 商品信息,价格,名称等 #3. img_url,发现有些商品的图片N多,多疑如果单纯添加字段,很容易崩掉,所以要另起新表 #4. 属性名称/属性值,因为不同类型商品的属性count不同,所以名称和属性值分开存放 from selenium import webdriver import pymysql import time import urllib.request import os #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(product_id,img_url, img_name): if (len(img_url) != 0): fileName = img_name file_Path="C:\\ZYD\\Upload\\IMG"+"\\"+product_id try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_Path, fileName)) except: print("这图我没法下载") #获取类目名称 def get_category(product_id,prt_name): cate_list=driver.find_elements_by_xpath("//div[@class='page_posit']/a") cate_1=cate_list[1].get_attribute("href") cate_1_id = cate_1[cate_1.index("list_")+5:cate_1.index(".html")] cate_1_name=cate_list[1].text cate_2 = cate_list[2].get_attribute("href") cate_2_id = cate_2[cate_2.index("list_")+5:cate_2.index(".html")] cate_2_name=cate_list[2].text cate_3 = cate_list[3].get_attribute("href") cate_3_id = cate_3[cate_3.index("list_")+5:cate_3.index(".html")] cate_3_name = cate_list[3].text #print("#"+str(len(cate_list)-1)+"层类目:"+cate_1_id+cate_1_name+"//"+cate_2_id+cate_2_name+"//"+cate_3_id+cate_3_name) insert_category(product_id,prt_name,cate_1_id,cate_1_name,cate_2_id,cate_2_name,cate_3_id,cate_3_name) def insert_category(product_id,prt_name,cate_1_id,cate_1_name,cate_2_id,cate_2_name,cate_3_id,cate_3_name): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_category_info " \ " (prt_id,prt_name,category_1_id,category_1_name,category_2_id,category_2_name,category_3_id,category_3_name)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s')" \ % (product_id,prt_name,cate_1_id,cate_1_name,cate_2_id,cate_2_name,cate_3_id,cate_3_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() #获取商品主要信息,如价格,品牌等 def get_prt_info(product_id, prt_name): #prt_model=driver.find_element_by_xpath("//div[@class='pro_desc clearfix mt20']/p[@class='wp100'][1]/span").text #prt_order_id=driver.find_element_by_xpath("//div[@class='pro_desc clearfix mt20']/p[@class='wp100'][2]/span").text #print("产品型号:"+prt_model+",订货号:"+prt_order_id) #discount_price=driver.find_element_by_css_selector(".f30.ceb6161.fw.t-count").text #print("折扣价"+discount_price) #face_price = driver.find_element_by_css_selector(".f30.ceb6161.fw.t-count").text #print("面价" + face_price) #brand_id_t=driver.find_element_by_xpath("//p[@class='row2']/span[@class='mr10']/a").get_attribute("href") #brand_id = brand_id_t[brand_id_t.index("list_") + 5:brand_id_t.index(".html")] #print("品牌ID:" + brand_id) #brand_name=driver.find_element_by_xpath("//p[@class='row2']/span[@class='mr10']/a").text #print("品牌:" + brand_name) #series=driver.find_element_by_xpath("//div[@class='pro_price clearfix']/p[4]/span").text #print("系列:" + series) #insert_prt_info(product_id, prt_name, prt_model, prt_order_id, discount_price,face_price,brand_id,brand_name,series) #time.sleep(0.2) prt_main_id=get_main_id(product_id) prt_main=str(prt_main_id).replace("(('","").replace("',),)","") #如果取出来的主要商品ID为空,证明没有存,所以insert if prt_main=="" or prt_main==product_id or prt_main=="()": #商品关联数据 time.sleep(10) prt_list=driver.find_elements_by_xpath("//tbody[@id='product_list']/tr[@class='pro_list']") print("共有"+str(len(prt_list))+"条相关产品") for i in range(len(prt_list)): prt_linked=prt_list[i].find_element_by_xpath("./td[1]/a").get_attribute("href") prt_linked_id=prt_linked[prt_linked.index("product_")+8:prt_linked.index(".html")] prt_linked_order_id=prt_list[i].find_element_by_xpath("./td[1]/a").text #print("关联商品ID:"+prt_linked_id+",关联商品订货号:"+prt_linked_order_id) prt_stock = prt_list[i].find_element_by_xpath("./td[5]").text #print("库存:"+prt_stock) prt_weight = prt_list[i].find_element_by_xpath("./td[8]").text #print("重量:"+prt_weight) prt_unit_name = prt_list[i].find_element_by_xpath("./td[9]").text #print("单位:"+prt_unit_name) insert_prt_linked_data(product_id,prt_linked_id,prt_linked_order_id,prt_stock,prt_weight,prt_unit_name) else: print("因关联商品" + str(prt_main) + ",已存在关联表数据") def insert_prt_info(product_id, prt_name, prt_model, prt_order_id, discount_price,face_price,brand_id,brand_name,series): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_prt_info " \ " (prt_id,prt_name,prt_model,prt_order_id,discount_price,face_price,brand_id,brand_name,series)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (product_id, prt_name, prt_model, prt_order_id, discount_price,face_price,brand_id,brand_name,series) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def insert_prt_linked_data(product_id,prt_linked_id,prt_linked_order_id,prt_stock,prt_weight,prt_unit_name): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_prt_linked_info " \ " (prt_main_id,prt_linked_id,prt_linked_order_id,stock,weight,unit_name)" \ " values('%s','%s','%s','%s','%s','%s')" \ % (product_id,prt_linked_id,prt_linked_order_id,prt_stock,prt_weight,prt_unit_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() #查询图片是否已经由关联商品爬取 def check_img_get_status(product_id): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select prt_main_id from zyd_prt_linked_info where prt_linked_id='%s' limit 1" %(product_id) try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() #img_url获取 def get_img_info(product_id, prt_name): #在获取img之前,需要去数据商品关联表查询,是否有关联 prt_main_id=get_main_id(product_id) prt_main=str(prt_main_id).replace("(('","").replace("',),)","") if prt_main=="" or prt_main==product_id or prt_main=="()": #="",说明不存在关联的商品,所以不需要考虑 #如果相同,说明是主体商品 img_path=driver.find_elements_by_xpath("//ul[@id='thumblist']/li/a/img") print("共"+str(len(img_path))+"张图片") for i in range (len(img_path)): img_url_big=img_path[i].get_attribute("big") img_num=str(i+1) #print("序号:"+img_num) img_name=img_url_big[img_url_big.rindex("/")+1:200]####################################################### #print("图片名称(GUID):"+img_name) original_url=img_url_big #print("众业达原始url:"+original_url) path="暂未定" #存储图片 type_1="1" insert_img_info(product_id, prt_name,img_num,img_name,path,original_url,type_1) getAndSaveImg(product_id,original_url,img_name) #详情页图片 detail_list = driver.find_element_by_xpath("//div[@class='pro_detail_info']/div[@class='pro_detail_txt mt30']") detail_img = detail_list.find_elements_by_tag_name("img") #print(len(detail_img)) for j in range(len(detail_img)): img_detail_url = detail_img[j].get_attribute("src") type_2 = "2" img_num_2 = str(j + 1) path_2 = "暂未定" try: img_detail_name=img_detail_url[img_detail_url.rindex("/")+1:img_detail_url.rindex(".jpg")+4] #print("详情页图片名称(GUID):"+img_detail_name) #print(img_detail_url) getAndSaveImg(product_id,img_detail_url,img_detail_name) except: img_detail_name ="error" insert_img_info(product_id, prt_name,img_num_2,img_detail_name,path_2,img_detail_url,type_2) else: print("因关联商品" + str(prt_main) + ",已存在图片") def insert_img_info(product_id, prt_name,img_num,img_name,img_path,original_url,type): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_img_info " \ " (prt_id,prt_name,img_num,img_name,img_path,original_url,type)" \ " values('%s','%s','%s','%s','%s','%s','%s')" \ % (product_id, prt_name,img_num,img_name,img_path,original_url,type) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() #获取关联商品的主ID def get_main_id(product_id): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select prt_main_id from zyd_prt_linked_info where prt_linked_id='%s' limit 1" %(product_id) try: execute=cursor.execute(sql) prt_main_id=cursor.fetchmany(execute) return prt_main_id except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() #获取属性名称,属性值 def get_attributes(product_id, prt_name): #获取属性名称 prt_main_id=get_main_id(product_id) prt_main=str(prt_main_id).replace("(('","").replace("',),)","") #如果取出来的主要商品ID为空,证明没有存,所以insert if prt_main=="" or prt_main==product_id or prt_main=="()": attr_name_list=driver.find_elements_by_xpath("//div[@class='pro_desc clearfix']/p/b") print("共"+str(len(attr_name_list))+"条属性") for i in range (len(attr_name_list)): attr_name_t=attr_name_list[i].text attr_name=attr_name_t.replace(":","") #print("属性名称:"+attr_name) attr_num = str(i + 1) insert_attributes(product_id,attr_num,attr_name) else: print("因关联商品"+str(prt_main)+",已存在属性名称") def get_attributes_value(product_id, prt_name): #获取属性值 prt_main_id=get_main_id(product_id) prt_main=str(prt_main_id).replace("(('","").replace("',),)","") #这是作为主从关系的点 attr_value_list = driver.find_elements_by_xpath("//div[@class='pro_desc clearfix']/p/span") #print("共"+str(len(attr_value_list))+"条属性值") for i in range (len(attr_value_list)): attr_num=str(i+1) attr_value_t = attr_value_list[i].text attr_value = attr_value_t.replace(":", "") #print("属性值:"+attr_value) if prt_main == "" or prt_main=="()": insert_attributes_value(product_id,prt_name,product_id,attr_num,attr_value) else: insert_attributes_value(product_id, prt_name, prt_main, attr_num, attr_value) def insert_attributes(product_id,attr_num,attr_name): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_attributes " \ " (prt_main_id,attribute_num,attribute_name)" \ " values('%s','%s','%s')" \ % (product_id,attr_num,attr_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def insert_attributes_value(product_id,prt_name,prt_id,attr_num,attr_value): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_attributes_value " \ " (prt_id,prt_name,prt_main_id,attribute_num,attribute_value)" \ " values('%s','%s','%s','%s','%s')" \ % (product_id,prt_name,prt_id,attr_num,attr_value) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() #获取run_log表的状态为0的第一条数据 def get_url_status(): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select product_id from run_log where status=0 and table_id>120000 and table_id<=157000 order by table_id limit 1 " try: execute=cursor.execute(sql) product_id=cursor.fetchmany(execute) return product_id except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(product_id): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update run_log set status=1 where product_id='%s' " \ % (product_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def clean_prt_info(product_id): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql1="delete from zyd_attributes_info where prt_id='%s';" % (product_id) sql2="delete from zyd_attributes where prt_main_id='%s';" % (product_id) sql3="delete from zyd_attributes_value where prt_id='%s';" % (product_id) sql4="delete from zyd_category_info where prt_id='%s';" % (product_id) sql5="delete from zyd_img_info where prt_id='%s';" % (product_id) sql6="delete from zyd_prt_info where prt_id='%s';" % (product_id) sql7="delete from zyd_prt_linked_info where prt_main_id='%s';" % (product_id) try: cursor.execute(sql1) cursor.execute(sql2) cursor.execute(sql3) cursor.execute(sql4) cursor.execute(sql5) cursor.execute(sql6) cursor.execute(sql7) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() if __name__=="__main__": #2.1版本新增加product_id的区间判断 #定义一个范围 print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") #product_id_t=get_url_status() driver = webdriver.Chrome() #product_id=str(product_id_t).replace("(('","").replace("',),)","") product_list=[89432] for i in range (len(product_list)): product_id=str(product_list[i]) print("当前起步:"+product_id) #清除一下当前条的数据 clean_prt_info(product_id) #driver.set_page_load_timeout(2) driver.get("http://www.zydmall.com/detail/product_" + str(product_id) + ".html") print(">>" + str(product_id) + "页面加载完成<<") time.sleep(0.2) try: prt_name = driver.find_element_by_css_selector(".c333.fw.f20.h20").text print("商品名称:" + prt_name) #get_category(product_id, prt_name) # 获取商品主要信息 get_prt_info(product_id, prt_name) # 获取属性属性值 #get_attributes(product_id, prt_name) #get_attributes_value(product_id, prt_name) # 获取图片信息 #get_img_info(product_id, prt_name) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") #update_status_to_run_log(product_id) time.sleep(0.1) except: print("商品不存在或者已经下架") print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") #update_status_to_run_log(product_id) # time.sleep(20) # 获取类目 <file_sep>/untitled/Selenium/米思米/main.py import time import pyautogui import pymysql import xlrd import xlsxwriter from untitled.Selenium import webdriver def print_xls(): data=xlrd.open_workbook(r"D:\BI\米思米\test.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 PRT_NAME=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss PRT_NAME.append(ss) return PRT_NAME def login(): print('准备页面跳转--登录') driver.get('https://cn.misumi-ec.com/mydesk2/s/login') time.sleep(3) #1. 点击LOGO driver.find_element_by_class_name('header__logo').click() time.sleep(3) #2. 切换到Login页面 handles = driver.window_handles driver.switch_to.window(handles[0]) time.sleep(1) #3. 登录 driver.find_element_by_class_name('id').send_keys('<PASSWORD>') driver.find_element_by_class_name('pass').send_keys('<PASSWORD>') driver.find_element_by_css_selector('.loginBtn.VN_opacity').click() time.sleep(10) #4. 刷新页面 #driver.get('http://cn.misumi-ec.com/vona2') time.sleep(5) driver.get('http://cn.misumi-ec.com') #2. #source=driver.page_source #print(source) def Baojia(): driver.get("http://cn.misumi-ec.com") time.sleep(5) print('点击首页的报价按钮') driver.find_element_by_xpath("//div[@class='directInfo__main']/ul/li/a[@class='VN_opacity']").click() time.sleep(10) print('等待中---准备点击Excel获取') try: driver.find_element_by_xpath("//div[@class='tableGreen marginT15']/div/span[@id='copyAndPasteCommand']").click() except: time.sleep(5) driver.find_element_by_xpath("//div[@class='tableGreen marginT15']/div/span[@id='copyAndPasteCommand']").click() time.sleep(3) #嫁接 click_title() def click_title(): handles = driver.window_handles print(handles) driver.switch_to.window(handles[2]) #输入text内容,从Excel中获取list进行批量插入,一次500条 #test_text="DZ47-60 1P C16,DZ47-60 1P C16,正泰(CHINT),1" text = "" for i in range (len(PRT_NAME)): print(PRT_NAME[i]) text=text+"\n"+str(PRT_NAME[i]).replace("['",'').replace("']",'').replace("('","").replace("')","").replace(" '","").replace("'","").replace(" 1)","1") print(text) driver.find_element_by_xpath("//div[@class='tableGrey marginT10']/table/tbody/tr/td/textarea[@name='uploadText']").send_keys(text) driver.find_element_by_id('DelimiterCOMMA').click() #下一步 driver.find_element_by_id('nextCommand').click() time.sleep(6) #由于下拉选择框的点击异常暂未解决,采药autogui方式试用 table_a=driver.find_element_by_css_selector('.tableGrey.marginT15.setItem_scroll') print(table_a.text) t1=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='columnList_0.uploadItemName']").click() time.sleep(5) pyautogui.click(171,290) #print(t1.text) print('第二个下拉选择框') time.sleep(0.5) t2=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='<EMAIL>']").click() time.sleep(0.5) pyautogui.click(343, 313) #print(t2.text) time.sleep(0.5) t3=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='<EMAIL>']").click() time.sleep(0.5) pyautogui.click(500, 360) time.sleep(0.5) t4=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='<EMAIL>3.<EMAIL>']").click() time.sleep(0.5) pyautogui.click(650, 320) time.sleep(3) driver.find_element_by_id('nextCommand').click() time.sleep(4) driver.find_element_by_id('nextCommand').click() time.sleep(4) try: driver.find_element_by_id('nextCommand').click() time.sleep(4) except: handles = driver.window_handles driver.switch_to.window(handles[0]) #以上属于搞事,准备返回主页面流程 handles = driver.window_handles print(handles) driver.switch_to.window(handles[0]) time.sleep(10) print('#进入报价结果页面') driver.find_element_by_xpath("//div[@id='contentsArea']/form/div[@class='floatR']/a[@class='btnNext']").click() time.sleep(200) handles = driver.window_handles driver.switch_to.window(handles[0]) time.sleep(50) table=driver.find_element_by_xpath("//div[@id='table_Product']/table[@id='marginTableTB']") for i in range (2,len(PRT_NAME)+2): price=table.find_element_by_xpath("//tbody/tr["+str(i)+"]/td[4]").text name = table.find_element_by_xpath("//tbody/tr[" + str(i) + "]/td[2]").text price=price.split("\n") name = name.split("\n") try: price_1=price[0] except: price_1="NULL" try: price_2=price[1] except: price_2="NULL" try: name_1=name[0] except: name_1="NULL" try: name_2=name[1] except: name_2="NULL" try: cate=name[2] except: cate="NULL" try: brand=name[3] except: brand="NULL" print(str(i-1)+'/'+str(len(PRT_NAME))) mysql_insert(name_1,name_2,cate,brand,price_1,price_2) #print(price_1) #print(price_2) def mysql_insert(name_1,name_2,cate,brand,price_1,price_2): db = pymysql.connect("192.168.180.147","root","123456","test01" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql="insert into misumi_price " \ " (name_1,name_2,cate,brand,price_1,price_2)" \ " values('%s','%s','%s','%s','%s','%s')" \ % (name_1,name_2,cate,brand,price_1,price_2) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() #print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:'+err) # 关闭数据库连接 db.close() def save_excel(fin_result1, fin_result2): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'D:\BI\米思米\test2.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result1)): tmp.write(i, 1, fin_result1[i]) tmp.write(i, 2, fin_result2[i]) def get_prt_name(): db = pymysql.connect("192.168.180.147","root","123456","test01" ) cursor = db.cursor() sql="SELECT PRT_NAME,PRT_NAME2,BRAND,COUNT from misumi_1 WHERE STATUS=1 order by ID limit 200" count=cursor.execute(sql) name_list = [] # 获取所有结果 results = cursor.fetchall() result = list(results) for r in result: name_list.append(r) db.close() return name_list def update_status(): db = pymysql.connect("192.168.180.147","root","123456","test01" ) cursor = db.cursor() sql="update misumi_1 set STATUS=0 WHERE STATUS=1 order by ID limit 200" cursor.execute(sql) db.close() if __name__=="__main__": for i in range(40): PRT_NAME=get_prt_name() print(PRT_NAME) update_status() #修改PRT_NAME的数据来源 ,从excel改为从数据表 #1. select 前200条数据 #2. 将200条数据拼接成对应格式的字符串list #3. update 该200条数据的状态,表示已记录 #4. 重新循环 driver=webdriver.Firefox() login() #driver.find_element_by_id('keyword_input').send_keys('<KEY>') Baojia() #save_excel(price_1,price_2) <file_sep>/MMBAO/对SKU进行属性的获取补充/通过类目-属性名称-属性值-查找对应的ID.py import pymysql import cx_Oracle def get_data_from_mysql(): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,sku_id,attr_name,attr_value,category_name_lev3 from find_attribute_id " #where attr_name!='系列' and attr_val_id='' try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('-------get_data_from_mysql--------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_attr_id(category_name_lev3,attr_name): #db = cx_Oracle.connect('mmbao2_bi/<EMAIL>:21252/mmbao2b2c') db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.17.32:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT attr_id FROM mmbao2.v_prt_catgory_attr "\ "WHERE lev3_cat_name='%s' AND attr_name='%s' " %(category_name_lev3,attr_name) # and create_date>to_date('%s','yy/MM/dd') # 因为还得分为新增和更新 # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def find_attr_val_id(category_name_lev3, attr_name,attr_value): #db = cx_Oracle.connect('mmbao2_bi/<EMAIL>:21252/mmbao2b2c') db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.17.32:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "select ATTR_VAL_ID from MMBAO2.V_PRT_CATGORY_ATTR_VAL "\ "WHERE lev3_cat_name='%s' AND attr_name='%s' AND ATTR_VAL_VALUE='%s' " %(category_name_lev3,attr_name,attr_value) # and create_date>to_date('%s','yy/MM/dd') # 因为还得分为新增和更新 # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def update_id_data_to_mysql(table_id,attr_id,attr_val_id): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update find_attribute_id set attr_id='%s',attr_val_id='%s' where table_id='%s' " %(attr_id,attr_val_id,table_id) try: execute = cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('-------get_data_from_mysql--------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #从mysql获取每一条类目-属性名称-属性值的匹配关系 attributes_data=get_data_from_mysql() for i in range (len(attributes_data)): table_id=attributes_data[i][0] sku_id=attributes_data[i][1] attr_name=attributes_data[i][2] attr_value=attributes_data[i][3] category_name_lev3=attributes_data[i][4] print(table_id,sku_id,attr_name,attr_value,category_name_lev3) #将每一条数据代入到oracle进行查询 try: attr_id_tmp=find_attr_id(category_name_lev3,attr_name) attr_id=attr_id_tmp[0][0] print("attr_id",attr_id) except IndexError as e: print(e, "pass") attr_id="" try: attr_val_id_tmp=attr_val_id = find_attr_val_id(category_name_lev3, attr_name,attr_value) attr_val_id=attr_val_id_tmp[0][0] print("attr_val_id_tmp",attr_val_id) except IndexError as e: print(e, "pass") attr_val_id="" #将找到的ID回填到mysql数据表中 update_id_data_to_mysql(table_id,attr_id,attr_val_id) <file_sep>/TMALL/数据分析架构模式化/针对legrand进行流交互尝试/针对403异常另类处理.py from selenium import webdriver from bs4 import BeautifulSoup import pymysql import random import time def s(a, b): t = random.randint(a, b) time.sleep(t) class tmall_data_procurement(): def get_lists(self): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select table_id,prt_url from prt_lists where status=1 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('------get_lists---------Error------Message--------:' + str(err)) db.close() cursor.close() def find_price_sales(self,content): soup=BeautifulSoup(content,'html.parser') sale_count=soup.find('span',attrs={'class':'tm-count'}).text return sale_count def update_sale_count(self,sale_count,prt_id): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update spu_info set sell_count='%s' where prt_id='%s' " %(sale_count,prt_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": url="https://list.tmall.com/search_product.htm?q=%C2%DE%B8%F1%C0%CA&type=p&spm=a220m.1000858.a2227oh.d100&from=.list.pc_1_searchbutton" #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() temp = input("tmp") driver.get(url) data_procurement=tmall_data_procurement() url_data = data_procurement.get_lists() print(str(len(url_data))) for i in range(len(url_data)): table_id = url_data[i][0] url = url_data[i][1] # prt_id=url.split('id=')[-1].split("&")[0] prt_id = table_id print(url, prt_id) driver.get(url) s(3,7) content=driver.page_source sale_count=data_procurement.find_price_sales(content) data_procurement.update_sale_count(sale_count,prt_id) #获取sku的价格 li_lists=driver.find_element_by_xpath("//dd/ul[@class='tm-clear J_TSaleProp tb-img ']").find_elements_by_tag_name('li') for x in range(len(li_lists)): li_lists[x].find_element_by_xpath("/a").click() market_price=driver.find_element_by_xpath("//dl[@id='J_PromoPrice']/dd/div/span").text face_price=driver.find_element_by_xpath("//dl[@id='J_StrPriceModBox']/dd/span").text print(face_price,market_price) s(3,7) <file_sep>/ZYDMALL/zydmall_德力西/数据分析-匹配已有和新增数据.py #对已有的2062条数据,逐条进行数据的匹配 #匹配结果可能性# #1. 不存在,直接标示状态为2, #2. 已存在,直接标示状态为1,将结果与link_id,一同记录到新表里面 import time import pymysql def get_data(): db = pymysql.connect("localhost","root","123456","mmbao_delixi",charset="utf8" ) cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select sku_id,prt_id,sku_title,po_number,series,prt_title,attr_val as prt_type from mmbao_delixi.sku_data" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def compare_data(sku_id,prt_id,sku_title,po_number,series,prt_title,prt_type): db = pymysql.connect("localhost","root","123456","zydmall_delixi",charset="utf8" ) cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,sku_id,sku_type,po_number,b.title,b.cnt from prt_sku a "\ "left join goods_lists_info b "\ "on a.prt_id=b.good_id "\ "where b.is_full=0 "\ "and (po_number='%s' or sku_type='%s')" %(po_number,prt_type) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_linked_data(mmb_sku_id,prt_id,sku_id,sku_type,po_number,title,cnt): db = pymysql.connect("localhost","root","123456","zydmall_delixi",charset="utf8" ) cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into linked_delixi_data(mmb_sku_id,prt_id,sku_id,sku_type,po_number,title,cnt) values('%s','%s','%s','%s','%s','%s','%s')" %(mmb_sku_id,prt_id,sku_id,sku_type,po_number,title,cnt) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": data=get_data() for i in range (len(data)): mmb_sku_id=data[i][0] mmb_prt_id=data[i][1] mmb_sku_title=data[i][2] mmb_po_number=data[i][3] mmb_series=data[i][4] mmb_prt_title=data[i][5] mmb_prt_type=data[i][6] print(mmb_sku_id,mmb_prt_id,mmb_sku_title,mmb_po_number,mmb_series,mmb_prt_title,mmb_prt_type) #将数据代入到数据表进行匹配查询 data2=compare_data(mmb_sku_id,mmb_prt_id,mmb_sku_title,mmb_po_number,mmb_series,mmb_prt_title,mmb_prt_type) print(data2) for j in range (len(data2)): prt_id=data2[j][0] sku_id=data2[j][1] sku_type=data2[j][2] po_number=data2[j][3] title=data2[j][4] cnt=data2[j][5] insert_linked_data(mmb_sku_id,prt_id,sku_id,sku_type,po_number,title,cnt) #time.sleep(10)<file_sep>/untitled/Selenium/天眼查test1.py #coding=utf-8 import random import time import bs4 import xlrd import xlsxwriter from untitled.Selenium import webdriver #随机等待时间 def s(): rand=random.randint(3,5) time.sleep(rand) #将company_name改为list,循环查询 def print_xls(): data=xlrd.open_workbook(r"C:\Users\Administrator\Desktop\test_info.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 Company_Name=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss Company_Name.append(ss) return Company_Name # 函数:获取公司链接 # input :页面资源 # output : 对应的公司详情url链接 def Get_Company_Url(web_source): pages = bs4.BeautifulSoup(web_source, "html.parser") try: company_info_url=pages.find('div',attrs={'class':'col-xs-10 search_repadding2 f18'}).find('a',attrs={'class':'query_name search-new-color'}).get('href') #print(company_info_url) return company_info_url except Exception as err: print('不存在相关公司信息') company.append('未找到') leader.append('未找到') address.append('未找到') phone.append('未找到') return 'None' def Get_Company_Main(url): driver3 = webdriver.Firefox() driver3.get(url) s() web_source=driver3.page_source #print(web_source) pages = bs4.BeautifulSoup(web_source, "html.parser") #筛选法定代表人 company_name=pages.find('div',attrs={'class':'company_info_text'}).find('div',attrs={'class':'in-block ml10 f18 mb5 ng-binding'}).text print(company_name) company.append(company_name) company_leader=pages.find('div',attrs={'class':'baseinfo-module-item'}).find('div',attrs={'class':'baseinfo-module-content-value-fr baseinfo-module-content-value'}) tmp_leader=company_leader.find('a').text print(tmp_leader ) if tmp_leader!="他的所有公司": company_leader=company_leader.find('a').text ##筛选地址 #company_info=pages.find('div',attrs={'class':'company_info_text'}).findAll('span',attrs={'class':'ng-binding'}) #for company_address in company_info: #print (company_leader) #筛选财报链接 leader.append(company_leader) else: leader.append('未公开') try: company_report_url = pages.find('div', attrs={'class': 'report_item_2017 float-left mr10 ng-scope'}).find('a', attrs={'class': 'detail_btn ml17 mt20 pt2 text-center f12 point'}).get('href') print(company_report_url) company_report_url='http://www.tianyancha.com'+company_report_url time.sleep(1) Get_Company_Phone(company_report_url) except Exception as err: phone.append('未公开') company_info=pages.find('div',attrs={'class':'company_info_text'}).findAll('span',attrs={'class':'ng-binding'}) company_address=company_info[2].text print (company_address) address.append(company_address) print(leader) print(phone) print(address) driver3.quit() #print(company_report_url) def Get_Company_Phone(url): driver2 = webdriver.Firefox() driver2.get(url) s() web_source = driver2.page_source pages = bs4.BeautifulSoup(web_source, "html.parser") company_report=pages.find('table').findAll('div',attrs={'class':'ng-binding'}) company_phone=company_report[3].text company_address = company_report[9].text phone.append(company_phone) address.append(company_address) print (company_phone) print(company_address) driver2.quit() return company_phone, def save_excel(fin_result1,fin_result2,fin_result3,fin_result4): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\test1.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result1)): tmp.write(i, 0, fin_result1[i]) tmp.write(i, 1, fin_result2[i]) tmp.write(i, 2, fin_result3[i]) tmp.write(i, 3, fin_result4[i]) #main函数 if __name__ == '__main__': Company_Info=print_xls() print(Company_Info) #定义多个list,存储地址,代表人,电话 company=[] address=[] leader=[] phone=[] Company_Num=len(Company_Info) for i in range (0,Company_Num): Company_Name=str(Company_Info[i]).replace("['",'').replace("']",'') print(str(i+1)+'/'+str(Company_Num)+' '+Company_Name) driver1 = webdriver.Firefox() driver1.get("http://www.baidu.com/link?url=RcRWaVxfM-TI5sbU0iv_DfuLzwif9BArWobmWkWBtD-lFrB7K5JhFxG0YSsMHuFX") time.sleep(2) driver1.get("http://www.tianyancha.com/") s() source = driver1.page_source #print(source) company_info_url=Get_Company_Url(source) if company_info_url!='None': print(company_info_url) Get_Company_Main(company_info_url) driver1.quit() for i in range (0,len(company)): print(company[i]+' '+address[i]+' '+leader[i]+' '+phone[i]) save_excel(company,address,leader,phone) <file_sep>/untitled/Selenium/众业达/众业达3.0/通过good_id获取sku的面价更新.py import pymysql from selenium import webdriver import random import time def s(a,b): seconds=random.randint(a,b) time.sleep(seconds) def get_good_id(): db = pymysql.connect("localhost", "root", "123456", "zydmall", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select good_id,good_url from goods_lists_info where status=0 " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_data_to_mysql(good_id,prt_name,po_number,prt_type,face_price): db = pymysql.connect("localhost", "root", "123456", "zydmall", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into face_price_update(good_id,prt_name,po_number,prt_type,face_price) values('%s','%s','%s','%s','%s')" %(good_id,prt_name,po_number,prt_type,face_price) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_status(good_id,status): db = pymysql.connect("localhost", "root", "123456", "zydmall", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update goods_lists_info set status='%d' where good_id='%s'" %(status,good_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": # 载入url,获取详情数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() goods=get_good_id() for i in range (len(goods)): good_id=goods[i][0] url=goods[i][1] print("-------------",good_id,"-------------") driver.get(url) s(5,8) try: prt_name=driver.find_element_by_xpath("//div[@class='page_posit']/span[@class='c333']").text print(prt_name) lists_tr=driver.find_elements_by_xpath("//tbody[@id='product_list']/tr[@class='pro_list']") print("该SPU共有%s条SKU"%str(len(lists_tr))) for i in range (len(lists_tr)): prt_info=lists_tr[i].find_elements_by_xpath("./td") po_number=prt_info[0].text prt_type=prt_info[1].text face_price=prt_info[2].text print(po_number,prt_type,face_price) insert_data_to_mysql(good_id,prt_name,po_number,prt_type,face_price) status=1 except: status=2 update_status(good_id,status)<file_sep>/SERVER/jd_vc 日志匹配/日常更新商品价格属性.py #1. 先将我的商品中的列表,更新到制定文件夹下的excel中 <file_sep>/JD后台/生成商品新增数据模板/查询价格及其他生成导入模板.py import pymysql import xlrd import time import os,shutil import logging import datetime from xlrd import xldate_as_tuple logging.basicConfig(level=logging.DEBUG,#控制台打印的日志级别 #filename='./output/import.log', filemode='a',##模式,有w和a,w就是写模式,每次都会重新写日志,覆盖之前的日志 #a是追加模式,默认如果不写的话,就是追加模式 format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'#日志格式 ) class excel_operation(): def foreach(self,rootDir): files_excel=[] for root,dirs,files in os.walk(rootDir): for file in files: file_name=os.path.join(root,file) if 'xls' in file_name: files_excel.append(file_name) for dir in dirs: self.foreach(dir) return files_excel def get_excel_data(self): excel_dir = "./input" path=os.path.abspath(excel_dir) #print(path) files_excel=self.foreach(path) #print(files_excel) for file_name in files_excel: logging.info(file_name) excel_name=file_name.split('\\')[-1] logging.info(excel_name) data = xlrd.open_workbook(file_name) # 打开excel # print("当前excel共有%s个SHEET" % str(len(data.sheets()))) sheetName = data.sheet_names()[0] # print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[0] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] logging.info(sheetName+"@"+str(nrows)) #开始获取excel内的详细信息 #获取excel_name的有效信息 shop_type=excel_name.split("-")[1] update_time=excel_name.split("-")[-1].split(".")[0] logging.info("shop_type:"+shop_type) logging.info("update_time:"+update_time) for i in range (1,int(nrows)): row_info=table.row_values(i) #print(row_info) 机构=row_info[0] 商品编码=str(row_info[1]).replace(".0","") 基本采购价=round(row_info[2],4) 币种=row_info[3] 申请理由 = row_info[4] #数据插入到数据表 self.insert_import_info(机构,商品编码,基本采购价,币种,申请理由,update_time,shop_type) #将获取完成的excel,转移到history文件夹 target_path=file_name.replace("input","history") shutil.move(file_name, target_path) logging.info("move %s -> %s" % (file_name, target_path)) def insert_import_info(self,机构,商品编码,基本采购价,币种,申请理由,update_time,shop_type): db = pymysql.connect("localhost", "root", "123456", "jd_server") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into import_price_data (机构,商品编码,基本采购价,币种,申请理由,上传时间,店铺类型) values('%s','%s','%s','%s','%s','%s','%s')"\ %(机构,商品编码,基本采购价,币种,申请理由,update_time,shop_type) logging.info(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": excel_operation=excel_operation() excel_operation.get_excel_data() <file_sep>/日常工作/检查过期的公司.py import pymysql import time def get_company(): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") #sql = "select table_id,company_name,expiration_date,status from find_expired_company" sql = "select company_name from find_expired_company group by company_name" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_expiration_info(company_name): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select expiration_date from find_expired_company where company_name='%s'" %company_name try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_expiration_info(company_name,expiration_date): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update find_expired_company set status=1 where company_name='%s' and expiration_date='%s'" %(company_name,expiration_date) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": company_data=get_company() for i in range (len(company_data)): company_name=company_data[i][0] print(company_name) expiration_data=get_expiration_info(company_name) useful_expiration_date=expiration_data[0][0] #print(time.strptime(str(useful_expiration_date), "%Y-%m-%d %H:%M:%S")) for i in range (len(expiration_data)): current_date=expiration_data[i][0] if time.strptime(str(useful_expiration_date),"%Y-%m-%d %H:%M:%S")<time.strptime(str(current_date),"%Y-%m-%d %H:%M:%S"): useful_expiration_date = current_date print("max", useful_expiration_date) update_expiration_info(company_name, useful_expiration_date) <file_sep>/untitled/Requests/collage.py import requests from bs4 import BeautifulSoup import bs4 # 获取网页信息的通用框架 def getHtmlText(url): try: r = requests.get(url, timeout = 30) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return '爬取失败' # 填充列表 def fillUnivList(ulist, html): soup = BeautifulSoup(html, 'lxml') for tr in soup.find('tbody').children: # 检查网页代码可以发现数据都储存在tboyd标签中,这里需要对tbody的儿子节点进行遍历 if isinstance(tr, bs4.element.Tag): # 检测标签类型,如果不是bs4库支持的Tag类型,就过滤掉,这里需要先导入bs4库 tds = tr('td') # 解析出tr标签中的td标签后,将其储存在列表tds中 ulist.append([tds[0].string, tds[1].string, tds[3].string]) # 我们需要的是排名、学校名称和总分 # 格式化后,输出列表数据 def printUnivList(ulist, num): tplt = '{:<10}\t{:<10}\t{:<10}' # 定义输出模板为变量tplt,\t为横向制表符,<为左对齐,10为每列的宽度 print(tplt.format('排名','学校名称','总分')) # format()方法做格式化输出 for i in range(num): u = ulist[i] print(tplt.format(u[0],u[1],u[2])) def main(): uinfo = [] url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2017.html' html = getHtmlText(url) fillUnivList(uinfo, html) printUnivList(uinfo, 10) # 选取前10所学校信息 main()<file_sep>/python监控Windows进程/main_scripts.py import os import win32api import win32con import win32gui from ctypes import * import time def mouse_move(x, y): windll.user32.SetCursorPos(x, y) def mouse_click(x=None, y=None): if not x is None and not y is None: mouse_move(x, y) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) def write_log(msg): with open(title, "a") as f: # 格式化字符串还能这么用! current_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) f.write(current_date) f.write(" ") f.write(msg) f.write('\n') def mouse_dclick(x=None, y=None): if not x is None and not y is None: mouse_move(x, y) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) if __name__=="__main__": #检查poe的进程是否存在 ##PathOfExile.exe title = "D:/logs.txt" with open(title, "w") as f: f.write('\n') while 1==1: process_status=os.popen('tasklist|find /i "PathOfExile.exe" ||exit').read() if len(process_status)==0: time.sleep(5) msg="process doesn't exist! try to restart..." write_log(msg) # 模拟鼠标点击 mouse_click(1050, 540) time.sleep(1) mouse_click(1044, 540) time.sleep(1) mouse_click(1050, 536) time.sleep(1) mouse_dclick(1050, 540) time.sleep(5) <file_sep>/待自动化运行脚本/客户过期资料-数据监控/scripts/test.py import time title = "../output/logs.txt" current_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) with open(title, "w") as f: f.write(current_date) f.write('\n')<file_sep>/untitled/随机生成身份证号.py import random import time # 地区区域码,此范例只列出3位 areas = ('610622', '410901', '321281', '350581') # 身份证前17位权重 w17 = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2) # 校验位字典 crc_dict = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'} # 生成身份证号码 def create_zjhm(): while True: # 6位数字区域 zjhm = random.choice(areas) # 8位数字出生年月 t_start = time.mktime((1970, 1, 1, 9, 0, 0, 0, 0, 0)) t_end = time.mktime((1995, 1, 1, 9, 0, 0, 0, 0, 0)) random.randrange(start=t_start, stop=t_end) zjhm += time.strftime('%Y%m%d', time.gmtime(random.randrange(t_start, stop=t_end))) # 3位数字顺序 zjhm += '%03d' % random.randrange(start=0, stop=999) # 1位校验位, 根据前面17位号码,计算最后一个校验位,也可用于身份证校验 # 乘以权重之后求和,最后除以11求余 crc = sum(map(lambda z: z[0] * z[1], zip(w17, [int(i) for i in zjhm]))) % 11 # 根据余数映射字符 crc = crc_dict.get(crc) if not crc: time.sleep(1) #continue zjhm += crc if not zjhm or len(zjhm) != 18: time.sleep(1) #continue return zjhm if __name__ == '__main__': print(create_zjhm())<file_sep>/MD5算法/MD5-V1.0.py import hashlib import base64 pwd='<PASSWORD>' checkcode=hashlib.md5(pwd.encode('utf-8')).hexdigest() print(checkcode) pwd='<PASSWORD>' checkcode=hashlib.sha1(pwd.encode('utf-8')).hexdigest() print(checkcode)<file_sep>/企查查/下载历史记录.py import pymysql from selenium import webdriver from bs4 import BeautifulSoup import time,random import requests def s(a,b): tt=random.randint(a,b) time.sleep(tt) def insert_company_data(company_name,leader,registered_capital,founding_date,phone,email,address): db = pymysql.connect("localhost", "root", "123456", "company_data") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into company_info_sxd (company_name,leader,registered_capital,founding_date,phone,email,address) values('%s','%s','%s','%s','%s','%s','%s')" %(company_name,leader,registered_capital,founding_date,phone,email,address) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_company_name(): db = pymysql.connect("localhost", "root", "123456", "company_data") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select * from company_name where status=0" try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(table_id): db = pymysql.connect("localhost", "root", "123456", "company_data") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update company_name set status=1 where table_id='%s' and status=0" %(table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": browser = "Chrome" if browser == "Chrome": driver = webdriver.Chrome() else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() login_url='https://www.qichacha.com/user_login' driver.get(login_url) name = input("Go?") print(name) #完成登录 original_url="https://www.qichacha.com/user_download" s(4,6) num=1 while 1==1: download_url=original_url+".shtml?p="+str(num) driver.get(download_url) num+=1 a_lists=driver.find_elements_by_tag_name('a') for i in range (len(a_lists)): try: href=a_lists[i].get_attribute('href') print(href) if '.xls' in href: print("downloading with requests") xls_name=href.split("/")[-1] r = requests.get(href) with open(xls_name, "wb") as code: code.write(r.content) s(2, 3) except TypeError as e: pass <file_sep>/untitled/灯问题.py n=2015 sum1=[] for i in range(1,n+1): #1循环到2015,i作为除数 for j in range(1,n+1): if j%i==0: #如果被整除 j =1 <file_sep>/MMBAO/关键词获取出现频率脚本/main.py #将数据从excel中获取到list中 import xlrd import pymysql def print_xls(): data=xlrd.open_workbook(r"D:\BI\买卖宝\关键词.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 PRT_NAME=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss PRT_NAME.append(ss) return PRT_NAME def find_data(name): #输入:关键词 #输出:count,出现频率 db = pymysql.connect("192.168.180.159", "root", "1<PASSWORD>", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select * from TMP_ORDER_PRT_NAME where prt_name like '%"+str(name)+"%' and PRT_NAME not like '%产品规格%'" cnt=cursor.execute(sql) print(str(cnt)) cursor.close() db.close() if __name__=="__main__": PRT_NAME=print_xls() print(PRT_NAME) for i in range(len(PRT_NAME)): name=PRT_NAME[i] name=str(name).replace("[","").replace("]","").replace(",","").replace("'","") find_data(name) <file_sep>/untitled/Selenium/西域网/Xiyu-2.1.py #coding=utf-8 import random import time import re import os import bs4 import pymysql import datetime import urllib.request from selenium import webdriver def s(a,b): rand=random.randint(a,b) time.sleep(rand) #定义需要处理的品牌 def company_info(): para_brand='施耐德' return para_brand def createFileWithFileName(localPathParam,fileName): totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath def getAndSaveImg(img_url, img_name): company_name = company_info() if (len(img_url) != 0): fileName = img_name + '.jpg' file_Path="C:\\Xiyu\\Upload\\IMG"+"\\"+company_name try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_Path, fileName)) except: print("这图我没法下载") #获取商品列表中详细数据 def get_data(cate_id): d_prt_name = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/div[@class='productName']/a/span") d_type1 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[1]") d_type2 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[2]") d_type3 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[3]") d_type4 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[4]") d_type5 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[5]") d_type6 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[6]") d_type7 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[7]") d_type8 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[8]") d_type9 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[9]") d_type10 = driver.find_elements_by_xpath("//div[@class='showArea listMode']/div[@class='product']/ul/li[10]") d_price = driver.find_elements_by_xpath("//ul[@class='product-parameter']/li/span[@class='now_money']") d_img_url=driver.find_elements_by_xpath("//div[@class='proImg']/div[@class='ico-div']/img") print(str(len(d_prt_name)) + " " + str(len(d_type1)) + " " + str(len(d_price))+ " " + str(len(d_img_url))) for j in range(len(d_prt_name)): prt_name = d_prt_name[j].text #重新定义img_url nowTime=datetime.datetime.now().strftime("%Y%m%d%H%M%S") randomNum=random.randint(0,100) if randomNum<=10: randomNum=str(0)+str(randomNum) uniqueNum=str(nowTime)+str(randomNum) img_url=d_img_url[j].get_attribute("src") #print(img_url) img_name = uniqueNum #print(img_name) #getAndSaveImg(img_url, img_name) type1 = d_type1[j].text type2 = d_type2[j].text type3 = d_type3[j].text try: type4 = d_type4[j].text except: type4="" try: type5 = d_type5[j].text except: type5="" try: type6 = d_type6[j].text except: type6="" try: type7 = d_type7[j].text except: type7="" try: type8 = d_type8[j].text except: type8="" try: type9 = d_type9[j].text except: type9="" try: type10 = d_type10[j].text except: type10="" price = d_price[j].get_attribute('title') #print(prt_name + "// " + type1 + "// " + type2 + "// " + type3 + "// " + type4 + "// " + type5 + "// " + type6 + "// " + type7 + "// " + type8 + "// " + price + "// ") mysql_insert_main(cate_id,str(prt_name), str(type1), str(type2), str(type3), str(type4), str(type5), str(type6), str(type7),str(type8),str(type9),str(type10), str(price),str(img_url),str(img_name)) #翻页 def next_page(j): driver.find_element_by_xpath("//div[@class='pagintion']/li[@class='pg-next']/a").click() s(4,6) #从品牌的查询结果中,对category的类目进行获取相应的数据 def get_url(): cate_ids=[] cate_urls=[] #点击更多按钮 try: driver.find_element_by_css_selector(".moreSelection.ev-expandAttr").click() except: print("类目已经展示完整") s(1,2) #category_lists=driver.find_elements_by_xpath("//div[@class='filter ']/div[@class='category expand']/div[@class='categoryWrap']/a[contains(@href,'category')]") #print(len(category_lists)) category_lists=driver.find_elements_by_xpath("//div[@class='filter ']/div[contains(@class,'category')]/div[@class='categoryWrap']/a[contains(@href,'category')]") #print(len(category_lists)) for i in range(len(category_lists)): cate_name=category_lists[i].find_element_by_tag_name("span").text cate_url=category_lists[i].get_attribute("href") # cate_id 取url中的category,使用string[a:b]截取字符串 cate_id = cate_url[cate_url.index("category-") + 9:cate_url.index("?k")] #print(cate_name+"// "+cate_url) #单独的设计一套数据表,用于存放西域的数据,不然后期的数据没法看 insert_mysql_cate(cate_id,cate_name,cate_url) #把结果返回出去,或者list cate_ids.append(cate_id) cate_urls.append(cate_url) return cate_ids,cate_urls #插入主要关键数据 def mysql_insert_main(cate_id,prt_name,type1,type2,type3,type4,type5,type6,type7,type8,type9,type10,price,img_url,img_name): company_name = company_info() db = pymysql.connect("localhost","root","123456","xiyu",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql="insert into xiyu_main " \ " (company_name,category_id,prt_name,type1,type2,type3,type4,type5,type6,type7,type8,type9,type10,price,img_url,img_name)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (company_name,cate_id,prt_name,type1,type2,type3,type4,type5,type6,type7,type8,type9,type10,price,img_url,img_name) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:'+str(err)) # 关闭数据库连接 db.close() #插入类目 def insert_mysql_cate(category_id,category_name,category_url): company_name = company_info() db = pymysql.connect("localhost","root","123456","xiyu",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into category " \ " (company_name,category_id,category_name,category_url)" \ " values('%s','%s','%s','%s')" \ % (company_name,category_id,category_name,category_url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() #类目属性 def insert_mysql_cate_attr(category_id,type_id,category_attr): company_name = company_info() db = pymysql.connect("localhost","root","123456","xiyu",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into category_attributes " \ " (company_name,category_id,type_id,type_name)" \ " values('%s','%s','%d','%s')" \ % (company_name,category_id,type_id,category_attr) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() def insert_mysql_cate_attr_value(category_id,type_id,type_name,type_value): company_name = company_info() db = pymysql.connect("localhost","root","123456","xiyu",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into category_attributes_values " \ " (company_name,category_id,type_id,type_name,type_value)" \ " values('%s','%s','%d','%s','%s')" \ % (company_name,category_id,type_id,type_name,type_value) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() #存入列表的标题 def insert_mysql_list_title(category_id,title_id,title): company_name = company_info() db = pymysql.connect("localhost","root","123456","xiyu",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into list_title " \ " (company_name,category_id,title_id,title)" \ " values('%s','%s','%s','%s')" \ % (company_name,category_id,title_id,title) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() #获取每个类目页面的类目属性 def get_cate_attr2(cate_id): try: driver.find_element_by_css_selector(".showmore-tips.showmore-text").click() except: print("不需要展开") s(1,2) #获取每一行 attr_lists=driver.find_elements_by_xpath("//div[contains(@class,'category') and contains(@data-id,'da_') and contains(@ng-class,'eachAttr.isExpand')]") print("共"+str(len(attr_lists))+"行属性") for i in range (len(attr_lists)): cate_attr = attr_lists[i].find_element_by_class_name("category-name-span").text type_id=i+1 insert_mysql_cate_attr(cate_id,type_id,cate_attr) #print(cate_attr) cate_attr_values = attr_lists[i].find_elements_by_xpath("./div[@class='categoryWrap']/a[contains(@class,'categoryEach')]")#当下路径用./ #print("该属性共"+str(len(cate_attr_values))+"条属性值") for j in range(len(cate_attr_values)): cate_attr_value=cate_attr_values[j].find_element_by_tag_name("span").text #print(cate_attr_value) insert_mysql_cate_attr_value(cate_id,type_id,cate_attr,cate_attr_value) #获取列表的标题 def get_cate_title(cate_id): #修改了一下,之前是因为直接通过相对路径,导致“xiyu价”抓不到,修改后即可 list_titles_tmp=driver.find_element_by_xpath("//li[@class='commodity-parameter']") list_titles=list_titles_tmp.find_elements_by_tag_name("span") title_num=len(list_titles) #print("标题共"+str(title_num)+"个") ################################################################## #后续获取span[i] for i in range (len(list_titles)): title_id='type'+str(i+1) title=list_titles[i].text insert_mysql_list_title(cate_id, title_id, title) return title_num def get_page_num(): page_num=driver.find_element_by_class_name("fullPage").text return page_num if __name__=='__main__': #定义一系列数组,2.1版本,将自动获取这些url para_brand=company_info() url='http://www.ehsy.com/search?k='+para_brand driver=webdriver.Firefox() driver.get(url) s(3,5) #获取分类,返回category_list category_id,category_list=get_url() driver.quit() for i in range (len(category_list)): m=i #print(str(m)) cate_id=category_id[m] print(category_list[m]) #print(category_id[i]) #这里重新打开一个页面,是简单的防止浏览器假死,导致后续直接崩溃,所以在跑完一个类目(包括翻页)后关闭 driver = webdriver.Firefox() driver.get(category_list[m]) s(4, 5) get_cate_attr2(cate_id) title_num=get_cate_title(cate_id) print("标题共" + str(title_num) + "个") page_num=get_page_num() print("当前类目商品共"+page_num+"页") #在进入循环之前,还有事情要做 for j in range(int(page_num)): get_data(cate_id) try: next_page(j) except: print("没有下一页") break driver.quit() <file_sep>/OA_FEGROUP/日报提醒助手_1.1.py #2018年4月13日15:11:58增加了工作日报详细的判断 import requests import base64 from bs4 import BeautifulSoup from utils import AliyunSMS import pymysql import time import random def s(a,b): time_=random.randint(a,b) time.sleep(time_) def get_content(url): s = requests.get(url,headers=headers) content = s.content.decode('gbk') #print(content) cookie = s.cookies #print(cookie) return content,cookie def find_data_from_content(content): soup=BeautifulSoup(content,'html.parser') liNoSubmit=soup.find('li',attrs={'id':'liNoSubmit'}).text #print(liNoSubmit.replace(" ","")) liNo=liNoSubmit.replace("未提交(","").replace(")","") return liNo def get_login_data(): db = pymysql.connect("localhost", "root", "123456", "oa_msg") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select user_name,password,hidEpsKeyCode,phone_num from oa_login_info where status=1 " #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as e: db.rollback() print('------get_login_data---------Error------Message--------:' + str(e)) cursor.close() db.close() def find_detail(submit_content): soup=BeautifulSoup(submit_content,'html.parser') type=[] date=[] tbody_trs=soup.find('tbody',attrs={'id':'lpEffSubmit_TBody'}).find_all('tr',attrs={'class':'evenLine'}) #print("%s条未提交的工作报表"%str(len(tbody_trs))) for i in range(len(tbody_trs)): tds=tbody_trs[i].find_all('td') report_type=tds[3].text report_date=tds[5].text #print(report_type,report_date) type.append(report_type) date.append(report_date) return type,date if __name__=="__main__": headers = { "Host" : "oa.fegroup.cn:8090", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer" : "http://oa.fegroup.cn:8090/c6/jhsoft.web.ydmh/myindex.aspx?moduleid=01400030", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" } # post发送的数据 #从mysql获取oa登录信息 login_data=get_login_data() for i in range (len(login_data)): user_name=login_data[i][0] password=login_data[i][1] hidEpsKeyCode=login_data[i][2] phone_num=login_data[i][3] #用户名密码作BASE64处理 loginCode=base64.b64encode(user_name.encode(encoding='utf-8')) pwd=base64.b64encode(password.encode(encoding='utf-8')) loginCode=str(loginCode).split("'")[1] pwd=str(pwd).split("'")[1] #print(loginCode,pwd) url=u'http://oa.fegroup.cn:8090/c6/Jhsoft.Web.login/AjaxForLogin.aspx?type=login&loginCode=%s&pwd=%s&hidEpsKeyCode=%s' %(loginCode,pwd,hidEpsKeyCode) print(url) content,cookie=get_content(url) report_url="http://oa.fegroup.cn:8090/c6/JHSoft.web.Aging/ReportMG.aspx" result=requests.get(report_url,cookies=cookie) content=result.content.decode('gbk') liNo=find_data_from_content(content) if int(liNo)>=1: # 新增功能,获取哪份日报未提交 report_detail_url = "http://oa.fegroup.cn:8090/c6/JHSoft.web.Aging/ReportSubmit.aspx" submit_result = requests.get(report_detail_url, cookies=cookie, headers=headers) submit_content = submit_result.content.decode('gbk') # print(submit_content) type, date = find_detail(submit_content) # 暂时不做处理,如果有多条未提交的 report_type = "" report_date = "" for x in range(len(type)): report_type = type[x] report_date = date[x] if report_type == "工作日志": break #如果有多条记录,就加个等吧 if len(type)>1: report_type=report_type+"等" if report_type != "": #print("有%s条未提交的%s"%(str(int(liNo)),report_type)) times=str(int(liNo)) print("您有%s条日报记录异常,%s,%s,请及时处理!"%(times,report_date,report_type)) sms = AliyunSMS() params = {"times": times, "date":report_date, "report_type":report_type } # 这就是随机生成的6位数 sms.send_single(phone=phone_num, sign="小旋风", template='SMS_130923451', params=params) else: #else的情况,可能就是月报了 pass s(1,8) <file_sep>/MMBAO/产品库数据校验/检查所有的属性数据ID是否正确.py import pymysql import cx_Oracle def get_mysql_data(): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select attr_id,attr_name,attr_value_id,attr_value from attribute_check where status=0" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def oracle_spu_data(attr_id,attr_value_id): db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.mmbao.com:21252/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT attr_val_value FROM mmbao2.v_cat_attr_val "\ "WHERE lev3_cat_id='2015032800001362' AND attr_id='%s' AND attr_val_id='%s'" %(attr_id,attr_value_id) # and create_date>to_date('%s','yy/MM/dd') # 因为还得分为新增和更新 # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def insert_log(table_name,error_id,content): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into log (table_name,error_id,content) values('%s','%s','%s')" %(table_name,error_id,content) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": data=get_mysql_data() for i in range (len(data)): attr_id=data[i][0] attr_name=data[i][1] attr_value_id=data[i][2] attr_value=data[i][3] data2=oracle_spu_data(attr_id, attr_value_id) print("查询结果%s条"%str(len(data2))) if len(data2)==1: if attr_value==data2[0][0]: print("-------") else: table_name="" error_id="" content=attr_id+","+attr_name+","+attr_value_id+","+attr_value+"值不匹配" insert_log(table_name,error_id,content) else: table_name = "" error_id = "" content = attr_id + "," + attr_name + "," + attr_value_id + "," + attr_value+"多条" insert_log(table_name,error_id,content) <file_sep>/待自动化运行脚本/客户过期资料-数据监控/scripts/数据校对.py import xlrd import time import os import logging import datetime from xlrd import xldate_as_tuple #把excel的数据直接存到临时数组,直接进行分析,抛弃mysql支持 class excel_operation(): def foreach(self,rootDir): files_excel=[] for root,dirs,files in os.walk(rootDir): for file in files: file_name=os.path.join(root,file) if 'xls' in file_name: files_excel.append(file_name) for dir in dirs: self.foreach(dir) return files_excel def get_excel_data(self): excel_dir = "..\input" path=os.path.abspath(excel_dir) #print(path) files_excel=self.foreach(path) #print(files_excel) for file_name in files_excel: #excel_name=r"..\input\33-006(1).xlsx" excel_name=file_name.split('\\')[-1] print(excel_name) data = xlrd.open_workbook(file_name) # 打开excel # print("当前excel共有%s个SHEET" % str(len(data.sheets()))) sheetName = data.sheet_names()[0] # print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[0] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] print(sheetName,nrows) 序号=[] 合同编号=[] 合同号=[] 客户合同号=[] 客户名称=[] 签订日期=[] 合同金额=[] 发放金额=[] 已履行金额=[] 付款方式=[] 定价原则=[] 原件返回类型=[] 原件返还日期=[] 交货期=[] 收货地址=[] 操作=[] 客户经理=[] for i in range (1,int(nrows)): row_info=table.row_values(i) #print(row_info) 序号.append(row_info[0]) 合同编号.append(row_info[1]) 合同号.append(row_info[2]) 客户合同号.append(row_info[3]) 客户名称.append(row_info[4]) 签订日期.append(row_info[5]) 合同金额.append(row_info[6]) 发放金额.append(row_info[7]) 已履行金额.append(row_info[8]) 付款方式.append(row_info[9]) 定价原则.append(row_info[10]) 原件返回类型.append(row_info[11]) 原件返还日期.append(row_info[12]) 交货期.append(row_info[13]) 收货地址.append(row_info[14]) 操作.append(row_info[15]) 客户经理.append(row_info[16]) 客户名称_filtered=list(set(客户名称)) #print(str(len(签订日期)), 签订日期) #print(str(len(客户名称_filtered)),客户名称_filtered) for x in range (len(客户名称_filtered)): #print(客户名称_filtered[x]) index_info=self.find_index(客户名称,客户名称_filtered[x]) expiration_date =签订日期[index_info[0]] master = 客户经理[index_info[0]] t_序号=序号[index_info[0]] t_合同编号=合同编号[index_info[0]] t_合同号=合同号[index_info[0]] t_客户合同号=客户合同号[index_info[0]] t_客户名称 =客户名称[index_info[0]] t_签订日期 =签订日期[index_info[0]] t_合同金额 =合同金额[index_info[0]] t_发放金额 =发放金额[index_info[0]] t_已履行金额 =已履行金额[index_info[0]] t_付款方式 =付款方式[index_info[0]] t_定价原则 =定价原则[index_info[0]] t_原件返回类型 =原件返回类型[index_info[0]] t_原件返还日期 =原件返还日期[index_info[0]] t_交货期 =交货期[index_info[0]] t_收货地址 =收货地址[index_info[0]] t_操作 =操作[index_info[0]] t_客户经理 =客户经理[index_info[0]] for y in range (len(index_info)): another_expiration_date=签订日期[index_info[y]] if time.strptime(str(expiration_date), "%Y/%m/%d") < time.strptime(str(another_expiration_date),"%Y/%m/%d"): expiration_date = another_expiration_date master = 客户经理[index_info[y]] t_序号 = 序号[index_info[y]] t_合同编号 = 合同编号[index_info[y]] t_合同号 = 合同号[index_info[y]] t_客户合同号 = 客户合同号[index_info[y]] t_客户名称 = 客户名称[index_info[y]] t_签订日期 = 签订日期[index_info[y]] t_合同金额 = 合同金额[index_info[y]] t_发放金额 = 发放金额[index_info[y]] t_已履行金额 = 已履行金额[index_info[y]] t_付款方式 = 付款方式[index_info[y]] t_定价原则 = 定价原则[index_info[y]] t_原件返回类型 = 原件返回类型[index_info[y]] t_原件返还日期 = 原件返还日期[index_info[y]] t_交货期 = 交货期[index_info[y]] t_收货地址 = 收货地址[index_info[y]] t_操作 = 操作[index_info[y]] t_客户经理 = 客户经理[index_info[y]] #print("max", expiration_date,客户名称_filtered[x],index_info) #将最大的日期和当前日期比较,如果小于当前日期,那么记log self.compare_with_now(excel_name,客户名称_filtered[x],expiration_date,t_序号,t_合同编号,t_合同号,t_客户合同号,t_客户名称,t_签订日期,t_合同金额,t_发放金额,t_已履行金额,t_付款方式,t_定价原则,t_原件返回类型,t_原件返还日期,t_交货期,t_收货地址,t_操作,t_客户经理) def find_index(self,data,index_data): #data=[1,2,3,4,4,5,5,5,5,5,5,4,4,4,4,4,5,5,5,5,5] times=[] s1=data for i in range (len(data)): try: i=s1.index(index_data) times.append(i) s1[i]='git' except ValueError as e: #print(e) break #print(times) return times def compare_with_now(self,excel_name,company_name,expiration_date,t_序号,t_合同编号,t_合同号,t_客户合同号,t_客户名称,t_签订日期,t_合同金额,t_发放金额,t_已履行金额,t_付款方式,t_定价原则,t_原件返回类型,t_原件返还日期,t_交货期,t_收货地址,t_操作,t_客户经理): str_now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) #print(str_now) now_time = time.strptime(str_now, '%Y-%m-%d %H:%M:%S') exp_time=time.strptime(str(expiration_date), "%Y/%m/%d") str_exp_time=time.strftime("%Y/%m/%d",exp_time) #print(str_exp_time) delta = (now_time.tm_year - exp_time.tm_year) * 365 + (now_time.tm_yday - exp_time.tm_yday) #print(delta) if delta>365: self.record_log(excel_name,company_name,expiration_date,t_序号,t_合同编号,t_合同号,t_客户合同号,t_客户名称,t_签订日期,t_合同金额,t_发放金额,t_已履行金额,t_付款方式,t_定价原则,t_原件返回类型,t_原件返还日期,t_交货期,t_收货地址,t_操作,t_客户经理) def record_log(self,excel_name,company_name,expiration_date,t_序号,t_合同编号,t_合同号,t_客户合同号,t_客户名称,t_签订日期,t_合同金额,t_发放金额,t_已履行金额,t_付款方式,t_定价原则,t_原件返回类型,t_原件返还日期,t_交货期,t_收货地址,t_操作,t_客户经理): with open(title, "a") as f: # 格式化字符串还能这么用! f.write(excel_name) f.write("@") f.write(company_name) f.write("@") f.write(expiration_date) f.write("@") f.write(str(t_序号)) f.write("@") f.write(str(t_合同编号)) f.write("@") f.write(str(t_合同号)) f.write("@") f.write(str(t_客户合同号)) f.write("@") f.write(str(company_name)) f.write("@") f.write(str(t_签订日期)) f.write("@") f.write(str(t_合同金额)) f.write("@") f.write(str(t_发放金额)) f.write("@") f.write(str(t_已履行金额)) f.write("@") f.write(str(t_付款方式)) f.write("@") f.write(str(t_定价原则)) f.write("@") f.write(str(t_原件返回类型)) f.write("@") f.write(str(t_原件返还日期)) f.write("@") f.write(str(t_交货期)) f.write("@") f.write(str(t_收货地址)) f.write("@") f.write(str(t_操作)) f.write("@") f.write(str(t_客户经理)) f.write('\n') if __name__=="__main__": title = "../output/logs.txt" current_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) with open(title, "w") as f: f.write(current_date) f.write('\n') excel_operation=excel_operation() excel_operation.get_excel_data() <file_sep>/JD后台/VC后台/图片详情内容修改-我的商品.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) prt_codes = ['5915533', '5915551', '5915553', '5915569', '5915571', '5915525', '5915531', '5915557', '5915559', '5915567', '5915575', '5965444', '5915577', '5915579', '5915591', '5915537', '5915563', '5915565', '5965428', '5965438', '7011272', '7224941', '7224981', '5922079', '5969794', '5969796', '5922099', '5922109', '5969798' ] for i in range (len(prt_codes)): driver.find_element_by_id('wareId').send_keys(prt_codes[i]) self.s(3,4) driver.find_element_by_css_selector('.btn.btn-primary').click() self.s(3,4) prt_status_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_saleState']" prt_status = driver.find_element_by_xpath(prt_status_path).text print(prt_status) if "上柜" in prt_status: nowhandle = driver.current_window_handle # 在这里得到当前窗口句柄 btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_wareId']/div/button[@class='btn btn-default']" driver.find_element_by_xpath(btn_down_path).click() self.s(5, 6) #需要获取新弹开的窗口 allhandles = driver.window_handles # 获取所有窗口句柄 for handle in allhandles: # 在所有窗口中查找弹出窗口 if handle != nowhandle: driver.close() driver.switch_to.window(handle) current_url=driver.current_url print(current_url) driver.get(current_url) content=driver.page_source #print(content) self.s(3,4) driver.find_element_by_id('cid3Submit').click() self.s(4,6) #获取京东价市场价 #jd_price=driver.find_element_by_xpath("//table[@class='form-tb']/tbody/tr[@class='sensitiveField'][-2]/td").text #jd_price = driver.find_element_by_xpath("//table[@class='form-tb']/tbody/tr[@class='sensitiveField'][-2]/td").text driver.find_element_by_id('auditedSubmit').click() self.s(4, 7) #针对工业品,才会需要这个 driver.find_element_by_class_name("combo-arrow").click() cz = driver.find_elements_by_xpath("//div[@class='combobox-item' ]") caizhi="铜质" for y in range(len(cz)): jd_caizhi = cz[y].text # print(jd_caizhi) if caizhi == jd_caizhi: cz[y].click() driver.find_element_by_id('categoryAttrSubmitNew').click() self.s(4, 7) pc_text = driver.find_element_by_id("introHtml").text print(pc_text) pc_text = pc_text.replace( '<div style="text-align: center;">','<div style="text-align: center;"><img src="//img10.360buyimg.com/imgzone/jfs/t20578/235/1687371504/266068/a724dcf0/5b30891dN07bb77a6.jpg">') print(pc_text) driver.find_element_by_id("introHtml").clear() driver.find_element_by_id("introHtml").send_keys(pc_text) self.s(1,2) # 进入商品介绍代码页面 driver.find_element_by_id('mobile_intro').click() driver.find_element_by_xpath("//a[@href='#mobile_html']").click() self.s(3, 6) app_text = driver.find_element_by_id("introMobile").text # print(app_text) app_text = app_text.replace( '<div style="text-align: center;">','<div style="text-align: center;"><img src="//img10.360buyimg.com/imgzone/jfs/t24184/11/377241727/378223/1844b067/5b2dfdf3N249c088f.jpg">') print(app_text) driver.find_element_by_id("introMobile").clear() driver.find_element_by_id("introMobile").send_keys(app_text) #ss = input("Go?") #print(ss) driver.find_element_by_id('createApply').click() self.s(3, 6) driver.find_element_by_id('toApplyList').click() self.s(3, 6) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) else: pass if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/untitled/抓取图片2.0.py import urllib.request import os def get_page(url): req=urllib.request.Request(url) req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0') response=urllib.request.urlopen(url) html=response.read().decode('utf-8') a=html.find('current-comment-page')+23 b=html.find(']',a) print(html[a:b]) def find_imgs(page_url): pass def save_imgs(folder,img_addrs): pass def download_mm(folder='ooxx',pages=10): os.mkdir(folder) os.chdir(folder) url="http://jandan.net/ooxx" page_num=int(get_page(url)) for i in range(pages): page_num-=i page_url=url+'page-'+str(page_num)+'#comments' img_addrs=find_imgs(page_url) save_imgs(folder,img_addrs) if __name__=='__main__': download_mm() <file_sep>/untitled/Selenium/MMBAO/查询详情页的所有图片数据/查询详情页所有图片数据V1.0.py import pymysql import os from urllib import request from bs4 import BeautifulSoup import xlrd import time def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(img_url, img_name): if (len(img_url) != 0): fileName = img_name file_Path="D:\\IMG\\" request.urlretrieve(img_url, createFileWithFileName(file_Path,fileName)) def getHtml(url): try: req=request.Request(url) req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0") req.add_header("Host","www.mmbao.com") response=request.urlopen(req) html=response.read().decode('utf-8') #print(html) return html except: html="" return html def find_img(html,sku_id): try: soup=BeautifulSoup(html,'html.parser') img_datas=soup.find_all('img') for img_data in img_datas: img_url=img_data.get("src") if "/upload/" in img_url: if "http" not in img_url: img_url="http://www.mmbao.com/"+img_url img_name = img_url[img_url.rindex("/") + 1:100] getAndSaveImg(img_url, img_name) path = "D:\\IMG\\" + img_name img_data = os.path.getsize(path) size=str(float(img_data) / 1024) print(img_name,img_url,size) insert_data(sku_id,img_name,img_url,size) except: img_name="" img_url="" size="" insert_data(sku_id, img_name, img_url, size) def insert_data(sku_id,img_name,img_url,size): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_img_info (sku_id,img_name,img_url,size) values('%s','%s','%s','%s')" %(sku_id,img_name,img_url,size) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #从excel中获取url的列表数据 def get_data_from_excel(sheet_num): data=xlrd.open_workbook(r"D:\BI\商品信息.xlsx") #打开excel #sheetName = data.sheet_names()[sheet_num] table=data.sheets()[sheet_num] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 url_lists=[] #print(sheetName) for i in range(1,nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss url_lists.append(ss) return url_lists if __name__=="__main__": sku_ids=get_data_from_excel(0) for sku_id in sku_ids: sku_id=str(sku_id).replace("['","").replace("']","") print(sku_id) url="http://trade.mmbao.com/s_"+sku_id+".html" print(url) html=getHtml(url) if html=="": continue #print(html) find_img(html,sku_id) time.sleep(2) <file_sep>/untitled/Selenium/test8 from 4.py #coding=utf-8 import bs4 import xlsxwriter from untitled.Selenium import webdriver def save_excel(fin_result, file_name): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\%s.xlsx' % file_name) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') row_num = len(fin_result) for i in range(0, row_num): #print('##############') fin_a=fin_result[i] #从50*2的二维数组中,遍历i后获取的每个一维数组 for j in range(0, len(fin_a)): fin_b = fin_result[i][j] #print(fin_b) for k in fin_b: #print(k) tmp.write(i, j, k) tmp.write(i, 0, fin_result[i][0]) #tmp.write(i,j,fin_a[j]) #for j in range (0,2): # tmp.write(i,j,fin_a[j]) driver = webdriver.PhantomJS() driver.get("http://search.mmbao.com/0_0_0.html?enc=utf-8&model_a=BVR&spec_a=10") driver.find_element_by_id('searchBarText').send_keys("德力西") driver.find_element_by_id("Button1").click() #print (driver.current_url) source=driver.page_source #查询列表页数 total_pages=driver.find_element_by_css_selector(".pagination.pagewidget.mt20")#筛选出转页所在的div page=total_pages.find_elements_by_tag_name('a')#再次进行筛选,得出<a>标签跳转页面链接 driver.quit() for i in range (0,len(page)): print(page[i]) #分页处理 bs_obj = bs4.BeautifulSoup(source,"html.parser") bs_div_title=bs_obj.findAll('div',attrs={'class':'tit mt5'}) bs_div_price=bs_obj.findAll('div',attrs={'class':'price clearfix'}) page_title= [[] for num in range(len(bs_div_title))] page_price=[[] for num in range(len(bs_div_price))] for i in range (0,len(bs_div_title)): page_title[i].append(bs_div_title[i].text) page_price[i].append(bs_div_price[i].text) page_title[i].append(page_price[i])#将title和price两个一维数组的数据整合成一个二维数组 <file_sep>/untitled/Selenium/test 4 mysql.py #coding=utf-8 #'latin-1' codec can't encode characters in position 132-141: ordinal not in range(256) #http://blog.csdn.net/csdnwws/article/details/51954825 import pymysql import xlrd def print_xls(): data=xlrd.open_workbook(r"C:\Users\Administrator\Desktop\电缆行业700强企业20170313.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 Company_Name=[] for i in range(2,nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss Company_Name.append(ss) return Company_Name db = pymysql.connect("192.168.180.147","root","123456","test01" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " Company_Name=print_xls() for i in range (0,len(Company_Name)): sql="insert into Cables_Company_Info_test " \ " (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category)" \ " values('%d','%s','%s','%s','%s','%s','%s','%s')" \ % (Company_Name[i][0],Company_Name[i][1],Company_Name[i][2],Company_Name[i][3],Company_Name[i][4],Company_Name[i][5],Company_Name[i][6],Company_Name[i][7]) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() print('----第'+str(i+1)+'条-----------Finished--'+str(int(Company_Name[i][0]))+'-----'+Company_Name[i][1]+'--------') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error--------------'+err) # 关闭数据库连接 db.close() <file_sep>/日常工作/获取taobao列表数据.py import requests import re from bs4 import BeautifulSoup def get_content(url): s = requests.get(url) content = s.content.decode('gbk','ignore') print(content) return content if __name__=="__main__": url="https://shop277740509.taobao.com/search.htm?spm=a1z10.1-c.0.0.56291ba8iu3uYm&search=y" content=get_content(url) soup=BeautifulSoup(content,'html.parser') main_menu=soup.find_all('p',attrs={'class':'desc'}) for i in range (len(main_menu)): print("https:"+main_menu[i].find('a').get('href')) <file_sep>/untitled/Selenium/test6-excel.py import xlsxwriter book=xlsxwriter.Workbook("D:\test1.xlsx") tmp=book.add_worksheet("sheet2") tmp.write(0,0,1) tmp.save() <file_sep>/日常工作/筛选电线类型所对应商品销量-part2-史旭东-2018年5月9日0918.py import pymysql def find_keywords(): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select keyword,sku_title,month from keyword_sku_0509 group by keyword,sku_title,month" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def get_prt_info(keyword,sku_title,month): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select sale_cnt from keyword_sku_0509 where keyword='%s' and sku_title='%s' and month='%s' " %(keyword,sku_title,month) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_data(keyword,sku_title,month,cnt): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into keyword_sku_cnt_0509 (keyword,sku_title,month,cnt) values('%s','%s','%s','%s')" %(keyword,sku_title,month,cnt) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": keyword_data=find_keywords() for i in range (len(keyword_data)): keyword=keyword_data[i][0] sku_title=keyword_data[i][1] month=keyword_data[i][2] print("keyword:",keyword,"sku_title",sku_title,",month",month) cnt_info=get_prt_info(keyword,sku_title,month) cnt=0 for x in range (len(cnt_info)): cnt=cnt+int(cnt_info[x][0]) insert_data(keyword,sku_title,month,cnt) <file_sep>/MMBAO/产品库数据校验/P2-对不完整的SKU源数据进行确认状态分类等.py import pymysql import cx_Oracle def get_original_sku_data(): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "zydmall_delixi", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select prt_id,sku_id,sku_type,po_number from `不完整SPU的SKU源数据` where is_exist is null order by table_id limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def check_data_in_oracle(prt_id,sku_id,sku_type,po_number): #将这些值带入到oracle数据表中查看 db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.58.3:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT a.ID AS SKU_ID,a.prt_id,a.po_number,c.ATTR_VAL as sku_type,b.prt_title FROM mmbao2.t_prt_sku a "\ "LEFT JOIN mmbao2.t_prt_entity b "\ "ON a.prt_id=b.id "\ "LEFT JOIN mmbao2.t_prt_sku_item c "\ "ON a.id=c.prt_sku_id AND c.attr_name='型号' "\ "WHERE a.po_number LIKE '%s' OR C.ATTR_VAL LIKE '%s' "\ %(po_number,sku_type) # and create_date>to_date('%s','yy/MM/dd') # 因为还得分为新增和更新 #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def update_original_data(prt_id,sku_id,new_sku_id,new_prt_id,new_po_number,new_sku_type,new_prt_title,is_exist): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update `不完整SPU的SKU源数据` set new_sku_id='%s',new_prt_id='%s',new_po_number='%s',new_sku_type='%s',new_prt_title='%s',is_exist='%d' "\ "where prt_id='%s' and sku_id='%s' " %(new_sku_id,new_prt_id,new_po_number,new_sku_type,new_prt_title,is_exist,prt_id,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #获取mysql数据表的数据 for i in range (7000): data1=get_original_sku_data() prt_id=data1[0][0] sku_id=data1[0][1] sku_type=data1[0][2] po_number=data1[0][3] print(prt_id,sku_id,sku_type,po_number) #将这些值带入到oracle数据表中查看 data2=check_data_in_oracle(prt_id,sku_id,sku_type,po_number) print("查找到%s条数据"%str(len(data2))) if len(data2)>0: #如果数据大于0,说明有值,那么就把数据回填到这条记录中去 is_exist=1 new_sku_id=data2[0][0] new_prt_id=data2[0][1] new_po_number=data2[0][2] new_sku_type=data2[0][3] new_prt_title=data2[0][4] #print(new_sku_id,new_prt_id,new_po_number,new_sku_type,new_prt_title) else: is_exist=0 new_sku_id="" new_prt_id="" new_po_number="" new_sku_type="" new_prt_title="" print(new_sku_id, new_prt_id, new_po_number, new_sku_type, new_prt_title) #回填更新数据 update_original_data(prt_id,sku_id,new_sku_id,new_prt_id,new_po_number,new_sku_type,new_prt_title,is_exist) <file_sep>/suning/苏宁后台/苏宁后台通过详情url获取具体内容.py import pymysql import random,time import os from bs4 import BeautifulSoup from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,login_url): browser = "Chrome" if browser == "Chrome": #profile_dir = r"C:\Users\CC-SERVER\AppData\Local\Google\Chrome\User Data" # 对应你的chrome的用户数据存放路径 options = webdriver.ChromeOptions() #options.add_argument("user-data-dir=" + os.path.abspath(profile_dir)) driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(login_url) name = input("Go?") print(name) prt_data=self.get_prt_content_url() for i in range (len(prt_data)): prt_id=prt_data[i][0] prt_content_url=prt_data[i][1] driver.get(prt_content_url) self.s(2,4) content=driver.page_source self.find_details(prt_id,content) #完成数据摘取,进行状态回填 self.update_status(prt_id) def update_status(self,prt_id): db = pymysql.connect("localhost", "root", "123456", "suning") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update suning_prt_content_url set status=1 where status=0 and prt_id='%s' " %prt_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_prt_content_url(self): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "suning") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_id,prt_content_url from suning_prt_content_url where status=0" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('------get_prt_content_url---------Error------Message--------:' + str(err)) cursor.close() db.close() def find_details(self,prt_id,content): soup=BeautifulSoup(content,'html.parser') #页面分为很多块内容 #1.基本信息 #2.商品规格 # 颜色图片,颜色,类型,售价,库存,库存预警值,鱼口库存,条形码,商家商品编码 #self.get_prt_guige(content) #3.商品详情 self.get_prt_detail(prt_id,content) def get_prt_detail(self,prt_id,content): soup = BeautifulSoup(content, 'html.parser') prt_content_names = soup.find_all("h3", attrs={'class': 'mt10 sub-title'}) prt_content_parts = soup.find_all("div", attrs={'class': 'proinfo'}) print(len(prt_content_names),len(prt_content_parts)) prt_detail_content,prt_sku_content = "","" for a in range (len(prt_content_names)): content_name=prt_content_names[a].text print(content_name) if content_name=="商品详情": prt_detail_content=prt_content_parts[a].find('table',attrs={'class':'infotable mt10'}).find('tbody').find_all('tr') if "商品规格" in content_name: prt_sku_content = prt_content_parts[a].find('table', attrs={'class': 'prostandard mt10'}).find('tbody') print(prt_sku_content) # 商家商品编码,商品标题,商品卖点,商品图片,商品白底图,电脑端详情,确认发布 if prt_detail_content!="": print(len(prt_detail_content)) prt_code, prt_title, prt_sale_point, prt_desc = "", "", "", "" for i in range (len(prt_detail_content)): tr=prt_detail_content[i].find_all('td') td_name=tr[0].text td_value = tr[1].text.replace(" ","").replace("\n","") print(td_name,td_value) if "商家商品编码" in td_name: prt_code=td_value print(prt_code) elif "商品标题" in td_name: prt_title = td_value print(prt_title) elif "商品卖点" in td_name: prt_sale_point=td_value print(prt_sale_point) elif "商品图片" in td_name: img_lists=tr[1].find_all('img') #print(img_lists) for x in range(len(img_lists)): img_src=img_lists[x].get('src') img_num=str(x+1) img_type="main_img" print(img_src) self.insert_img_data(prt_id, img_num, img_src, img_type) elif "商品白底图" in td_name: img_bottom_lists = tr[1].find_all('img') for y in range(len(img_bottom_lists)): img_bottom_src = img_bottom_lists[y].get('src') print(img_bottom_src) img_num=str(y+1) img_type="bottom_img" self.insert_img_data(prt_id, img_num, img_bottom_src, img_type) elif "商品详情" in td_name: prt_desc=tr[1].find('iframe',attrs={'id':'introduceEditFrame'}) print(prt_desc) self.insert_data(prt_id,prt_code,prt_title,prt_sale_point,prt_desc) if prt_sku_content!="": img_lists = prt_sku_content.find_all('img') print(img_lists) for y in range(len(img_lists)): img_src = img_lists[y].get('src') img_num = str(y + 1) img_type = "sku_img" print(img_src) self.insert_img_data(prt_id, img_num, img_src, img_type) #设计后台存储表 def insert_data(self,prt_id,prt_code,prt_title,prt_sale_point,prt_desc): db = pymysql.connect("localhost", "root", "123456", "suning") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into suning_prt_data (prt_id,prt_code,prt_title,prt_sale_point,prt_desc) values('%s','%s','%s','%s','%s')" %(prt_id,prt_code,prt_title,prt_sale_point,prt_desc) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_data--------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_img_data(self,prt_id,img_num,img_url,img_type): db = pymysql.connect("localhost", "root", "123456", "suning") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into suning_img_data (prt_id,img_num,img_url,img_type) values('%s','%s','%s','%s')" %(prt_id,img_num,img_url,img_type) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------insert_img_data------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" login_url="https://mpassport.suning.com/ids/login" main.init(login_url) <file_sep>/TMALL/数据分析架构模式化/tmall商品图片筛选下载/将图片信息整理成prt_content.py import pymysql def get_prt_imgs_from_table(): db = pymysql.connect("localhost", "root", "123456", "mmbao") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id from prt_img_copy where img_type='desc_img' group by prt_id" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_prt_imgs(prt_id): db = pymysql.connect("localhost", "root", "123456", "mmbao") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select c.sku_id,a.* from prt_img_copy a left join sku_info c on a.prt_id=c.prt_id where img_type='desc_img' and a.prt_id='%s' " %prt_id #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": data=get_prt_imgs_from_table() for i in range(len(data)): prt_id=data[i][0] img_lists=get_prt_imgs(prt_id) prt_content_start = '<div id="md2" class="mb list-boxw" style="margin-bottom: 0;border-bottom:none;">' for x in range (len(img_lists)): sku_id=img_lists[x][0] img_path=img_lists[x][5] img_html='<p><img src="'+img_path+'" >' prt_content_start=prt_content_start+img_html prt_content=prt_content_start+'</div>' print(sku_id,"~",prt_content) <file_sep>/进销存系统/main.py import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import (QWidget, QToolTip,QPushButton, QApplication,QMessageBox,QMainWindow, QAction, qApp,) from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QLabel, QLineEdit,QTextEdit, QGridLayout class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): QToolTip.setFont(QFont('SansSerif', 10)) self.initButton() self.menu_bar() self.tool_bar() self.resize(750, 500) self.move(300, 300) #self.setGeometry(300, 300, 300, 200) self.setWindowTitle('INVOICING-MANAGEMENT-SYS') # 修改默认的图标 self.setWindowIcon(QIcon('ico1.ico')) self.show() def menu_bar(self): exitAction = QAction(QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) def tool_bar(self): #add_user User_Action = QAction(QIcon('add_user.png'), 'Add_User', self) User_Action.setShortcut('Ctrl+A') #connect所链接的事件需要修改 User_Action.triggered.connect(self.add_user_clicked) self.toolbar = self.addToolBar('Add_User') self.toolbar.addAction(User_Action) #add_stock stock_Action=QAction(QIcon('calculator.png'), 'Add_Stock', self) stock_Action.setShortcut('Ctrl+S') stock_Action.triggered.connect(qApp.quit) self.toolbar = self.addToolBar('Add_Stock') self.toolbar.addAction(stock_Action) #初始化button def initButton(self): btn = QPushButton('Button', self) btn.setToolTip('This is a <b>QPushButton</b> widget') btn.resize(btn.sizeHint()) btn.move(50, 50) def add_user_clicked(self): sender = self.sender() self.statusBar().showMessage(sender.text() + ' was pressed') #加载内容 self.general_main_content() def general_main_content(self): title = QLabel('Title') author = QLabel('Author') review = QLabel('Review') titleEdit = QLineEdit() authorEdit = QLineEdit() reviewEdit = QTextEdit() grid = QGridLayout() grid.setSpacing(10) grid.addWidget(title, 1, 0) grid.addWidget(titleEdit, 1, 1) grid.addWidget(author, 2, 0) grid.addWidget(authorEdit, 2, 1) grid.addWidget(review, 3, 0) grid.addWidget(reviewEdit, 3, 1, 5, 1) self.setLayout(grid) #点击关闭的事件 ''' def closeEvent(self, event): reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() ''' if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) <file_sep>/untitled/Selenium/米思米/test.py import time import pyautogui from untitled.Selenium import webdriver def prt_content(url): print('GET-->'+url) driver.get(url) time.sleep(5) handles = driver.window_handles driver.switch_to.window(handles[0]) time.sleep(1) pyautogui.typewrite(['tab','tab','esc']) time.sleep(1) driver.find_element_by_xpath("//div[@id='Tab_container']/ul/li/a[@id='Tab_codeList']").click() time.sleep(2) pyautogui.typewrite(['down','down','down','down','down','down','down','down','down','down','down','down','down','down','down','down','down','down','down','down','down']) time.sleep(1) page_num1 = int(driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text) print('当前页面:第' + str(page_num1)+'页') prt_info = driver.find_elements_by_xpath("//div[@id='listContents']/table[@id='ListTable']/tbody/tr/td[@class='model']") print(str(len(prt_info))) for i in range(len(prt_info)): prt_name = prt_info[i].text print(prt_name) next_page(page_num1) def prt_content2(): page_num1=driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text print('当前页面:第' + str(page_num1) + '页') prt_info = driver.find_elements_by_xpath("//div[@id='listContents']/table[@id='ListTable']/tbody/tr/td[@class='model']") print(str(len(prt_info))) for i in range(len(prt_info)): prt_name = prt_info[i].text print(prt_name) if next_pg!="none": next_page(page_num1) #driver.find_element_by_id('detail_codeList_pager_lower_right').click() #page_num1=page_num1+1 #print('自加1='+str(page_num1)) def next_page(page_num): try: #driver.find_element_by_xpath("//li[@id='detail_codeList_pager_upper_right']/a").click() driver.find_element_by_id('detail_codeList_pager_lower_right').click() time.sleep(10) page_num2 = int(driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text) #print('当前页面-->' + str(page_num2)) if page_num2!=page_num: prt_content2() else: time.sleep(10) prt_content2() except : next_pg="none" print("error,已到底页,该类型商品翻页循环结束") if __name__=="__main__": prt_1=[] prt_2=['http://cn.misumi-ec.com/vona2/detail/222004933162/?KWSearch=%E6%AD%A3%E6%B3%B0&Keyword=%E6%AD%A3%E6%B3%B0&searchFlow=results2products'] next_pg="" driver=webdriver.Firefox() #获取产品一级类目 for i in range(len(prt_2)): prt_content(prt_2[i]) print('结束一个三级类目商品的名称获取') <file_sep>/TMALL/西蒙开关-数据获取-2018年3月9日/test1.py import requests import re from bs4 import BeautifulSoup def get_content(url): s=requests.get(url) content=s.content.decode("gbk") #print(content) return content if __name__=="__main__": url="https://simon.tmall.com/" content=get_content(url) #可以通过class="J_TWidget japb abs -_-popup-hidden" 一波提取所有的子类目 soup=BeautifulSoup(content,'html.parser') #div_parts=soup.find_all('div',attrs={'class':re.compile('J_TWidget japb abs -_-popup-hidden')}) #jcb abs apuaH-4gXn junefade jnwz jz div_parts = soup.find_all('div', attrs={'class': re.compile('junefade jnwz jz')}) #print(str(len(div_parts))) for i in range (len(div_parts)): #print(div_parts[i]) a_parts=div_parts[i].find_all('a',attrs={'class':re.compile('juneo')}) for j in range (len(a_parts)): cate_name=a_parts[j].get("href") print(cate_name)<file_sep>/untitled/Selenium/test 4+翻页.py #coding=utf-8 import bs4 import xlsxwriter from untitled.Selenium import webdriver def save_excel(fin_result, file_name): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\%s.xlsx' % file_name) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') row_num = len(fin_result) for i in range(0, row_num): #print('##############') fin_a=fin_result[i] #从50*2的二维数组中,遍历i后获取的每个一维数组 for j in range(0, len(fin_a)): fin_b = fin_result[i][j] #print(fin_b) for k in fin_b: #print(k) tmp.write(i, j, k) tmp.write(i, 0, fin_result[i][0]) driver = webdriver.PhantomJS() driver.get("http://search.mmbao.com") def next_page(source): driver.find_element_by_xpath("//div[@class='pagination pagewidget mt20']/a[contains(text(),'下一页')]").click() def main_search(brand): driver.find_element_by_id('searchBarText').send_keys(brand) driver.find_element_by_id("Button1").click() #print (driver.current_url) source=driver.page_source bs_obj = bs4.BeautifulSoup(source, "html.parser") bs_div_title=bs_obj.findAll('div',attrs={'class':'tit mt5'}) bs_div_price=bs_obj.findAll('div',attrs={'class':'price clearfix'}) page_title= [[] for num in range(len(bs_div_title))] page_price=[[] for num in range(len(bs_div_price))] for i in range (0,len(bs_div_title)): page_title[i].append(bs_div_title[i].text) page_price[i].append(bs_div_price[i].text) page_title[i].append(page_price[i])#将title和price两个一维数组的数据整合成一个二维数组 save_excel(page_title, 'test') tag_name = ['title','price'] brand='正泰' main_search(brand) <file_sep>/MMBAO.COM遍历URL筛选404链接-1.1/获取URL返回状态-V1.2.py import requests import pymysql def get_status(url): try: r = requests.get(url) return r.status_code except requests.exceptions.ConnectTimeout: NETWORK_STATUS = False code='405' return code except requests.exceptions.ConnectionError: code='406' return code except requests.exceptions.InvalidURL: code='' return code def get_cnt(): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select count(href_current) as cnt from url_code where code is null " try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) cnt=str(cnt).replace("((", "").replace(",),)", "") return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def get_url(): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select href_current from url_code where code is null" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_code(url,code): db = pymysql.connect("localhost", "root", "123456", "tmp", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql = "update url_code set code='%s' where href_current='%s' " % (code,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": cnt=get_cnt() print("共计%s条数据"%cnt) urls = get_url() for i in range (len(urls)): url=urls[i][0] print(url) if 'mmbao' in url: if 'jpg' not in url: if 'JPG' not in url: print(url) code = get_status(url) update_code(url, code) else: update_code(url, "jpg") else: update_code(url, "jpg") else: update_code(url, "NONE-MMBAO")<file_sep>/untitled/Selenium/工品汇页面列表爬取V1.0.py #coding=utf-8 #实现功能 #1. 列表数据搜集,翻页,导入excel,MAX页码获取,数组合并 import random import re import time import bs4 import xlsxwriter from selenium import webdriver def list_roll(var,data_main): driver.find_element_by_xpath("//div[@class='saas-paging saas-paging-l J_paging']/a[contains(text(),'末页')]").click() time.sleep(3) source=driver.page_source pages = bs4.BeautifulSoup(source,"html.parser") page=pages.find('div',attrs={'class':'saas-paging saas-paging-l J_paging'}) page_num=pages.findAll('a',attrs={'class':'hover on'}) page_num=re.sub('<[^>]+>','',str(page_num)) page_num=page_num.replace('[','').replace(']','') print('%s 对应共%s页数据' %(var ,page_num)) time_random = random.randint(4, 8) time.sleep(time_random) print('#回到首页,准备开始加载列表') driver.find_element_by_xpath("//div[@class='saas-paging saas-paging-l J_paging']/a[contains(text(),'首页')]").click() time.sleep(time_random) for i in range(1,int(page_num)): source = driver.page_source page_data = main_data(source) data_main=data_main+page_data print('当前第%s页:loading' %(i+1)) driver.find_element_by_xpath("//div[@class='saas-paging saas-paging-l J_paging']/a[contains(text(),'下一页')]").click() # 调用一次mian_data函数,跑出第一页的数据 source = driver.page_source page_data=main_data(source) data_main = data_main + page_data print(page_data) print(data_main) time.sleep(time_random) def main_data(page_source): bs_obj = bs4.BeautifulSoup(page_source, "html.parser") bs_div_title = bs_obj.find('div', attrs={'class': 'J_goodsHtml'}).findAll('li',attrs={'class':'f'}) bs_div_type = bs_obj.find('div', attrs={'class': 'J_goodsHtml'}).findAll('li',attrs={'class':'b'}) bs_div_order = bs_obj.find('div', attrs={'class': 'J_goodsHtml'}).findAll('li', attrs={'class': 'c'}) bs_div_price = bs_obj.find('div', attrs={'class': 'J_goodsHtml'}).findAll('li', attrs={'class': 'd weight'}) page_title = [[] for num in range(len(bs_div_title))] page_type = [[] for num in range(len(bs_div_type))] page_order = [[] for num in range(len(bs_div_order))] page_price = [[] for num in range(len(bs_div_price))] page_data = [] for i in range(0, len(bs_div_title)): page_title[i].append(bs_div_title[i].text) page_type[i].append(bs_div_type[i].text) page_order[i].append(bs_div_order[i].text) page_price[i].append(bs_div_price[i].text) # 将title和price两个一维数组的数据整合成一个二维数组 page_order[i].append(page_price[i]) page_type[i].append(page_order[i]) page_title[i].append(page_type[i]) page_data=page_data+page_title[i] return page_data #需要修改save_excel模块的存储结构 def save_excel(fin_result, file_name): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\%s.xlsx' % file_name) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') row_num = len(fin_result) for i in range(0, row_num): #print('##############') fin_a=fin_result[i] #从50*2的二维数组中,遍历i后获取的每个一维数组 for j in range(0, len(fin_a)): fin_b = fin_result[i][j] #print(fin_b) for k in fin_b: #print(k) tmp.write(i, j, k) tmp.write(i, 0, fin_result[i][0]) #正泰 http://www.vipmro.net/search?brandId=105 if __name__ == '__main__': data_main = [] #数组存放 driver = webdriver.Firefox() driver.get("http://www.vipmro.net/facePrice") time.sleep(3) source = driver.page_source #print(source) pages = bs4.BeautifulSoup(source,"html.parser") #page=pages.findAll('div',attrs={'class':'saas-paging saas-paging-l J_paging'}) #系列筛选条件 #cate_xilie=driver.find_element_by_xpath("//div[@class='face-price-brand-cate-ms']") cate_info=str(pages.find('div',attrs={'class':'face-price-brand-cate-ms'}).findAll('a')) cate_xilie1=re.sub('<[^>]+>','',str(cate_info)) cate_xilie2 = cate_xilie1.replace('[','').replace(']','') cate_xilie=re.split('[,]',cate_xilie2) print(cate_xilie) time.sleep(2) for i in cate_xilie: time_random=random.randint(3,6) var ="//div[@class='face-price-brand-cate-ms']/a[contains(text(),'%s')]" %i.lstrip() print('正在加载链接---->%s <------' %var) driver.find_element_by_xpath(var ).click() time.sleep(time_random) page_source=driver.page_source #选择了类别,然后进行类别下的列表数据爬取 list_roll(var,data_main) #page_title=main_data(page_source) driver.find_element_by_xpath(var).click() time.sleep(time_random) save_excel(data_main) <file_sep>/TMALL/列表页数据获取/列表页销量评价获取-legrand.py import pymysql from bs4 import BeautifulSoup from selenium import webdriver import time def get_useful_data(html): soup=BeautifulSoup(html,'html.parser') prt_divs=soup.find_all('div',attrs={'class':'product item-1111 '}) print("current page have %s records"%str(len(prt_divs))) for prt_div in prt_divs: prt_price=prt_div.find('p',attrs={'class':'productPrice'}).find('em').text #print("prt_price",prt_price) prt_title = prt_div.find('p', attrs={'class': 'productTitle'}).find('a').text #print("prt_title", prt_title) prt_url = prt_div.find('p', attrs={'class': 'productTitle'}).find('a').get('href') #print("prt_url", prt_url) #//detail.tmall.com/item.htm?id=524785657239&skuId=3573590028479&areaId=320200&user_id=923873351&cat_id=50067923&is_b=1&rn=a36346c54fc20f2a4d2dbed860331aa9 prt_id=prt_url.split("&skuId")[1].split('&user_id')[0] #print("prt_id",prt_id) prt_shop = prt_div.find('div', attrs={'class': 'productShop'}).find('a').text #print("prt_shop", prt_shop) prt_sales = prt_div.find('p', attrs={'class': 'productStatus'}).find_all('span')[0].text prt_evaluations = prt_div.find('p', attrs={'class': 'productStatus'}).find_all('span')[1].text #print("prt_sales,prt_evaluations", prt_sales,prt_evaluations) #insert_prt_lists_data(prt_id, prt_url, prt_title, prt_price, prt_shop, prt_sales, prt_evaluations) def insert_prt_lists_data(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations): prt_title=prt_title.replace("\n","") prt_shop=prt_shop.replace("\n","") db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_lists_info (prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) values('%s','%s','%s','%s','%s','%s','%s')" \ %(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def next_page(num): driver.find_element_by_class_name('ui-page-s-next').click() time.sleep(3) try: page_num=driver.find_element_by_class_name("ui-page-s-len").text print(page_num) page_num=page_num.split("/")[0] current_page=num+2 if current_page==page_num: print("success") except: temp = input("tmp") #在处理next_page时,应该会有两种跳转的结果,一种结果是返回登录页面,另一种是网警验证码页面,只能做等待处理 if __name__=="__main__": url="https://list.tmall.com/search_product.htm?q=%C2%DE%B8%F1%C0%CA&type=p&spm=a220m.1000858.a2227oh.d100&from=.list.pc_1_searchbutton" #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) temp = input("tmp") #将html带入到函数进行分析 for i in range(100): html = driver.page_source get_useful_data(html) next_page(i) <file_sep>/JD后台/VC后台/xinan_chuanyu列表匹配.py import pymysql def get_lists(): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 规格,SKU编码,序号 from chuanyu_lists where 物料基本分类='电线、电缆'" # print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def find_exists(sql_info): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = sql_info #print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('-------find_exists--------Error------Message--------:' + str(err)) cursor.close() db.close() def update_data(xuhao, xinghao, sku_bianma, jindu): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update chuanyu_lists set new_SKU编码='%s',new_上线时间='%s',new_SKU规格='%s' where 序号='%s'" %(sku_bianma,jindu,xinghao,xuhao) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------update_data--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": data=get_lists() #print(data) for i in range (len(data)): guige=data[i][0] sku_id=data[i][1] xuhao=data[i][2] print(guige,sku_id,xuhao) guige_parts=guige.replace(" ","") solution = "" slotion_part = "商品型号 like'%" + guige_parts + "%'" solution = solution + " where 采购价!='' and " + slotion_part #print(solution) sql_info="select 商品型号,SKU编码,上传进度 from xinan_jindu " +solution print(sql_info) exist_data=find_exists(sql_info) try: if len(exist_data)==1: xinghao = exist_data[0][0] sku_bianma = exist_data[0][1] jindu = exist_data[0][2] print(xinghao, sku_bianma, jindu) update_data(xuhao, xinghao, sku_bianma, jindu) #update_data(xuhao,xinghao, sku_bianma, jindu) elif len(exist_data)==2: xinghao1 = exist_data[0][0] xinghao2 = exist_data[1][0] xinghao=xinghao1+","+xinghao2 sku_bianma = "" jindu = "" print(xinghao, sku_bianma, jindu) update_data(xuhao, xinghao, sku_bianma, jindu) elif len(exist_data)==3: xinghao1 = exist_data[0][0] xinghao2 = exist_data[1][0] xinghao3 = exist_data[2][0] xinghao=xinghao1+","+xinghao2+","+xinghao3 sku_bianma = "" jindu = "" print(xinghao, sku_bianma, jindu) update_data(xuhao, xinghao, sku_bianma, jindu) except TypeError as e: pass <file_sep>/TMALL/详情页内容解析/test01.py import requests import json import re import html import pymysql import urllib.parse import time,random from bs4 import BeautifulSoup def s(a,b): t=random.randint(a,b) time.sleep(t) def get_content(url): s = requests.get(url) content = s.content.decode('gbk') #print(content) data=re.findall('TShop.Setup[\s\S]+J_SpuMore_Act',content) #print(data) data=data[0].replace("TShop.Setup(\r\n\t \t","").replace("\r\n","").replace("\n","").replace(' );})();</script></div><!-- ruleBanner--> <script id="J_SpuMore_Act',"") #print(data) #完成json的整体取出 return data,content def find_json_info(json_data,content): items = json.loads(json_data) prt_title = items['itemDO']['title'] print("prt_title", prt_title) ############################################################# sellerNickName = items['itemDO']['sellerNickName'] # 解码 sellerNickName = urllib.parse.unquote(sellerNickName) print("sellerNickName", sellerNickName) ############################################################# provience = items['itemDO']['prov'] print("provience", provience) ############################################################# brand_name = items['itemDO']['brand'] brand_name=html.unescape(brand_name) print("brand_name", brand_name) ############################################################# brand_id = items['itemDO']['brandId'] print("brand_id", brand_id) ############################################################# itemId = items['itemDO']['itemId'] spuId = items['itemDO']['spuId'] sellerId=items['rateConfig']['sellerId'] _ksTS='' callback="jsonp253" ajax_url="https://dsr-rate.tmall.com/list_dsr_info.htm?itemId="+itemId s2 = requests.get(ajax_url) content2 = s2.content.decode('gbk') content2=content2.split("(")[-1].split(")")[0] #print(content2) rate_data=json.loads(content2) rate_total=rate_data['dsr']['rateTotal'] print("rate_total",rate_total) ###################################################### # 通过正则,获取pvs_id的集合 try: pvs_img_url = items['propertyPics'] pvs_data = re.findall(';\d+:\d+;', str(pvs_img_url)) print(pvs_data) if len(pvs_data)!=0: # 反过来根据json格式,将pvs_id代入属性名称,反倒是能快点,不用思考正则 spu_data = [] for pvs_id in pvs_data: sku_data = [] img_url = items['propertyPics'][pvs_id] # print(img_url) # sku数据 sku_price = items['valItemInfo']['skuMap'][pvs_id]['price'] sku_id = items['valItemInfo']['skuMap'][pvs_id]['skuId'] sku_stock = items['valItemInfo']['skuMap'][pvs_id]['stock'] # print(pvs_id,sku_price,sku_id,sku_stock) sku_data.append(pvs_id.replace(";", "")) sku_data.append(sku_price) sku_data.append(sku_id) sku_data.append(sku_stock) sku_data.append(img_url[0]) spu_data.append(sku_data) # SPU默认的商品图片 default_img = items['propertyPics']['default'] print("default_img", default_img) img_num = 1 for x in range(len(default_img)): img_name = default_img[x].split("/")[-1] original_url = default_img[x] img_num += 1 insert_img_data(prt_id, "", img_name, original_url, img_num, "spu_img") #获取SKU的名称信息 soup = BeautifulSoup(content, 'html.parser') for i in range(len(pvs_data)): pvs_id=pvs_data[i].replace(";", "") sku_name = soup.find('li', attrs={"data-value": pvs_id}).get('title') #print(sku_name) spu_data[i].append(sku_name) print("spu_data",spu_data) ############################################################# for sku_info in spu_data: price=sku_info[1] sku_id=sku_info[2] sku_stock=sku_info[3] img_url=sku_info[4] img_name=img_url.split('/')[-1] sku_name=sku_info[5] insert_sku_data(sku_id, prt_id, sku_name,price, sku_stock) img_num+=1 insert_img_data(prt_id,sku_id, img_name, img_url, img_num, "sku_img") else: print("单SKU商品") itemId = items['itemDO']['itemId'] reservePrice = items['itemDO']['reservePrice'] quantity = items['itemDO']['quantity'] print("itemId", itemId) print("reservePrice", reservePrice) print("quantity", quantity) insert_sku_data(itemId, prt_id, "",reservePrice, quantity) #单个SKU,图片要通过解析content获得 get_img_info(content) except KeyError as e: print("单SKU商品",e) itemId = items['itemDO']['itemId'] reservePrice = items['itemDO']['reservePrice'] quantity = items['itemDO']['quantity'] print("itemId", itemId) print("reservePrice", reservePrice) print("quantity", quantity) insert_sku_data(itemId, prt_id, "",reservePrice, quantity) get_img_info(content) #存储spu数据 insert_spu_data(prt_id, prt_title, sellerNickName, provience, brand_id, brand_name,rate_total) def get_img_info(content): soup = BeautifulSoup(content, 'html.parser') img_lis=soup.find('ul',attrs={'class':'tb-thumb tm-clear'}).find_all('li') print("默认图片有%s张"%str(len(img_lis))) for i in range (len(img_lis)): img_url=img_lis[i].find('img').get('src') img_url=img_url.replace("_60x60q90.jpg","") img_name=img_url.split("/")[-1] img_num=i+1 insert_img_data(prt_id, "", img_name, img_url, img_num, "spu_img") def insert_spu_data(prt_id,prt_title,sellerNickName,provience,brand_id,brand_name,rate_total): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into simon_spu_info(prt_id,prt_title,sellerNickName,provience,brand_id,brand_name,rate_total)" \ "values('%s','%s','%s','%s','%s','%s','%s')" \ % (prt_id,prt_title,sellerNickName,provience,brand_id,brand_name,rate_total) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_sku_data(sku_id,prt_id,sku_name,price,stock): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into simon_sku_info(sku_id,prt_id,sku_name,price,stock)" \ "values('%s','%s','%s','%s','%s')" \ % (sku_id,prt_id,sku_name,price,stock) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_sku_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_img_data(prt_id,sku_id,img_name,original_url,img_num,img_type): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into simon_prt_img(prt_id,sku_id,img_name,original_url,img_num,img_type)" \ "values('%s','%s','%s','%s','%s','%s')" \ % (prt_id,sku_id,img_name,original_url,img_num,img_type) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_img_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def find_attributes(content): soup=BeautifulSoup(content,'html.parser') ul=soup.find('ul',attrs={'id':'J_AttrUL'}) attr_lis=ul.find_all('li') print("共有%s条属性"%str(len(attr_lis))) for i in range (len(attr_lis)): attribute_info=attr_lis[i].text #通过关键字分类 if "证书编号" in attribute_info: zhengshu_no=attribute_info print(zhengshu_no) insert_attributes(prt_id, zhengshu_no) elif "3C产品型号" in attribute_info: sanc_type=attribute_info print(sanc_type) insert_attributes(prt_id, sanc_type) elif "型号" in attribute_info and "3C" not in attribute_info: prt_type=attribute_info print(prt_type) insert_attributes(prt_id,prt_type ) elif "插座类型" in attribute_info: chazuo_leixing=attribute_info print(chazuo_leixing) insert_attributes(prt_id, chazuo_leixing) elif "插孔类型" in attribute_info: chakong_leixing=attribute_info print(chakong_leixing) insert_attributes(prt_id, chakong_leixing) elif "额定电流" in attribute_info: eding_dianliu=attribute_info print(eding_dianliu) insert_attributes(prt_id, eding_dianliu) elif "颜色" in attribute_info and "分类" not in attribute_info: color=attribute_info print(color) insert_attributes(prt_id,color) def insert_attributes(prt_id,attribute_value ): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into simon_prt_attribute(prt_id,attribute_name)" \ "values('%s','%s')" \ % (prt_id,attribute_value) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_img_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def get_lists(): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_id,prt_url from simon_prt_lists where status=0 " try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('------get_lists---------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": #对从mysql里面获取的详情页url进行解析 url_data=get_lists() print(str(len(url_data))) for i in range (len(url_data)): url=url_data[i][1] prt_id=url.split('id=')[-1].split("&")[0] print(url,prt_id) #url="https://detail.tmall.com/item.htm?id=9363952198&scene=taobao_shop" #url="https://detail.tmall.com/item.htm?id=538218198610&scene=taobao_shop" #prt_id="538218198610" #首先,测试用的这条数据是多SKU的版面样式,后面也需要找一个单SKU的进行测试 json_data,content=get_content(url) find_json_info(json_data,content) find_attributes(content) s(1,4) #httpsDescUrl <file_sep>/untitled/Selenium/西域网/main.py #coding=utf-8 import random import time import bs4 import pymysql from selenium import webdriver def s(): rand=random.randint(2,3) time.sleep(rand) def page_num(url): print(url) driver=webdriver.Firefox() driver.get(url) source=driver.page_source pages=bs4.BeautifulSoup(source,'html.parser') total_page=pages.find('div',attrs={'class':'showPagintion clearfix'}).find('li',attrs={'class':'pg-num-total'}).text driver.quit() return total_page def content(url): driver = webdriver.Firefox() driver.get(url) s() source = driver.page_source pages = bs4.BeautifulSoup(source, 'html.parser') product_content = pages.find('div', attrs={'class': 'showArea listMode'}).findAll('div',attrs={'class':'product'}) count=len(product_content) #count为一页上,商品的个数 print(count) for i in range(0,count): #print(product_content[i]) #商品名称 product_name=product_content[i].find('img') product_name=product_name.attrs['alt'] #print(product_name) PRODUCT_NAME.append(product_name) #品牌,型号,类别 product_li=product_content[i].find('ul',attrs={'class':'product-parameter'}).findAll('li') product_brand=product_li[0].text product_type=product_li[1].text product_cate=product_li[2].text #print(product_brand) PRODUCT_BRAND.append(product_brand) #print(product_type) PRODUCT_TYPE.append(product_type) #print(product_cate) PRODUCT_CATE.append(product_cate) #西域价 product_price=product_content[i].find('span',attrs={'class':'now_money'}).text #print(product_price) PRODUCT_PRICE.append(product_price) #订货号 product_order=product_content[i].find('div',attrs={'class':'order ell'}).findAll('span') product_order=product_order[1].text #print(product_order) PRODUCT_ORDER.append(product_order) mysql_insert(product_name,product_brand,product_type,product_cate,product_price,product_order) driver.quit() def mysql_insert(product_name,product_brand,product_type,product_cate,product_price,product_order): db = pymysql.connect("192.168.180.147","root","123456","test01" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql="insert into Xiyu " \ " (PRODUCT_NAME,PRODUCT_BRAND,PRODUCT_TYPE,PRODUCT_CATE,PRODUCT_PRICE,PRODUCT_ORDER)" \ " values('%s','%s','%s','%s','%s','%s')" \ % (product_name,product_brand,product_type,product_cate,product_price ,product_order) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() print(product_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:'+err) # 关闭数据库连接 db.close() if __name__=='__main__': #定义一系列数组 PRODUCT_NAME=[] PRODUCT_BRAND=[] PRODUCT_TYPE=[] PRODUCT_CATE=[] PRODUCT_PRICE=[] PRODUCT_ORDER=[] para_brand='公牛' url='http://www.ehsy.com/search?k='+para_brand driver=webdriver.Firefox() driver.get(url) s() source=driver.page_source pages = bs4.BeautifulSoup(source, "html.parser") cate_info=pages.find('div',attrs={'class','categoryWrap'}) cate_name=cate_info.findAll('span',attrs={'class','att-val'}) cate_url=cate_info.findAll('a') driver.quit() for i in range (0,len(cate_name)): #print(cate_name[i].text) #print(cate_url[i].get('href')) print(cate_name[i].text) cate_url_link='http://www.ehsy.com/'+cate_url[i].get('href') total_page=page_num(cate_url_link) total_page=total_page.replace('共','').replace('页','') print('--------------共'+total_page+'页----------------') for j in range(0,int(total_page)): print('http://www.ehsy.com/' + cate_url[i].get('href')+'%3Fp%3D1&p='+str(j+1)) #driver = webdriver.Firefox() #driver.get('http://www.ehsy.com/' + cate_url[i].get('href')+'?p'+(j+1)) list_url='http://www.ehsy.com/' + cate_url[i].get('href')+'%3Fp%3D1&p='+str(j+1) product_content=content(list_url) <file_sep>/JD后台/优信VOP/优信VOP订单详情获取.py import pymysql import time import random import logging import pyperclip from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.select import Select logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #判断是否登陆成功 go_name = input("Go?") print(go_name) driver.get("https://vcp.jd.com/sub_dropship/orderManage/initListPage") self.s(2, 3) driver.find_element_by_id("queryOrderTab").click() self.s(2,2) #获取mysql表中的待导入数据 data=self.get_lists() for i in range (len(data)): #哪里需要填写数据,再进行赋值 order_id=data[i][0] #order_id="77116386852" driver.find_element_by_id("queryOrder_orderId").clear() driver.find_element_by_id("queryOrder_orderId").send_keys(order_id) self.s(1,1) driver.find_element_by_id("btnQuery").click() self.s(2,3) #查询出对应的数据, #detailContent driver.find_elements_by_xpath("//div[@class='div_margin_top']/a")[-1].click() self.s(1, 2) while 1==1: try: detail_info=driver.find_element_by_id("detailWin") break except Exception as e: self.s(1,1) order_status=driver.find_element_by_id("stateName").text print(order_status) order_content=driver.find_elements_by_xpath("//div[@class='mb20 tb_msg']/table/tbody/tr/td")[-1].text print(order_content) #下单人信息 customer_info=driver.find_elements_by_xpath("//div[@class='mb20']/table/tbody/tr/td/table/tbody/tr") account="" name="" address="" phone_number="" email="" for x in range(len(customer_info)): customer_text=customer_info[x].text print(customer_text) if "下单账号" in customer_text: account=customer_text if "收货人姓名" in customer_text: name=customer_text if "收货地址" in customer_text: address=customer_text if "手机号码" in customer_text: phone_number=customer_text if "电子邮件" in customer_text: email=customer_text self.insert_data(order_id,order_status,order_content,account,name,address,phone_number,email) driver.find_element_by_xpath("//button[@class='pui-button ui-widget ui-state-default ui-corner-all pui-button-text-icon-left']").click() self.update_status(order_id) self.s(2,3) def insert_data(self,order_id,order_status,order_content,account,name,address,phone_number,email): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into order_info (order_id,order_status,order_content,account,name,address,phone_number,email) values('%s','%s','%s','%s','%s','%s','%s','%s')" %(order_id,order_status,order_content,account,name,address,phone_number,email) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(self,order_id): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update 订单综合查询导出 set status=1 where 客户订单号='%s'" %order_id print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_lists(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 客户订单号 from 订单综合查询导出 where status=0 group by 客户订单号 " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/JD后台/VC后台/图片详情内容修改-驳回.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) find_lists=driver.find_elements_by_xpath("//table[@class='grid']/tbody/tr") print("current page have %s records " %(str(len(find_lists)))) prt_codes = [ '5054498','5054500','5054460','5054504','5054452', '5054468','5054470','5050720','6448789','5307564','4555936','4496497','4363477','4332419','4848859'] for i in range (len(prt_codes)): driver.find_element_by_id('wareId').send_keys(prt_codes[i]) self.s(2,4) driver.find_element_by_css_selector('.btn.btn-primary').click() self.s(2,4) prt_status_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_state']/a" prt_status = driver.find_element_by_xpath(prt_status_path).text print(prt_status) if "产品驳回" in prt_status: btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_applyId']/div/button" driver.find_elements_by_xpath(btn_down_path)[1].click() btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_applyId']/div/ul/li/a" driver.find_elements_by_xpath(btn_down_path)[1].click() self.s(3, 5) driver.find_element_by_id('cid3Submit').click() self.s(3, 5) driver.find_element_by_id('auditedSubmit').click() self.s(3, 6) driver.find_element_by_id('categoryAttrSubmitNew').click() self.s(3, 6) pc_text = driver.find_element_by_id("introHtml").text print(pc_text) pc_text = pc_text.replace( ' <img src="//img10.360buyimg.com/imgzone/jfs/t4666/154/4572725365/182310/90510460/590fcc0bNd65edb82.jpg" /> \n <br /> ',"") print(pc_text) driver.find_element_by_id("introHtml").clear() driver.find_element_by_id("introHtml").send_keys(pc_text) self.s(1,2) # 进入商品介绍代码页面 driver.find_element_by_id('mobile_intro').click() driver.find_element_by_xpath("//a[@href='#mobile_html']").click() self.s(3, 6) app_text = driver.find_element_by_id("introMobile").text # print(app_text) app_text = app_text.replace( ' <img src="//img10.360buyimg.com/imgzone/jfs/t7690/142/2025175497/186557/1c0c0238/59a69effN30378da0.jpg" /> \n <br /> ', "") app_text = app_text.replace( ' <img src="//img10.360buyimg.com/imgzone/jfs/t4627/362/4630065428/186557/1c0c0238/59111c67Nf4322e9e.jpg" /> ',"") print(app_text) driver.find_element_by_id("introMobile").clear() driver.find_element_by_id("introMobile").send_keys(app_text) ss = input("Go?") print(ss) driver.find_element_by_id('createApply').click() self.s(3, 6) driver.find_element_by_id('toApplyList').click() self.s(3, 6) else: pass if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/工品汇/正泰.NET/工品汇2.1-main.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver from selenium.common.exceptions import NoSuchElementException def s(a,b): t=random.randint(a,b) time.sleep(t) def company_info(): company_name="正泰" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() s(3,5) def get_main_data_bak(company_name,url): J_searchLists=driver.find_elements_by_xpath("//div[@class='J_searchList']/ul") for Searchlist in J_searchLists: img_url=Searchlist.find_element_by_xpath("./li[@class='a']/a/img").get_attribute('src') prt_name=Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").text prt_url =Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").get_attribute('href') prt_id = prt_url[prt_url.index("product/") + 8:100] prt_type=Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[0].text order = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[1].text try: price=Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='a']").text except: price="" try: market_price = Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='b']").text except: market_price="" stock=Searchlist.find_element_by_xpath("./li[@class='f']").text print(img_url,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock) insert_data1(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock,url) def get_main_data(company_name,table_id): page_num=1 while 1==1: J_searchLists = driver.find_elements_by_xpath("//div[@class='J_searchList']/ul") for Searchlist in J_searchLists: img_url = Searchlist.find_element_by_xpath("./li[@class='a']/a/img").get_attribute('src') prt_name = Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").text prt_url = Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").get_attribute('href') prt_id = prt_url[prt_url.index("product/") + 8:100] prt_type = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[0].text order = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[1].text try: price = Searchlist.find_element_by_xpath( "./li[@class='e lh tl']/div[@class='search-active']/span[@class='a']").text except: price = "" try: market_price = Searchlist.find_element_by_xpath( "./li[@class='e lh tl']/div[@class='search-active']/span[@class='b']").text except: market_price = "" stock = Searchlist.find_element_by_xpath("./li[@class='f']").text #print(img_url, prt_id, prt_name, prt_url, prt_type, order, price, market_price, stock) insert_data1(company_name, prt_id, prt_name, prt_url, prt_type, order, price, market_price, stock, table_id) try: page_num += 1 print("翻页-%s"%str(page_num)) driver.find_element_by_xpath( "//div[@class='saas-paging J_paging']/a[@class='J_page_turn'][@page-id='" + str( page_num) + "']").click() s(5,7) except NoSuchElementException as e: print(e) break def insert_data1(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock,table_id): #company_name=company_info() db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into vipmro_net_data (company_name,prt_id,prt_name,prt_url,prt_type,order_,price,market_price,stock,cate_id)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock,table_id) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def next_page(j): s(3, 5) xpath_data="//div[@class='saas-paging J_paging']/a[@class='J_page_turn'][@page-id='"+str(j+2)+"']" print(xpath_data) driver.find_element_by_xpath(xpath_data).click() s(3, 6) def get_url_status(): #company_name=company_info() db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select table_id,case when cate_2_url='' then cate_1_url else cate_2_url end as url,company_name from vipmro_net_url where status=0 order by table_id " try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(table_id): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_net_url set status=1 where table_id='%s' " \ % (table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def find_series(num): series_names=[] series_urls=[] series_tmp= driver.find_elements_by_css_selector('.b.p-left10.no-border') series_info_div = driver.find_elements_by_css_selector('.b.p-left10.no-border')[num] series_info=series_info_div.find_elements_by_tag_name('a') print("%s个分支"%str(len(series_info))) for i in range(len(series_info)): series_name=series_info[i].text series_url=series_info[i].get_attribute('href') #print(series_name,series_url) series_names.append(series_name) series_urls.append(series_url) return series_names,series_urls if __name__=="__main__": browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() url = "http://www.vipmro.net/login" driver.get(url) s(3, 5) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) #完成登录 #点击一下搜索按钮,使页面正确加载url #driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() driver.get("http://www.vipmro.net/search?keyword=%25E6%2596%25BD%25E8%2580%2590%25E5%25BE%25B7") s(3, 5) driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() s(3, 5) data = get_url_status() for i in range (len(data)): table_id=data[i][0] url=data[i][1] company_name=data[i][2] #url=str(url_t).replace("(('","").replace("',),)","") print(company_name,url) #url=u'http://www.vipmro.net/search?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&categoryId=50101811' driver.get(url) s(4, 6) #先判断一共多少页 page_num=driver.find_element_by_css_selector('.J_page_sum.t_num').text print("##################当前类目共%s页数据"%page_num) if page_num=='15': #拆到系列这一级 print("进行第一级系列的细化") series_names, series_urls=find_series(1) for x in range(len(series_names)): print("分支",series_names[x],series_urls[x]) driver.get(series_urls[x]) s(3,5) page_num2 = driver.find_element_by_css_selector('.J_page_sum.t_num').text print("当前类目共%s页数据" % page_num2) if page_num2 == '15': # 拆到系列这一级 print("进行第二级的细化") series_names2, series_urls2 = find_series(2) for y in range(len(series_names2)): print("分支", series_names2[y], series_urls2[y]) driver.get(series_urls2[y]) s(5, 8) page_num3 = driver.find_element_by_css_selector('.J_page_sum.t_num').text print("当前类目共%s页数据" % page_num3) if page_num3 == '15': print("进行第三级的细化") series_names3, series_urls3 = find_series(3) for z in range (len(series_names3)): print("分支", series_names3[z], series_urls3[z]) driver.get(series_urls3[z]) s(3, 5) get_main_data(company_name, table_id) else: get_main_data(company_name, table_id) else: get_main_data(company_name, table_id) else: get_main_data(company_name, table_id) #update_status_to_run_log(table_id) <file_sep>/ZYDMALL/zydmall产品价格调整监控/oracle数据同步到mysql.py import cx_Oracle import pymysql def find_sku_data(): #db = cx_Oracle.connect('mmbao2_bi/<EMAIL>@<EMAIL>:21252/mmbao2b2c') db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@192.168.3.11:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT a.ID,A.PRT_ID,A.OLD_PRICE,A.SKU_TITLE,A.PO_NUMBER,A.WEIGHT,B.PRT_TITLE,a.dqs_prt_sku_id,b.series FROM mmbao2.t_prt_sku a "\ "LEFT JOIN mmbao2.t_prt_entity b ON a.prt_id=b.id "\ "WHERE b.shop_id in ('1781956') "\ "AND b.is_delete=0 AND b.is_sale=1 AND b.is_use=1 "\ "AND a.is_delete=0 " # and create_date>to_date('%s','yy/MM/dd') # 因为还得分为新增和更新 #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def save_oracle_data(sku_id,prt_id,old_price,sku_title,po_number,weight,prt_title,brand_name,dqs_prt_sku_id,series): db = pymysql.connect("localhost", "root", "123456", "mmbao") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into t_prt_sku (sku_id,prt_id,old_price,sku_title,po_number,weight,prt_title,brand_name,dqs_prt_sku_id,series) "\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ %(sku_id,prt_id,old_price,sku_title,po_number,weight,prt_title,brand_name,dqs_prt_sku_id,series) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------save_oracle_data--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #将Oracle数据导出到mysql,按品牌 brand_name="德力西" data=find_sku_data() print(len(data)) #将数据整理录入到mysql中 for i in range (len(data)): sku_id=data[i][0] prt_id=data[i][1] old_price=data[i][2] sku_title=data[i][3] po_number=data[i][4] weight=data[i][5] prt_title=data[i][6] dqs_prt_sku_id=data[i][7] series=data[i][8] save_oracle_data(sku_id,prt_id,old_price,sku_title,po_number,weight,prt_title,brand_name,dqs_prt_sku_id,series) percent=round(float(i/len(data))*100,2) #print(str(percent)) <file_sep>/JD/前台审核库存信息.py import pymysql import requests from bs4 import BeautifulSoup from selenium import webdriver def get_urls(): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select table_id,prt_id,prt_url from stock_info " try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('------get_lists---------Error------Message--------:' + str(err)) db.close() cursor.close() def update_status(status,table_id): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update stock_info set status='%s' where table_id='%s'" %(status,table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------get_lists---------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": browser = "Chrome" if browser == "Chrome": driver = webdriver.Chrome() else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() urls=get_urls() for i in range(len(urls)): table_id=urls[i][0] prt_url=urls[i][2] driver.get(prt_url) content = driver.page_source #print(content) #使用soup分析一波 soup=BeautifulSoup(content,'html.parser') #<div id="store-prompt" class="store-prompt"><strong>无货</strong>,此商品暂时售完</div> #<div id="store-prompt" class="store-prompt"><strong>有货</strong></div> #<div class="itemover-tip">该商品已下柜,欢迎挑选其他商品!</div> try: sold_status = soup.find('div', attrs={'class': 'itemover-tip'}).text print(sold_status) if "下柜" in sold_status: status = "下柜" else: status = "其他2" except AttributeError as e: try: sold_status = soup.find('div', attrs={'id': 'store-prompt'}).text print(sold_status) if "暂时售完" in sold_status: status = "暂时售完" elif "有货" in sold_status: status = "有货" else: status = "其他1" except AttributeError as e: status = "其他3" update_status(status,table_id) <file_sep>/untitled/Selenium/dq123/产品目录获取.py import time from selenium import webdriver if __name__=="__main__": driver=webdriver.Firefox() driver.get("http://www.dq123.com/price/index.php?fid=3&sid=263") time.sleep(8) tab=driver.find_element_by_id("showhidediv1").click() time.sleep(8) for i in range(0,66): #共65 cate1_id="dirlist"+str(i) cate_1=driver.find_element_by_id(str(cate1_id)) cate1_name=cate_1.find_element_by_xpath("a/span").text print(str(i)) print(cate1_name) for i in range(0, 66): # 共65 try: cate2_id = "items" + str(i) #cate_2=driver.find_element_by_id(cate2_id) #cate2_name=driver.find_elements_by_xpath("//dd[@id='"+str(cate2_id)+"']/div/ul/li/a[@class='ccnode']") cate2_name=driver.find_elements_by_xpath("//a[@class='ccnode']") #print(cate2_name) for j in range(len(cate2_name)): cate2_name1=cate2_name[j].find_element_by_xpath("span") print() print(str(i)+" "+cate2_name1.text) except: print('没有二级类目') <file_sep>/MMBAO/片区划分.py import pymysql def find_company_info(): db = pymysql.connect("localhost", "root", "123456", "tianyancha") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 序号,省,市 from company_basic_info "\ "where 企业名称 not in (select cust_name from company_info_ebs group by cust_name) "\ "and 统一社会信用代码 not in (select CUST_NUMBER from company_info_ebs group by CUST_NUMBER) " try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def find_pianqu(province,city): db = pymysql.connect("localhost", "root", "123456", "tianyancha") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") if province=="江苏省": sql = "select 片区领导,片区名称 from leader_province where 对应省份='%s' and 对应地级='%s' " %(province,city) else: sql = "select 片区领导,片区名称 from leader_province where 对应省份='%s' " %province print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_link(table_id,leader,pianqu_name): db = pymysql.connect("localhost", "root", "<PASSWORD>", "<PASSWORD>") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into pianqu_link (table_id,leader,pianqu_name) values('%s','%s','%s') " %(table_id,leader,pianqu_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": data=find_company_info() for i in range(len(data)): table_id=data[i][0] province=data[i][1] city=data[i][2] print(table_id,province,city) pianqu_data=find_pianqu(province,city) leader=pianqu_data[0][0] pianqu_name=pianqu_data[0][1] print(leader,pianqu_name) insert_link(table_id,leader,pianqu_name) <file_sep>/ZYDMALL/zydmall_德力西/筛选出本次需要提供给技术的图片.py #因为数据量并不多,所以直接遍历判断是新增还是复制吧 #抄当时vipmro里面的获取图片的函数 #尽量将一些经常使用的函数打包成库的方法使用,省的老是复制粘贴 #将数据表中,所有is_repeat为1的 import os import urllib.request import pymysql import sys import shutil import time #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(product_id,img_url, img_name): if (len(img_url) != 0): fileName = img_name file_path=u"Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+product_id try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) status=1 except: print("这图我没法下载") status=2 return status #复制图片 def copy_Img(prt_id_exist,prt_id,img_name): #暂时不加异常捕捉机制,试运行 src="Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id_exist+"\\"+img_name dst="Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id+"\\"+img_name print("waiting for "+src+" =>=>=>=>=>=> "+dst) file_path = u"Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\" + prt_id createFileWithFileName(file_path, img_name) shutil.copyfile(src,dst) print("复制成功") def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,table_id,original_url from prt_img_info where download_status=2 and is_use=1 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def is_existed_files(prt_id,img_name): path="D:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id file="D:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id+"\\"+img_name state1=os.path.exists(path) print("已找到目录"+str(state1)) state2=os.path.isfile(file) print("已找到文件"+str(state2)) if state1 is True: if state2 is True: state=1 return state state=0 return state def is_existed(table_id,img_name,url): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,original_url from prt_img_info where download_status=2 and table_id <>'%s' and img_name='%s' and original_url='%s' limit 1" %(table_id,img_name,url) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_state(prt_id,url,status): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update prt_img_info set download_status='%d' where prt_id='%s' and original_url='%s' and is_use=1" %(status,prt_id,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__ == "__main__": # 从数据表获取prt_id,img_url,img_name for i in range(4000): data = get_prt_data() prt_id = data[0][0] img_name = data[0][1] table_id = data[0][2] url = data[0][3] print(table_id, prt_id, img_name, url) file_state = is_existed_files(prt_id, img_name) # 判断是否已经存在相同的图片,进行复制,而不是重新下载 ''' prt_id_exist = data[0][0] print("已存在相同的数据prt_id=%s" % prt_id_exist) copy_Img(prt_id_exist, prt_id, img_name) # 返回状态更新,以及path更新 state = 2 #is_repeat = 1 print("-------------------------------------") #返回path路径,更新到数据表字段 ''' # print(file_state) if file_state == 1: state = 2 update_state(prt_id, url, state) else: data = is_existed(table_id, img_name, url) print(data) if data == "()": state = 3 update_state(prt_id, url, state) else: prt_id_exist = data[0][0] print("已存在相同的数据prt_id=%s" % prt_id_exist) copy_Img(prt_id_exist, prt_id, img_name) state = 2 update_state(prt_id, url, state) print("------------------") time.sleep(1)<file_sep>/找电缆EXCEL处理/判断当前excel格式.py # 打开一个excel import xlrd import os import pymysql # 从excel中获取url的列表数据 def get_data_from_excel(excel_name): # excel_name=r"D:\BI\找电缆\2017年12月红本出厂价《产品价格目录》\1712出厂价/201712 架空线出厂价-国标.xls" #print(excel_name) data=xlrd.open_workbook(excel_name) #打开excel # 遍历所有的sheet # print("当前excel共有%s个SHEET" % str(len(data.sheets()))) for i in range (len(data.sheets())): sheetName = data.sheet_names()[i] #print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[i] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] # print(sheetName) try: first_row = table.row_values(0) second_row = table.row_values(1) #print(first_row) len_first_row=len(first_row) if len_first_row==2: # ['型号规格', '出厂价'] # ['规格型号', '出厂价'] # print(second_row) # second有两种情况 if second_row[0]=="": # ['', '元/KM'] for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] exw_price = ss[1] print(type_specification, exw_price) full_text=excel_name+","+sheetName+","+type_specification insert_new_details(full_text,exw_price) else: # ['3*10/3*6', 376.79488600421473] for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] exw_price = ss[1] print(type_specification, exw_price) full_text = excel_name + "," + sheetName + "," + type_specification insert_new_details(full_text, exw_price) elif len_first_row==3: if first_row[1]=="出厂价": #print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] zrc = ss[1] zrb=ss[2] print(type_specification, zrc, zrb) x_type=["zrc","zrb"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification+ "," + x_type[x] insert_new_details(full_text, exw_price) elif first_row[1]=="普通": # print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] zrc = ss[1] zrb=ss[2] print(type_specification, zrc, zrb) x_type=["zrc","zrb"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification+ "," + x_type[x] insert_new_details(full_text, exw_price) elif len_first_row==4: if first_row[1] == "出厂价": #print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] zrc = ss[1] zrb=ss[2] zra = ss[3] print(type_specification, zrc, zrb, zra) x_type=["zrc","zrb","zra"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification+ "," + x_type[x] insert_new_details(full_text, exw_price) elif first_row[1]=="型号": #print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 wuliao_num = ss[0] type = ss[1] specification=ss[2] exw_price = ss[3] if wuliao_num!="物料编码" and wuliao_num!="": print(wuliao_num, type, specification, exw_price) full_text = excel_name + "," + sheetName + "," + wuliao_num+ "," + type+ "," + specification insert_new_details(full_text, exw_price) pass elif len_first_row==5: if first_row[1] == "出厂价": #print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb=ss[3] zra = ss[4] if type_specification!="": print(type_specification, pt,zrc, zrb, zra) x_type = ["pt","zrc", "zrb", "zra"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(full_text, ss[x+1]) elif first_row[1]=="普通": #print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb = ss[3] zra = ss[4] print(type_specification, zrc, zrb, zra) x_type = ["pt", "zrc", "zrb", "zra"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(full_text, ss[x + 1]) elif len_first_row==6: if first_row[1] == "出厂价": #print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] exw_price = ss[1] print(type_specification, exw_price) full_text = excel_name + "," + sheetName + "," + type_specification insert_new_details(full_text, exw_price) elif first_row[1]=="": #print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] type2=ss[1] pt = ss[2] zrc = ss[3] zrb=ss[4] zra = ss[5] print(type_specification,type2,pt, zrc, zrb, zra) x_type = ["pt", "zrc", "zrb", "zra"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(full_text, ss[x + 2]) #type2不入 elif len_first_row == 8: #print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb = ss[3] zra = ss[4] essence_pt= ss[5] essence_zc = ss[6] pt_balance =ss[7] essence_balance=ss[8] essence_sale_price=ss[9] zc_balance=ss[10] print(type_specification, pt, zrc, zrb, zra, essence_pt, essence_zc, pt_balance, essence_balance, essence_sale_price, zc_balance) x_type = ["pt", "zrc", "zrb", "zra","essence_pt", "essence_zc", "pt_balance", "essence_balance", "essence_sale_price", "zc_balance"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(full_text, exw_price) elif len_first_row == 11: #print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb = ss[3] zra = ss[4] essence_pt= ss[5] essence_zc = ss[6] zc_balance =ss[7] print(type_specification, pt, zrc, zrb, zra, essence_pt, essence_zc, zc_balance) x_type = ["pt", "zrc", "zrb", "zra", "essence_pt", "essence_zc", "pt_balance"] for x in range(len(x_type)): full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(full_text, exw_price) # type2不入 except IndexError as e: print(e) ''' # 从excel中获取url的列表数据 def get_data_from_excel_bak(excel_name): # excel_name=r"D:\BI\找电缆\2017年12月红本出厂价《产品价格目录》\1712出厂价/201712 架空线出厂价-国标.xls" print(excel_name) data=xlrd.open_workbook(excel_name) #打开excel # 遍历所有的sheet print("当前excel共有%s个SHEET" % str(len(data.sheets()))) for i in range (len(data.sheets())): sheetName = data.sheet_names()[i] print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[i] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] # print(sheetName) try: first_row = table.row_values(0) print(first_row) if len(first_row) == 2: second_row = table.row_values(0) print(second_row) print("不含阻燃等级的型号") type_name = "Type1" rows = len(first_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] exw_price = ss[1] # print(type_specification, exw_price) else: if len(first_row) == 4: second_row = table.row_values(1) if len(second_row) == 4 and second_row[1] == "ZRC" and second_row[2] == "ZRB" and second_row[3] == "ZRA": print("含阻燃等级的型号、不含普通") type_name = "Type2" rows = len(first_row) # 需要额外判断第二行的数据 for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] ZRC = ss[1] ZRB = ss[2] ZRA = ss[3] # print(type_specification, ZRC, ZRB, ZRA) else: print("未知-含阻燃等级的型号、不含普通") else: if len(first_row) == 5: if first_row[1] == "普通" \ and "C" in first_row[2] and "B" in first_row[3] and "A" in first_row[4]: print("含阻燃等级的型号、含普通") type_name = "Type3" rows = len(first_row) # 需要额外判断第二行的数据 for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] PT = ss[1] ZRC = ss[2] ZRB = ss[3] ZRA = ss[4] # print(type_specification, PT, ZRC, ZRB, ZRA) else: second_row = table.row_values(1) print(second_row) if len(second_row) == 5 and second_row[1] == "普通" \ and "C" in second_row[2] and "B" in second_row[3] and "A" in second_row[4]: print("含阻燃等级的型号、含普通") type_name = "Type3" rows = len(first_row) # 需要额外判断第二行的数据 for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] PT = ss[1] ZRC = ss[2] ZRB = ss[3] ZRA = ss[4] # print(type_specification, PT, ZRC, ZRB, ZRA) else: print("未知-含阻燃等级的型号、不含普通") else: if len(first_row) == 3: if first_row[1] == "普通" \ and "C" in first_row[2]: print("含阻燃等级的型号、含普通、ZRC") type_name = "Type3" rows = len(first_row) # 需要额外判断第二行的数据 for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] PT = ss[1] ZRC = ss[2] else: pass else: print("未知") type_name = "Type4" rows = len(first_row) except IndexError as e: print(e) ''' #读取所有文件夹中的xls文件 def read_xls(path, type2): #遍历路径文件夹 for file in os.walk(path): for each_list in file[2]: file_path=file[0]+"/"+each_list #os.walk()函数返回三个参数:路径,子文件夹,路径下的文件,利用字符串拼接file[0]和file[2]得到文件的路径 name.append(file_path) #储存结果集 def insert_new_details(full_text,price): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into zhaodianlan_price_update (full_text,price) values('%s','%s') "%(full_text,price) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__ == "__main__": xpath = r"D:\BI\找电缆\12月源数据" xtype = "xls" name = [] read_xls(xpath, xtype) print("%s个文件"%str(len(name))) for i in range (len(name)): excel_name = name[i] get_data_from_excel(excel_name) <file_sep>/OA_FEGROUP/test-后台登录OA获取日报状态.py import requests import base64 from bs4 import BeautifulSoup from utils import AliyunSMS import pymysql def get_content(url): s = requests.get(url,headers=headers) content = s.content.decode('gbk') print(content) cookie = s.cookies #print(cookie) return content,cookie def find_data_from_content(content): soup=BeautifulSoup(content,'html.parser') liNoSubmit=soup.find('li',attrs={'id':'liNoSubmit'}).text #print(liNoSubmit.replace(" ","")) liNo=liNoSubmit.replace("未提交(","").replace(")","") return liNo def find_detail(submit_content): soup=BeautifulSoup(submit_content,'html.parser') type=[] date=[] tbody_trs=soup.find('tbody',attrs={'id':'lpEffSubmit_TBody'}).find_all('tr',attrs={'class':'evenLine'}) print("%s条未提交的工作报表"%str(len(tbody_trs))) for i in range(len(tbody_trs)): tds=tbody_trs[i].find_all('td') report_type=tds[3].text report_date=tds[5].text print(report_type,report_date) type.append(report_type) date.append(report_date) return type,date if __name__=="__main__": headers = { "Host" : "oa.fegroup.cn:8090", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer" : "http://oa.fegroup.cn:8090/c6/jhsoft.web.ydmh/myindex.aspx?moduleid=01400030", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" } # post发送的数据 #从mysql获取oa登录信息 loginCode=base64.b64encode("066460".encode(encoding='utf-8')) pwd=base64.b64encode("<PASSWORD>".encode(encoding='utf-8')) loginCode=str(loginCode).split("'")[1] pwd=str(pwd).split("'")[1] hidEpsKeyCode='' #print(loginCode,pwd) url=u'http://oa.fegroup.cn:8090/c6/Jhsoft.Web.login/AjaxForLogin.aspx?type=login&loginCode=%s&pwd=%s&hidEpsKeyCode=%s' %(loginCode,pwd,hidEpsKeyCode) #print(url) content,cookie=get_content(url) report_url="http://oa.fegroup.cn:8090/c6/JHSoft.web.Aging/ReportMG.aspx" result=requests.get(report_url,cookies=cookie) content=result.content.decode('gbk') liNo=find_data_from_content(content) #新增功能,获取哪份日报未提交 report_detail_url="http://oa.fegroup.cn:8090/c6/JHSoft.web.Aging/ReportSubmit.aspx" submit_result=requests.get(report_detail_url,cookies=cookie,headers=headers) submit_content=submit_result.content.decode('gbk') #print(submit_content) type, date=find_detail(submit_content) #暂时不做处理,如果有多条未提交的 report_type="" report_date="" for x in range(len(type)): report_type=type[x] report_date=date[x] if report_type=="工作日志": break if report_type!="": print(report_type,report_date) <file_sep>/untitled/Selenium/工品汇/工品汇2.1-普通层级/工品汇2.1-查看总的数据总数.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver def company_info(): company_name="德力西" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) def get_url_status(): company_name=company_info() db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select case when cate_2_url='' then cate_1_url else cate_2_url end as url from vipmro_url where status=0 and company_name='"+company_name+"' order by table_id limit 1 " try: execute=cursor.execute(sql) category_url=cursor.fetchmany(execute) return category_url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(url): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_url set status=1 where cate_2_url='%s' or cate_1_url='%s' " \ % (url,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def get_cnt_data(): cnt=driver.find_element_by_css_selector('.J_page_sum.t_num').text print(int(cnt)*10) if __name__=="__main__": driver=webdriver.Firefox() url = "http://www.vipmro.com/search?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&brandId=104" driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) #完成登录 #点击一下搜索按钮,使页面正确加载url driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() time.sleep(10) for i in range (200): url_t=get_url_status() url=str(url_t).replace("(('","").replace("',),)","") #print(url) driver.get(url) time.sleep(10) get_cnt_data() update_status_to_run_log(url) <file_sep>/TMALL/西门子-开关插座/legrand-获取天猫详情页数据.py import pymysql from selenium import webdriver import time from bs4 import BeautifulSoup import random def s(a,b): s_time=random.randint(a,b) time.sleep(s_time) def insert_data_to_prt_info(prt_id, prt_url, prt_name,small_price,main_price,prt_type, prt_item_id,prt_color,prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing): db = pymysql.connect("localhost", "root", "123456", "tmall_semens", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into prt_info (prt_id, prt_url, prt_name,small_price,main_price,prt_type, prt_item_id,prt_color,prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(prt_id, prt_url, prt_name,small_price,main_price,prt_type, prt_item_id,prt_color,prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_data_to_prt_info-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_data_to_prt_desc(prt_id,sku_id,prt_desc): db = pymysql.connect("localhost", "root", "123456", "tmall_semens", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into prt_desc (prt_id,sku_id,prt_desc) values('%s','%s','%s')" %(prt_id,sku_id,prt_desc) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_data_to_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_data_to_prt_img(prt_id, img_url,img_type): db = pymysql.connect("localhost", "root", "123456", "tmall_semens", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into prt_img (prt_id,img_url,img_type) values('%s','%s','%s')" %(prt_id,img_url,img_type) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_data_to_prt_img-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_prt_lists(): db = pymysql.connect("localhost", "root", "123456", "tmall_semens", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,url from prt_lists where status=0 " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_prt_lists-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_html(prt_id,prt_url): driver.get(prt_url) #等待页面相应完成 try: color_type=driver.find_elements_by_xpath("//ul[contains(@class,'J_TSaleProp')]/li") print("%s条SKU数据" % str(len(color_type))) if len(color_type)==0: sku_id = prt_id s(10, 16) sku_name = "" print("they don't have sku") html = driver.page_source status = find_useful_info(sku_id, sku_name, html) return status else: tmp_status=1 for i in range(len(color_type)): sku_name = color_type[i].get_attribute('title') sku_id = color_type[i].get_attribute('data-value') print(sku_name) color_type[i].click() s(10,13) html = driver.page_source status=find_useful_info(sku_id, sku_name, html) tmp_status=tmp_status*status return tmp_status except: print("error in get_html") status=2 return status def find_useful_info(sku_id,sku_name,html): try: soup = BeautifulSoup(html, 'html.parser') # 名称 prt_title = soup.find('div', attrs={'class': 'tb-detail-hd'}).find('h1').get_text() print("prt_title", prt_title) # 价格 face_price = soup.find('dl', attrs={'id': 'J_StrPriceModBox'}).find('span', attrs={'class': 'tm-price'}).get_text() market_price = soup.find('div', attrs={'class': 'tm-promo-price'}).find('span', attrs={'class': 'tm-price'}).get_text() print("face_price", face_price, "market_price", market_price) # 属性 attr_lis = soup.find('ul', attrs={'id': 'J_AttrUL'}).find_all('li') print("共有%s条属性" % str(len(attr_lis))) brand_name = "" type_name = "" prt_type = "" color_type = "" other_name = "" for i in range(len(attr_lis)): tmp_value = attr_lis[i].get_text() if "品牌" in tmp_value: brand_name = tmp_value if "型号" in tmp_value: type_name = tmp_value if "产品类型" in tmp_value: prt_type = tmp_value if "颜色" in tmp_value: color_type = tmp_value if "产品名称" in tmp_value: other_name = tmp_value print(brand_name,type_name,prt_type,other_name) # 详情内容 img_desc_data = [] prt_desc = soup.find('div', attrs={'class': 'content ke-post'}) #print(prt_desc) try: img_desc_infos = prt_desc.find_all('img', attrs={'align': 'absmiddle'}) for j in range(len(img_desc_infos)): img_desc_info = img_desc_infos[j].get('data-ks-lazyload') if "jpg" in img_desc_info: img_desc_data.append(img_desc_info) except AttributeError as e: pass # 详情内容图片 print("共%s张图片" % str(len(img_desc_data))) print(img_desc_data) # 商品图片 prt_spu_img_info = [] prt_img = soup.find('ul', attrs={'id': 'J_UlThumb'}).find_all('img') print("共%s张商品主图" % str(len(prt_img))) for i in range(len(prt_img)): prt_img_url = prt_img[i].get('src') prt_spu_img_info.append(prt_img_url) # 数据都已检出,后续是将这些数据插入到数据表中 insert_data_to_prt_info(prt_id, prt_url, prt_title, face_price, market_price, prt_type, sku_id, sku_name,type_name, prt_type, other_name, color_type) # 详情内容 insert_data_to_prt_desc(prt_id,sku_id, prt_desc) # 图片 for m in range(len(prt_spu_img_info)): insert_data_to_prt_img(prt_id, prt_spu_img_info[m], 'good_img') # insert_data_to_prt_img(prt_id, prt_sku_img_url, 'sku_img') for n in range(len(img_desc_data)): insert_data_to_prt_img(prt_id, img_desc_data[n], 'desc_img') status = 1 return status except: status = 2 return status def update_prt_status(prt_id,status): db = pymysql.connect("localhost", "root", "123456", "tmall_semens", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update prt_lists set status='%d' where table_id='%s' " %(status,prt_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_status-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() data = get_prt_lists() for i in range(len(data)): # status=1 prt_id = data[i][0] prt_url = data[i][1] print(prt_id, prt_url) # 打开url,对数据进行一系列的分析抓取 status=get_html(prt_id, prt_url) # 处理完成后更新状态 update_prt_status(prt_id, status) s(4,12) <file_sep>/untitled/Selenium/工品汇/VIPMRO-list获取.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver def s(a,b): rand=random.randint(a,b) time.sleep(rand) def company_info(): company_name="德力西电气" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) ''' def get_main_data(url): d_prt_name=driver.find_elements_by_xpath("//div[@class='J_searchList']/ul/li[@class='b lh tl']/a") d_prt_type = driver.find_elements_by_xpath("//div[@class='J_searchList']/ul/li[@class='b lh tl']/div[@class='fl small_text']"[0]) d_order = driver.find_elements_by_xpath("//div[@class='J_searchList']/ul/li[@class='b lh tl']/div[@class='fl small_text']"[1]) d_price = driver.find_elements_by_xpath("//div[@class='J_searchList']/ul/li[@class='e lh tl']/div[@class='search-active']/span[@class='a']") d_market_price = driver.find_elements_by_xpath("//div[@class='J_searchList']/ul/li[@class='e lh tl']/div[@class='search-active']/span[@class='b']") print(str(len(d_prt_name)) + " " + str(len(d_price)) + " " + str(len(d_market_price))) for i in range(len(d_price)): prt_name = d_prt_name[i].text prt_url=d_prt_name[i].get_attribute("href") prt_type = d_prt_type[i].text order = d_order[i].text price = d_price[i].text market_price = d_market_price[i].text insert_data1(prt_name,prt_url,prt_type,order,price,market_price,url) ''' def get_main_data(url): J_searchLists=driver.find_elements_by_xpath("//div[@class='J_searchList']/ul") for Searchlist in J_searchLists: img_url=Searchlist.find_element_by_xpath("./li[@class='a']/a/img").get_attribute('src') prt_name=Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").text prt_url =Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").get_attribute('href') prt_id = prt_url[prt_url.index("product/") + 8:100] prt_type=Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[0].text order = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[1].text price=Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='a']").text market_price = Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='b']").text print(img_url,prt_name,prt_url,prt_type,order,price,market_price) insert_data1(img_url,prt_id,prt_name, prt_url, prt_type, order, price, market_price, url) def insert_data1(img_url,prt_id,prt_name,prt_url,prt_type,order,price,market_price,url): company_name=company_info() db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into vipmro_data (img_url,company_name,prt_id,prt_name,prt_url,prt_type,order_,price,market_price,cate_2_url)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(img_url,company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,url) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def next_page(j): time.sleep(4) xpath_data="//div[@class='saas-paging J_paging']/a[@class='J_page_turn'][@page-id='"+str(j+2)+"']" print(xpath_data) driver.find_element_by_xpath(xpath_data).click() time.sleep(4) def get_url_status(): company_name=company_info() db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select case when series_href='' then cate_2_url else series_href end as url from series_info where status=0 order by table_id limit 1 " try: execute=cursor.execute(sql) url=cursor.fetchmany(execute) return url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(url): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update series_info set status=1 where cate_2_url='%s' or series_href='%s' " \ % (url,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() if __name__=="__main__": driver=webdriver.Firefox() url = "http://www.vipmro.com/login" driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) driver.get("http://www.vipmro.com/search?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&brandId=104") s(3,5) driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() s(3,5) for i in range (60): url_t=get_url_status() url=url_t[0][0] print(url) driver.get(url) time.sleep(10) for j in range(15): s(5,8) get_main_data(url) try: next_page(j) except: print("没有下一页") break update_status_to_run_log(url) <file_sep>/找电缆EXCEL处理2.0新版/整理出excel匹配关系.py import os def read_xls(path, type2): #遍历路径文件夹 for file in os.walk(path): for each_list in file[2]: file_path=file[0]+"/"+each_list #os.walk()函数返回三个参数:路径,子文件夹,路径下的文件,利用字符串拼接file[0]和file[2]得到文件的路径 name.append(file_path) if __name__ == "__main__": xpath = r"D:\BI\找电缆\2017年12月红本出厂价《产品价格目录》" xtype = "xls" name = [] read_xls(xpath, xtype) for i in range (len(name)): print(name[i])<file_sep>/TMALL/西门子-开关插座/legrand-获取天猫列表数据.py import pymysql from selenium import webdriver import time import re from bs4 import BeautifulSoup def get_prt_lists(): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,url from legrand_tmall_series_info where status=0 " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_prt_lists-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_html(series_name,prt_url): driver.get(prt_url) #等待页面相应完成 html=driver.page_source time.sleep(11) data=driver.find_elements_by_xpath("//a[@class='item-name J_TGoldData']") for i in range (len(data)): url=data[i].get_attribute('href') #time.sleep(0.5) print(url) insert_data(series_name,url) #return html def find_useful_info(series_name,html): soup=BeautifulSoup(html,'html.parser') data=soup.find_all('a',attrs={'class':re.compile("J_TGoldData")}) print(data) for i in range (len(data)): url=data[i].get('href') #time.sleep(0.5) print(url) insert_data(series_name,url) def insert_data(series_name,url): db = pymysql.connect("localhost", "root", "123456", "tmall_semens", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into prt_lists (series_name,url) values('%s','%s') " %(series_name,url) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() data = get_prt_lists() #因为数据量不多,所以直接定义数组去循环就行了 series_names=['远景','灵致','悦动'] series_urls=[ 'https://siemensdg.tmall.com/category-1064252886.htm?spm=a1z10.3-b-s.w4011-15178175083.18.2fa6316bqjD8vj&tsearch=y#TmshopSrchNav', 'https://siemensdg.tmall.com/category-1064853734.htm?spm=a1z10.3-b-s.w4011-15178175083.21.2fa6316bJOfLx8&tsearch=y#TmshopSrchNav', 'https://siemensdg.tmall.com/category-1064853728.htm?spm=a1z10.3-b-s.w4011-15178175083.22.2fa6316blk4yQc&tsearch=y#TmshopSrchNav' ] for i in range(len(series_urls)): # status=1 series_name=series_names[i] series_url=series_urls[i] print(series_name, series_url) # 打开url,对数据进行一系列的分析抓取 html = get_html(series_name, series_url) print(html) # 把html的内容通过bs4进行检查 #find_useful_info(series_name,html) time.sleep(50) <file_sep>/suning/苏宁后台/苏宁后台获取商品基础信息.py import pymysql import random,time import os from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,login_url): browser = "Chrome" if browser == "Chrome": #profile_dir = r"C:\Users\CC-SERVER\AppData\Local\Google\Chrome\User Data" # 对应你的chrome的用户数据存放路径 options = webdriver.ChromeOptions() #options.add_argument("user-data-dir=" + os.path.abspath(profile_dir)) driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(login_url) name = input("Go?") print(name) driver.get('https://mcmp.suning.com/mcmp/myGoodsLibrary/mylibary.htm') self.s(3, 4) #进入我的商品表之后,开始抓取指定的数据 while 1==1: table_trs = driver.find_elements_by_xpath("//table[@class='protable myprotable jmy']/tbody/tr") print(len(table_trs)) for i in range (len(table_trs)): a_info=table_trs[i].find_elements_by_tag_name('a')[0] prt_id=a_info.get_attribute('id') prt_value = a_info.get_attribute('value') prt_class = a_info.get_attribute('class') print(prt_id,prt_value,prt_class) #拼接新的详情页内容url #https://mcmp.suning.com/mcmp/cmPublish/viewDetail.htm?categoryCode=R9004701&applyCode=6dd754d3-946e-49c3-ba9b-ce02614efb7d&productCode=10573347185&status=mine prt_info_url="https://mcmp.suning.com/mcmp/cmPublish/viewDetail.htm?categoryCode=%s&applyCode=%s&productCode=%s&status=mine" %(prt_class,prt_id,prt_value) print(prt_info_url) self.s(1,2) driver.find_element_by_xpath("//div[@class='pages r']/a[@class='next']").click() self.s(3, 5) if __name__=="__main__": main=main() #url="http://www.baidu.com" login_url="https://mpassport.suning.com/ids/login" main.init(login_url) <file_sep>/JD后台/VC后台/图片管理-名称&src关联.py import requests import os import pymysql from bs4 import BeautifulSoup def insert_to_img_zone(img_name,img_original_url,img_link,img_code): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into img_zone(img_original_url,img_link,img_code,img_name) values('%s','%s','%s','%s')" \ % (img_original_url,img_link,img_code,img_name) # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": url=r"D:\\Noname1.html" html_content=open(url,'r',encoding="utf-8") content=html_content.read() #print(content) soup = BeautifulSoup(content, "html.parser") # 实例化一个BeautifulSoup对象 img_lists=soup.find_all('li',attrs={'class':'main-item J-data-item'}) print("current page have %s records"%(str(len(img_lists)))) for i in range (len(img_lists)): img_original_url=img_lists[i].find('i',attrs={'class':'all J-original'}).get('data-url') img_link = img_lists[i].find('i', attrs={'class': 'link J-copy'}).get('data-clipboard-text') img_code = img_lists[i].find('i', attrs={'class': 'code J-copy-code'}).get('data-clipboard-text') img_name=img_lists[i].find('div',attrs={'class':'name J-name'}).get('title') print(img_name,img_original_url,img_link,img_code) insert_to_img_zone(img_name, img_original_url, img_link, img_code) <file_sep>/企查查/将企查查下载的excel合并到数据表.py #遍历所有的excel import xlrd import time import os import pymysql import logging import datetime from xlrd import xldate_as_tuple #把excel的数据直接存到临时数组,直接进行分析,抛弃mysql支持 class excel_operation(): def foreach(self,rootDir): files_excel=[] for root,dirs,files in os.walk(rootDir): for file in files: file_name=os.path.join(root,file) if 'xls' in file_name: files_excel.append(file_name) for dir in dirs: self.foreach(dir) return files_excel def get_excel_data(self): excel_dir = ".\input" path=os.path.abspath(excel_dir) #print(path) files_excel=self.foreach(path) #print(files_excel) for file_name in files_excel: #excel_name=r"..\input\33-006(1).xlsx" excel_name=file_name.split('\\')[-1] print(excel_name) data = xlrd.open_workbook(file_name) # 打开excel #print("当前excel共有%s个SHEET" % str(len(data.sheets()))) sheetName = data.sheet_names()[0] # print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[0] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] print(sheetName,nrows) for i in range (1,int(nrows)): row_title=table.row_values(0) row_info=table.row_values(i) #print(row_info) 企业名称 = "" 法定代表人 = "" 成立日期 = "" 注册资本 = "" 地址 = "" 邮箱 = "" 电话号码 = "" 经营范围 = "" 网址 = "" 统一社会信用代码 = "" 省份 = "" 城市 = "" 企业类型 = "" 更多电话号码 = "" for x in range (len(row_info)): row_name=row_title[x] row_value=row_info[x] #print(row_value) if "企业名称" in row_name: 企业名称=row_value elif "法定代表人" in row_name: 法定代表人=row_value elif "成立日期" in row_name: 成立日期 = row_value elif "注册资本" in row_name: 注册资本 = row_value elif "地址" in row_name: 地址 = row_value elif "邮箱" in row_name: 邮箱 = row_value elif "电话号码" == row_name: 电话号码 = row_value elif "经营范围" in row_name: 经营范围 = row_value elif "网址" in row_name: 网址 = row_value elif "统一社会信用代码" in row_name: 统一社会信用代码 = row_value elif "省份" in row_name: 省份 = row_value elif "城市" in row_name: 城市 = row_value elif "企业类型" in row_name: 企业类型 = row_value elif "电话号码(更多号码)" in row_name: 更多电话号码 = row_value #print(企业名称, 法定代表人, 成立日期, 注册资本, 地址, 邮箱, 电话号码, 经营范围, 网址, 统一社会信用代码, 省份, 城市, 企业类型,更多电话号码) insert_into_qichacha(企业名称,法定代表人,成立日期,注册资本,地址,邮箱,电话号码,经营范围,网址,统一社会信用代码,省份,城市,企业类型,更多电话号码) def insert_into_qichacha(company_name,legal,establish_date,register_capital,address,email,phone_number,scope_of_operation,website,social_code,provience,city,company_type,more_phone_number): db = pymysql.connect("localhost", "root", "123456", "company_data") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into company_info_qichacha(company_name,legal,establish_date,register_capital,address,email,phone_number,scope_of_operation,website,social_code,provience,city,company_type,more_phone_number) " \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (company_name,legal,establish_date,register_capital,address,email,phone_number,scope_of_operation,website,social_code,provience,city,company_type,more_phone_number) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": current_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) excel_operation=excel_operation() excel_operation.get_excel_data() <file_sep>/TMALL/ABB开关数据/main.py #获取两个系列的ABB开关的数据 #https://abb.tmall.com/p/rd624503.htm?spm=a1z10.1-b-s.w5001-15436620633.6.63e34987TnmTLk&scene=taobao_shop #这个页面,包含了6个子系列,轩致和德静 #1. 用requests请求,把所有的商品的url都抓出来;B了狗,又是坐标轴形式的数据流 import requests from selenium import webdriver from bs4 import BeautifulSoup import re def get_content(html): soup=BeautifulSoup(html,'html.parser') sub_series_info=soup.find_all('div',attrs={'class':'psrel lcr-out'}) print(len(sub_series_info)) #20个就对了 for i in range(len(sub_series_info)): #取<a>[0]的name属性 sub_series_name=sub_series_info[i].find_all('a')[0].get('name') print(sub_series_name) sub_series_prt_data=sub_series_info[i].find_all('a',attrs={'class':re.compile('psabs utools_module hotarea hotarea_')}) for x in range (len(sub_series_prt_data)): prt_url=sub_series_prt_data[x].get('href') prt_num=sub_series_prt_data[x].get('class') prt_num=str(prt_num[3]).replace("hotarea_","") print(sub_series_name,"^",prt_num,"^",prt_url) if __name__=="__main__": #通过requests获取url,然后分析一波 #看了一下requests的请求结果,决定还是用selenium抓取url把 #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() url="https://abb.tmall.com/p/rd624503.htm?spm=a1z10.1-b-s.w5001-15436620633.6.63e34987TnmTLk&scene=taobao_shop" driver.get(url) html=driver.page_source get_content(html) #懒得做数据存储了,直接导出print结果,放到excel处理了<file_sep>/Scrapy/Rainmeter/Rainmeter/spiders/get_imgurl.py import scrapy class Get_img_url(scrapy.Spider):#类的继承 #必须定义 name="Get_img_url" start_urls = [ "https://bbs.rainmeter.cn/forum-25-1.html" ] # 默认response处理函数 def parse(self, response): # 把结果写到文件中 filename = response.url.split("/")[-2] with open(filename, 'wb') as f: f.write(response.body) <file_sep>/HTML处理/html内容增加属性.py import pymysql import xlwt def get_html(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_id,prt_desc from prt_desc where status=1 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update(prt_id,prt_desc): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_desc set status=0,prt_desc='%s' where prt_id ='%s'" %(prt_desc,prt_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def replace_data(prt_id,prt_desc): prt_desc=prt_desc.replace('58c0b92939b328598f779c3a048b11be52eafb54.jpg"','58c0b92939b328598f779c3a048b11be52eafb54.jpg" class="max-width-900" ') prt_desc=prt_desc.replace('6a000295742b3091aa6d2f55a3d23d897fa7a2ba.jpg"','6a000295742b3091aa6d2f55a3d23d897fa7a2ba.jpg" class="max-width-900" ') prt_desc=prt_desc.replace('09c944a54811607b6d5babe94f4a043595801176.jpg"','09c944a54811607b6d5babe94f4a043595801176.jpg" class="max-width-900" ') prt_desc=prt_desc.replace('942e0de55831036fd7b93444247070176020e668.jpg"','942e0de55831036fd7b93444247070176020e668.jpg" class="max-width-900" ') prt_desc=prt_desc.replace('a1ae9e51c032a0e45ee9c36fc60943503d31f25e.jpg"','a1ae9e51c032a0e45ee9c36fc60943503d31f25e.jpg" class="max-width-900" ') prt_desc=prt_desc.replace('df085452ffbd457c640c3f2462e952839d1abc24.jpg"','df085452ffbd457c640c3f2462e952839d1abc24.jpg" class="max-width-900" ') print(prt_desc) return prt_desc if __name__=="__main__": for i in range (1000): data=get_html() prt_id=data[0][0] prt_desc=data[0][1] print(prt_id,prt_desc) prt_desc=replace_data(prt_id,prt_desc) update(prt_id,prt_desc) <file_sep>/untitled/Selenium/数据导入MYSQL.py import pymysql import xlrd from untitled.Selenium import webdriver def print_xls(): data=xlrd.open_workbook(r"D:\BI\test.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 PRT_NAME=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss PRT_NAME.append(ss) return PRT_NAME def mysql_insert(prt_name): db = pymysql.connect("192.168.180.147","root","1<PASSWORD>","test01" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql="insert into misumi" \ " (PRT_NAME)" \ " values('%s')" \ % (prt_name) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() #print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:'+err) # 关闭数据库连接 db.close() if __name__=="__main__": prt_1=[] next_pg="" driver=webdriver.Firefox() print('loading...进入品牌页面...') prt_content() save_prt_name(prt_1) <file_sep>/多线程/test.py import multiprocessing import time import urllib.request def worker(): name = multiprocessing.current_process().name print (name, 'Starting') getHtml() time.sleep(2) print (name, 'Exiting') def getHtml(): #print("正在打开网页并获取....") url='http://www.baidu.com' data=None req=urllib.request.Request(url,data) response = urllib.request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") print(Html) return Html if __name__ == '__main__': worker_1 = multiprocessing.Process(name='worker 1',target=worker) worker_2 = multiprocessing.Process(name='worker 2',target=worker) worker_1.start() worker_2.start() <file_sep>/对MMBAO搜索词Jieba分词/将剩余的关键词分词后进行反查用于确认分词所属.py import urllib.request import urllib.error from bs4 import BeautifulSoup import re import os import pymysql import xlrd import time from urllib import request def getHtml(url): req = request.Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/47.0") response = request.urlopen(req) html = response.read().decode('utf-8') # print(html) return html #从excel中获取url的列表数据 def get_data_from_excel(sheet_num): data=xlrd.open_workbook(r"D:\BI\MMBAO搜索词分类\搜索词通过功能返回商品名.xlsx") #打开excel sheetName = data.sheet_names()[sheet_num] table=data.sheets()[sheet_num] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 url_lists=[] #print(sheetName) for i in range(1,nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss url_lists.append(ss) return url_lists def find_first_prt(html,keyword): soup=BeautifulSoup(html,'html.parser') goods_boxs=soup.find_all('div',attrs={'class':'goods_box'}) prt_name=goods_boxs[0].find('div',attrs={'class':'tit mt5'}).find('a').get('title') print(prt_name) insert_data(keyword,prt_name ) def insert_data(keyword,prt_name ): db = pymysql.connect("localhost", "root", "123456", "mmbao") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into search_keyword_prt_name (keyword,prt_title)" \ "values('%s','%s')" \ % (keyword,prt_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() if __name__=="__main__": #url来自数据库,或者excel都可以 for x in range (1): sheet_num=x keyword_lists=get_data_from_excel(sheet_num) for i in range(len(keyword_lists)): data=keyword_lists[i] keyword=data[0] encode=data[1] #print(keyword,encode) #url='http://trade.mmbao.com/s_2017071400096566.html' #print(i+1,keyword) url=u'http://search.mmbao.com/?keywords='+encode print(i+1,keyword,url) html=getHtml(url) #print(html) try: find_first_prt(html,keyword) except: pass time.sleep(2) <file_sep>/untitled/返回图片大小V1.0.py import re from io import BytesIO import requests from PIL import Image import os import urllib.request import pymysql #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(img_url, img_name): if (len(img_url) != 0): fileName = img_name file_Path="D:\\IMG\\" urllib.request.urlretrieve(img_url, createFileWithFileName(file_Path,fileName)) def get_url(): db = pymysql.connect("localhost", "root", "123456", "mmbao") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select img_url from prt_img_data where img_name='%s' and original_url='%s' and is_repeat=0 limit 1" %(img_name) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #data=get_url() #img_url=data[0][0] img_urls={'http://www.mmbao.com//upload/prt/images/162294/%E8%AF%A6%E6%83%85(56).jpg' } for img_url in img_urls: img_name=img_url[img_url.rindex("/")+1:100] #print(img_name) url_response=requests.get(url=img_url) im=Image.open(BytesIO(url_response.content)) #print(im.format,im.size,im.mode) getAndSaveImg(img_url,img_name) path="D:\\IMG\\"+img_name size=os.path.getsize(path) print(float(size)/1024)<file_sep>/untitled/get_zyd_table.py import sys import urllib.request import pymysql import time import random from bs4 import BeautifulSoup import urllib.error def s(a,b): rand=random.randint(a,b) time.sleep(rand) def getHtml(url): #print("正在打开网页并获取....") headers = { 'Host': 'www.zydmall.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Accept': 'text/html, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'DNT': '1', 'Cookie':'wP_v=ab386a064e40Y1x1EZWpMZ9qFt80ztw6ZRWpkhp6mOIxTFlFUEG3z1wE7NMZw1P; ASP.NET_SessionId=glnzre4qzx4luxygcuffaugh; Hm_lvt_0d4eb179db6174f7994d97d77594484e=1498381442,1498529909,1498531476,1498543618; Hm_lpvt_0d4eb179db6174f7994d97d77594484e=1498546860', 'Referer': 'http://www.zydmall.com/detail/good_2192.html', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' } data=None req=urllib.request.Request(url,data,headers) try: response=urllib.request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") state=1 # print(Html) except urllib.error.URLError as e: print(e.reason) Html="" state=403 return Html,state def get_url(): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select good_url from good_url where status=0 order by table_id limit 1 " try: execute=cursor.execute(sql) product_id=cursor.fetchmany(execute) return product_id except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status(id,state): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update good_url set status='%d' where good_id='%s' " \ % (state,id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def insert_table_data(id,table_content): db = pymysql.connect("localhost","root","123456","ZYD",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_table_data " \ " (good_id,table_data)" \ " values('%s','%s')" \ % (id,table_content) try: cursor.execute(sql) db.commit() state=1 except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) state=2 db.close() cursor.close() return state if __name__=="__main__": #首先url要改为从数据表获取,动态url for i in range (5022): url=str(get_url()).replace("(('","").replace("',),)","") #url='http://www.zydmall.com/detail/good_1299.html' id=url.replace("http://www.zydmall.com/detail/good_","").replace(".html","") print(id+":"+url) html,state=getHtml(url) #print(state) if state == 403: print("403:访问被拒绝,需要变更IP,进程停止") break soup=BeautifulSoup(html,"html.parser") table_content=soup.find_all("table",attrs={"id":"prod_spec_table"}) print( table_content) state=insert_table_data(id,table_content) update_status(id,state) s(1,2) <file_sep>/待自动化运行脚本/产品库数据整理自动化/逐张表连库查询核对数据.py #通过excel数据导入mysql那个脚本,已经将所有的模板数据导入到了mysql #后面就要对每个sheet的数据进行校验,主要是针对ID #为了防止不同环境的ID不同,所以不管填不填,都要查一遍 import pymysql import cx_Oracle import logging def get_mysql_data(type): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") if type=="spu表": sql = "select spu_id,二级类目ID,二级类目名称,三级类目ID,三级类目名称,系列名称,品牌名称,SPU标题 from " + type elif type=="sku表": sql = "select * from " + type elif type=="销售属性表": sql = "select ID,对应SKU_ID,销售属性ID,销售属性名称,销售属性值ID,销售属性值,销售属性顺序_数字 from " + type elif type=="普通属性表": sql = "select ID,对应SPU_ID,普通属性ID,普通属性名称,普通属性值ID,普通属性值,普通属性顺序_数字 from " + type # print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('-------get_mysql_data--------Error------Message--------:' + str(err)) cursor.close() db.close() class spu_data(): def spu_table(self): spu_data=get_mysql_data('spu表') #print(spu_data) for spu_data_row in spu_data: spu_id = spu_data_row[0] cate2_id = spu_data_row[1] cate2_name = spu_data_row[2] cate3_id = spu_data_row[3] cate3_name = spu_data_row[4] cate_data=self.find_cate_id(cate2_name,cate3_name) new_cate2_id=cate_data[0][0] new_cate3_id=cate_data[0][1] if new_cate2_id!=cate2_id: print(cate2_id,new_cate2_id,cate2_name) if new_cate3_id!=cate3_id: print(cate3_id,new_cate3_id,cate3_name) self.update_spu_id(spu_id,new_cate2_id,new_cate3_id) logger.info("finish the spu_table check") def update_spu_id(self,spu_id,new_cate2_id,new_cate3_id): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update spu表 set 二级类目ID='%s',三级类目ID='%s' where spu_id='%s' " %(new_cate2_id,new_cate3_id,spu_id) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------get_mysql_data--------Error------Message--------:' + str(err)) cursor.close() db.close() def find_cate_id(self,cate2_name,cate3_name): if current_version=="test": db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.<EMAIL>.com:21252/mmbao2b2c') else: db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.58.3:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "select LEV2_CAT_ID,LEV3_CAT_ID from MMBAO2.V_PRT_CATGORY_LEVEL3 WHERE LEV2_CAT_NAME='%s' and LEV3_CAT_NAME='%s' " \ %(cate2_name,cate3_name) # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data class sale_attr_data(): def sale_attr_table(self): saleattr_data=get_mysql_data('销售属性表') #print(spu_data) for data_row in saleattr_data: table_id = data_row[0] sku_id = data_row[1] attr_id = data_row[2] attr_name = data_row[3] attr_value_id = data_row[4] attr_value = data_row[5] cate_data=self.find_cate(sku_id) cate2_id = cate_data[0][1] cate3_id = cate_data[0][2] sale_attr_name_data = self.find_sale_attr_id(cate2_id,cate3_id,attr_name,attr_value) if len(sale_attr_name_data)==0: sale_attr_id='' else: sale_attr_id=sale_attr_name_data[0][0] #################然后拿着attr_id去查找attr_value_id sale_attr_value_data = self.find_sale_attr_value_id(cate2_id, cate3_id, attr_name, attr_value) if len(sale_attr_value_data)==0: sale_attr_value_id='' else: sale_attr_value_id=sale_attr_value_data[0][0] logger.info(sale_attr_id) logger.info(sale_attr_value_id) self.update_sale_attr_id(table_id,sale_attr_id,sale_attr_value_id) logger.info("finish the sale_attribute check") def update_sale_attr_id(self,table_id,sale_attr_id,sale_attr_value_id): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update 销售属性表 set 销售属性ID='%s',销售属性值ID='%s' where ID='%s'" %(sale_attr_id,sale_attr_value_id,table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------update_sale_attr_id--------Error------Message--------:' + str(err)) cursor.close() db.close() def find_sale_attr_id(self,cate2_id, cate3_id, attr_name, attr_value): if current_version=="test": db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.<EMAIL>:21252/mmbao2b2c') else: db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.58.3:7018/mmbao2b2c') cursor = db.cursor() sql = "select ATTR_ID from MMBAO2.V_PRT_CATGORY_ATTR_VAL "\ "WHERE LEV2_CAT_ID='%s' and LEV3_CAT_ID = '%s' AND attr_name='%s'" \ %(cate2_id, cate3_id, attr_name) #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def find_sale_attr_value_id(self,cate2_id, cate3_id, attr_name, attr_value): if current_version=="test": db = cx_Oracle.connect('mmbao2_bi/<EMAIL>:21252/mmbao2b2c') else: db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.58.3:7018/mmbao2b2c') cursor = db.cursor() sql = "select ATTR_ID from MMBAO2.V_PRT_CATGORY_ATTR_VAL "\ "WHERE LEV2_CAT_ID='%s' and LEV3_CAT_ID = '%s' AND attr_name='%s' and attr_val_value='%s' " \ %(cate2_id, cate3_id, attr_name,attr_value) # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def find_cate(self,sku_id): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select a.SKU_ID,b.二级类目ID,b.三级类目ID from sku表 a "\ "left join spu表 b on a.对应SPU_ID=b.spu_id "\ "where a.SKU_ID='%s' " %(sku_id) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('-------get_mysql_data--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) current_version='test' #spu_table spu_data=spu_data() spu_data.spu_table() sale_attr_data=sale_attr_data() sale_attr_data.sale_attr_table() <file_sep>/JD/JD-德力西开关/德力西开关CD301和CD601.py import pymysql from selenium import webdriver from bs4 import BeautifulSoup def insert_data(name,href): db = pymysql.connect("localhost", "root", "123456", "德力西电工", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into jd_delixi_lists (prt_name,prt_url) values('%s','%s')" %(name,href) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_lists(html): soup=BeautifulSoup(html,"html.parser") lis=soup.find_all('li',attrs={'class':'jSubObject'}) print(str(len(lis))) for i in range (len(lis)): href=lis[i].find('div',attrs={'class':'jDesc'}).find('a').get('href') print(href) name = lis[i].find('div', attrs={'class': 'jDesc'}).find('a').text insert_data(name,href) if __name__=="__main__": url="https://mall.jd.com/view_search-629426-555716-547800-0-0-0-0-1-2-60.html?keyword=cd601&isGlobalSearch=0&other=" driver=webdriver.Firefox() driver.get(url) html=driver.page_source find_lists(html) <file_sep>/untitled/Selenium/米思米/商品获取模块2.0.py import time import pyautogui import pymysql from untitled.Selenium import webdriver def Get_category_1(): print('loading...进入品牌页面...') driver.get('http://cn.misumi-ec.com/vona2/result/?Keyword=%E6%96%BD%E8%80%90%E5%BE%B7%E7%94%B5%E6%B0%94') time.sleep(2) pyautogui.typewrite(['tab','tab','esc']) time.sleep(2) prt_link = driver.find_elements_by_css_selector(".wrap.clearfix") print('共' + str(len(prt_link)) + '种商品类别') page_num3 = int(driver.find_element_by_xpath("//ul[@id='series_pager_upper']/li[@class='on']/a").text) print('当前第'+str(page_num3)+'页') for i in range(len(prt_link)): prt_link1 = prt_link[i].find_element_by_class_name('mainArea__productlist--txt').find_element_by_tag_name('a') # print('saving...category_name_2...to the arraylist-->prt_5') prt_link5 = prt_link1.text prt_1.append(prt_link1) print(prt_link1.text) # print('saving...category_url_2...to the arraylist-->prt_6') prt_link2 = prt_link1.get_attribute('href') prt_2.append(prt_link2) print('url:' + prt_link2) category_next_page(page_num3) # print('---------------------------------------分割线--------------------------------------') def Get_category_2(): time.sleep(2) prt_link = driver.find_elements_by_css_selector(".wrap.clearfix") print('共' + str(len(prt_link)) + '种商品类别') page_num3 = int(driver.find_element_by_xpath("//ul[@id='series_pager_upper']/li[@class='on']/a").text) print('当前第'+str(page_num3)+'页') for i in range(len(prt_link)): prt_link1 = prt_link[i].find_element_by_class_name('mainArea__productlist--txt').find_element_by_tag_name('a') # print('saving...category_name_2...to the arraylist-->prt_5') prt_link5 = prt_link1.text prt_1.append(prt_link1) print(prt_link1.text) # print('saving...category_url_2...to the arraylist-->prt_6') prt_link2 = prt_link1.get_attribute('href') prt_2.append(prt_link2) print('url:' + prt_link2) category_next_page(page_num3) # print('---------------------------------------分割线--------------------------------------' def category_next_page(page_num): try: driver.find_element_by_id("series_pager_upper_right").click() time.sleep(5) #pyautogui.typewrite(['down','down','down','down','down','down']) page_num4 = int(driver.find_element_by_xpath("//ul[@id='series_pager_upper']/li[@class='on']/a").text) #print('当前页面-->' + str(page_num2)) if page_num4!=page_num: Get_category_2() else: time.sleep(4) Get_category_2() except : next_pg="none" print("error,已到底页,该类型商品翻页循环结束") def mysql_insert(prt_name,prt_name2,brand): db = pymysql.connect("192.168.180.147","root","123456","test01" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql="insert into misumi " \ " (PRT_NAME,PRT_NAME2,BRAND)" \ " values('%s','%s','%s')" \ % (prt_name,prt_name2,brand) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() #print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:'+err) # 关闭数据库连接 db.close() def prt_content(url): print('GET-->'+url) driver.get(url) time.sleep(5) handles = driver.window_handles driver.switch_to.window(handles[0]) time.sleep(1) pyautogui.typewrite(['tab','tab','esc']) time.sleep(2) pyautogui.typewrite(['down', 'down', 'down', 'down', 'down', 'down', 'down', 'down', 'down']) driver.find_element_by_xpath("//div[@id='Tab_container']/ul/li/a[@id='Tab_codeList']").click() time.sleep(2) try: driver.find_element_by_id('detail_codeList_pager_lower_right').click() pyautogui.typewrite(['down', 'down', 'down', 'down', 'down', 'down']) except: print('MDZZ就一页翻个毛!') #target = driver.find_element_by_id("detail_codeList_pager_lower") #driver.execute_script("arguments[0].scrollIntoView();", target) # 拖动到可见 的元素去 #pyautogui.typewrite(['up','up','up','up','up','up','up','up','up','up']) #js = "var q=document.documentElement.scrollTop=document.body.scrollTop*0.7" #driver.execute_script(js) #time.sleep(1) page_num1 = int(driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text) print('当前页面:第' + str(page_num1)+'页') prt_info = driver.find_elements_by_xpath("//div[@id='listContents']/table[@id='ListTable']/tbody/tr/td[@class='model']") print(str(len(prt_info))) for i in range(len(prt_info)): prt_name = prt_info[i].text #print(prt_name) mysql_insert(prt_name,prt_name,brand) next_page(page_num1) def prt_content2(): page_num1=driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text print('当前页面:第' + str(page_num1) + '页') prt_info = driver.find_elements_by_xpath("//div[@id='listContents']/table[@id='ListTable']/tbody/tr/td[@class='model']") print(str(len(prt_info))) for i in range(len(prt_info)): prt_name = prt_info[i].text #print(prt_name) mysql_insert(prt_name,prt_name,brand) time.sleep(3) if next_pg!="none": next_page(page_num1) #driver.find_element_by_id('detail_codeList_pager_lower_right').click() #page_num1=page_num1+1 #print('自加1='+str(page_num1)) def next_page(page_num): try: #driver.find_element_by_xpath("//li[@id='detail_codeList_pager_upper_right']/a").click() driver.find_element_by_id('detail_codeList_pager_lower_right').click() time.sleep(4) #pyautogui.typewrite(['down','down','down','down','down','down']) page_num2 = int(driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text) #print('当前页面-->' + str(page_num2)) if page_num2!=page_num: prt_content2() else: time.sleep(3) prt_content2() except : next_pg="none" print("error,已到底页,该类型商品翻页循环结束") if __name__=="__main__": prt_1=[] prt_2=[] next_pg="" brand="施耐德电气(Schneider Electric)" driver=webdriver.Firefox() #获取产品一级类目 Get_category_1() for i in range(len(prt_2)): prt_content(prt_2[i]) print('结束一个三级类目商品的名称获取') <file_sep>/untitled/Selenium/dq123/dq123数据获取-20170831/DQ123-根据关键词获取详情页V1.1.py #倒叙进行 from selenium import webdriver from selenium.common.exceptions import TimeoutException import time import pymysql import random def s(a,b): rand=random.randint(a,b) time.sleep(rand) def swith_tab(): print("开始切换标签") driver.find_element_by_id("showhidediv1").click() def find_same_record(name,price): #输入型号、价格,用于验证数据准确性;输出状态,1为找到,2为没有找到,结果为页面跳转事件 table = driver.find_element_by_id('part_list') trs = table.find_elements_by_tag_name('tr') nums = len(trs) print("共%s条相似的记录,正在查找完全一样的数据" % nums) for tr in trs: tds = tr.find_elements_by_tag_name('td') prt_id = tds[0].text # prt_name=tds[1].get_attribute('title') prt_name = tds[1].find_element_by_tag_name('a').text prt_price = tds[2].text print(prt_id, prt_name, prt_price) if name==prt_name and price==prt_price: #当两个数据完全一样,那么触发点击事件 print("找到一样的数据了,正在加载页面") print("waiting for the page to reload") tds[1].find_element_by_tag_name('a').click() s(4,6) list_state = 1 return list_state print("maybe there have no same data for you") list_state=2 return list_state def get_prt_cnt(): #输入无,输出一个tuple,prt_name和price db = pymysql.connect("localhost", "root", "123456", "yidun", charset="utf8") cursor = db.cursor() sql = "select count(prt_name) as cnt from yidun_prt_lists where status=10 " try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) cnt=str(cnt).replace("((", "").replace(",),)", "") return cnt except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def update_prt_status(status,prt_no,prt_name): #输入无,输出一个tuple,prt_name和price db = pymysql.connect("localhost", "root", "123456", "yidun", charset="utf8") cursor = db.cursor() sql = "update yidun_prt_lists set status='%d' where status=10 and prt_no='%s' and prt_name='%s'" %(status,prt_no,prt_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_prt_info(): #输入无,输出一个tuple,prt_name和price db = pymysql.connect("localhost", "root", "123456", "yidun", charset="utf8") cursor = db.cursor() sql = "select prt_name,prt_price,prt_no from yidun_prt_lists where status=10 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def get_basic_data(prt_name): # 输入无,输出无,结果直接insert到数据表 ''' cnt=0 while 1==1: name = driver.find_element_by_id('result_prodname').text if name!=prt_name: print("waiting...") time.sleep(1) cnt+=1 if cnt>15: break ''' name = driver.find_element_by_id('result_prodname').text try: if name != prt_name: detail_state = 2 print("为什么会因为名称不同跳出?") return detail_state detail_state = 1 print("成功二次验证") return detail_state except: print("异常跳出") detail_state = 3 return detail_state def get_attrs_data(prt_no,prt_name): #输入无,输出无,结果直接insert到数据表 Part_MainProp=driver.find_element_by_id('Part_MainProp') div_lists=Part_MainProp.find_elements_by_class_name('prop_part') print("共%s条属性"%str(len(div_lists))) attr_no=0 for div_list in div_lists: attr_no+=1 attr_name=div_list.find_element_by_xpath("./div[@class='prop_title']/label").text try: attr_value = div_list.find_element_by_xpath("./div[@class='prop_list']/span[@ischk='1']").text except: attr_value="" print(attr_no,attr_name,attr_value) insert_attrs(prt_no,prt_name,attr_no,attr_name,attr_value) def insert_attrs(prt_no,prt_name,attr_no,attr_name,attr_value): db = pymysql.connect("localhost", "root", "123456", "yidun", charset="utf8") cursor = db.cursor() sql = "insert into prt_attribute(prt_no,prt_name,attr_no,attr_name,attr_value) values('%d','%s','%d','%s','%s')" %(prt_no,prt_name,attr_no,attr_name,attr_value) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_imgs(prt_no,prt_name): img_src=driver.find_element_by_id('elementimg').get_attribute('src') img_name=img_src[img_src.rindex("/")+1:100] print(img_name,img_src) insert_img_data(prt_no,prt_name,img_name,"","small_img",img_src,1) def insert_img_data(prt_no,prt_name,img_name,img_path,type,original_url,img_num): db = pymysql.connect("localhost", "root", "123456", "<PASSWORD>", charset="utf8") cursor = db.cursor() sql = "insert into prt_img_info " \ " (prt_no,prt_name,img_name,img_path,type,original_url,img_num)" \ " values('%d','%s','%s','%s','%s','%s','%d')" \ % (prt_no,prt_name, img_name, img_path, type, original_url, img_num) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #从数据表获取数据 cnt=get_prt_cnt() print("共%s条数据"%cnt) driver = webdriver.Firefox() driver.set_page_load_timeout(50) #driver.set_script_timeout(10) #driver.maximize_window() url = "http://www.dq123.com/price/index.php?kw=prt_name" count = 0 while True: count += 1 print("第%s次尝试" % str(count)) try: driver.get(url) break except: pass for i in range(int(cnt)): data=get_prt_info() prt_name=data[0][0] price=data[0][1] prt_no=data[0][2] print(prt_no,prt_name,price) while 1 == 1: # 验证页面的加载情况 print("waiting...") try: div_table = driver.find_element_by_id('part_list').find_elements_by_tag_name('tr') if len(div_table) > 0: break time.sleep(1) except: time.sleep(1) s(2, 4) #加入输入、点击事件 try: driver.find_element_by_id('searchinputmodel').clear() except: print("重新切换标签") swith_tab() s(4,5) driver.find_element_by_id('searchinputmodel').clear() driver.find_element_by_id('searchinputmodel').send_keys(prt_name) driver.find_element_by_id("search_text").click() while 1==1: #验证页面的加载情况 print("waiting...") try: div_table=driver.find_element_by_id('part_list').find_elements_by_tag_name('tr') if len(div_table)>0: break time.sleep(1) except: time.sleep(1) s(1,3) #获取列表中当的结果记录,到click(),返回状态 try: list_state=find_same_record(prt_name,price) except: list_state=3 if list_state==1: #进入到详情页后,获取属性模块,详情页基础模块 detail_state=get_basic_data(prt_name) if detail_state==1: get_attrs_data(prt_no,prt_name) get_imgs(prt_no,prt_name) status=11 else: print("error in detail_state") status=12 else: print("error in list_state") status=13 update_prt_status(status, prt_no, prt_name) s(1,2) try: swith_tab() except: pass print("-----------------------------------------")<file_sep>/untitled/抓取斗图.py #打开html #获取所有指定的<a>标签中的href #遍历打开所有的href中的url #获取指定的元素 #获取图片的url链接 #通过函数,将图片保存到本地 import time import os import re import urllib.request import uuid from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait #生成一个文件名字符串 def generateFileName(): return str(uuid.uuid1()) #根据文件名创建文件 def createFileWithFileName(localPathParam,fileName): totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath def getAndSaveImg(imgUrl,img_name): if (len(imgUrl) != 0): fileName = img_name + '.jpg' fileName = re.sub('[\/:*?"<>|]', '-', fileName) try: urllib.request.urlretrieve(imgUrl, createFileWithFileName("C:\\Downloads", fileName)) except: print("这图我没法下载") #获取每个list的url def get_list(): lists = driver.find_elements_by_class_name("list-group-item") for i in range(len(lists)): list = lists[i].get_attribute("href") print(list) # 存入list中 list_info.append(list) if __name__=="__main__": driver=webdriver.PhantomJS() driver.set_window_size(1400, 900) for m in range(1,50): list_info = [] url="http://www.doutula.com/article/list?page="+str(m+1) driver.get(url) #网页加载完成后,等待2s wait1 = WebDriverWait(driver, 2) # 获取每个list的url,返回结果存入了list_info get_list() #遍历每个url链接,打开 for j in range(len(list_info)): driver.get(list_info[j]) wait2 = WebDriverWait(driver, 2) #page=driver.page_source #print(page) url_info=driver.find_elements_by_xpath("//div[@class='artile_des']/table/tbody") for x in range (len(url_info)): img_url=url_info[x].find_element_by_tag_name("img").get_attribute("src") img_name = url_info[x].find_element_by_tag_name("img").get_attribute("alt") print("坐标" + str(m+1)+":"+str(j)+":"+str(x)) print(img_url+"----->"+img_name) getAndSaveImg(img_url,img_name) #print('第'+str(j+1)+"行") <file_sep>/工品汇/获取.com类目数据.py import requests import re from bs4 import BeautifulSoup def get_content(url): s = requests.get(url) content = s.content.decode('utf-8') print(content) return content if __name__=="__main__": url="http://www.vipmro.com/promotion/delixi.html?flag=25083247" content=get_content(url) soup=BeautifulSoup(content,'html.parser') main_menu=soup.find('div',attrs={'class':'menu-main'}).find_all('div',attrs={'class':'li'}) for i in range (len(main_menu)): menu_li=main_menu[i].find_all('div',attrs={'class':'menu_li'}) for j in range(len(menu_li)): cate3=menu_li[j].find_all('a',attrs={'class':'flag aaaa'}) for k in range (len(cate3)): print(cate3[k].text) <file_sep>/untitled/Selenium/dq123/dq123数据获取-20170831/dq123-伊顿电气获取.py #数据量,所有的伊顿电气,list、详情页属性、图片、等等 #分为3步骤: #1.获取类目数据 #2.将伊顿电气的所有list跑一遍,取出型号、价格、公司 #3.获取详情 from selenium import webdriver import pymysql import time #import logging #logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(levelname)s - %(message)s') from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import random def s(a,b): rand=random.randint(a,b) time.sleep(rand) def swith_tab(): print("开始切换标签") try: tab=wait1.until(EC.presence_of_element_located((By.ID,"showhidediv1"))) tab.click() except TimeoutException: return swith_tab() class get_lists(): def get_list_data(self,series): table=driver.find_element_by_id('part_list') trs=table.find_elements_by_tag_name('tr') for tr in trs: tds=tr.find_elements_by_tag_name('td') prt_id=tds[0].text #prt_name=tds[1].get_attribute('title') prt_name=tds[1].find_element_by_tag_name('a').text prt_price=tds[2].text print(prt_id,prt_name,prt_price) self.insert_prt_lists(int(prt_id),prt_name,prt_price,series) nums=len(trs) return nums def insert_prt_lists(self,prt_no,prt_name,prt_price,series): db = pymysql.connect("localhost", "root", "123456", "yidun", charset="utf8") cursor = db.cursor() sql = "insert into yidun_prt_lists (prt_no,prt_name,prt_price,series) values('%d','%s','%s','%s')" % (prt_no,prt_name,prt_price,series) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def turn_pages(self): #先看下有没有下一页,没有下一页,就说明到底了 div_=driver.find_element_by_id('pagesdiv') next_btn=div_.find_element_by_xpath("./a[@title='下一页']") print("点击",next_btn.text) next_btn.click() s(4,6) #page_no=" "+str(page_no)+" " #if int(page_num)<=2: #page_num=int(page_num)-1 #page_a=driver.find_element_by_id('pagesdiv').find_elements_by_tag_name('a')[int(page_num)] #next_page=page_a.text #print('即将转到第%s页'%next_page) #page_a.click() if __name__=="__main__": url="http://www.dq123.com/price" browser="Firefox" if browser=="Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser=="Firefox": driver=webdriver.Firefox() else: driver=webdriver.PhantomJS() driver.get(url) wait1 = WebDriverWait(driver, 15) s(4,5) #print(driver.page_source) swith_tab() #简化结构,添加循环判断 print('-----------------手动选择公司名称-------20s内------') while 1==1: title = driver.find_element_by_xpath("//a[@class='level1 curSelectedNode']").get_attribute('title') print(title) if title=="伊顿电气集团-2017年3月版价格": print("已确认公司名称匹配,continue...") break s(2,3) s(5,7) #先获取一次选择项 for i in range (500): #selected_cate=driver.find_element_by_css_selector(".level2.curSelectedNode").get_attribute('title') selected_cate = driver.find_elements_by_xpath("//a[contains(@class,'curSelectedNode')]")[1].get_attribute('title') print("当前选择的系列-->%s"%selected_cate) current_category="" print("-----------------------------------------------") while 1==1: #current_cate=driver.find_element_by_css_selector(".level2.curSelectedNode").get_attribute('title') current_cate=driver.find_elements_by_xpath("//a[contains(@class,'curSelectedNode')]")[1].get_attribute('title') if current_cate!=selected_cate: print('已选择系列%s'%current_cate) current_category=current_cate break s(2,3) s(5,7) #table_data=driver.find_element_by_class_name('yjtbs') #print(table_data) #在获取数据前,还要再核对一次右上角的系列 table_data = get_lists() page_no=1 while 1==1: try: current_page = driver.find_element_by_id('pagesdiv').find_element_by_tag_name('strong').text except: print("可能就一页,没有pagesdiv") current_page='1' print("当前第%s页"%current_page,"page_no:%s"%str(page_no)) #判断当前页码 if str(current_page.replace(" ", "")) == str(page_no): print("准备刷取第" + str(page_no) + "页数据") nums=table_data.get_list_data(current_category) #返回当前页面的数据量,供验证 if nums==50: print("翻页") try: table_data.turn_pages() except: break page_no += 1 s(5, 7) else: try: table_data.turn_pages() except: print("翻页出现异常,应该是到底了") break print("完成该系列数据,准备切换系列") <file_sep>/untitled/爬取图片保存本地.py import urllib.request import re def getHtml(url): """通过页面url获取其对应的html内容""" page = urllib.request.urlopen(url) # 打开页面 content = page.read() # 读取页面内容 return content def getImage(html): """通过解析html获取图片地址,实现图片的下载""" regx = r'src="(.+?\.jpg)" pic_ext' # 利用正则表达式获得图片url imgreg = re.compile(regx) html = html.decode('utf-8') # python3 imglist = re.findall(imgreg, html) x = 0 for imgurl in imglist: filepath = 'F:\\Downloads\\' + str(x) + '.jpg' urllib.request.urlretrieve(imgurl ,'%s.jpg'%x) # 将图片下载到本地 x += 1 print('completed!') html = getHtml('http://tieba.baidu.com/f?ie=utf-8&kw=%E6%96%97%E5%9B%BE&fr=search&red_tag=h1859340659') imglist = getImage(html)<file_sep>/待自动化运行脚本/产品库数据整理自动化/excel数据导入mysql.py import pymysql import os import xlrd class excel_operation(): def foreach(self,rootDir): files_excel=[] for root,dirs,files in os.walk(rootDir): for file in files: file_name=os.path.join(root,file) if 'xls' in file_name: files_excel.append(file_name) for dir in dirs: self.foreach(dir) return files_excel def get_excel_name(self): excel_dir = ".\excel" path=os.path.abspath(excel_dir) #print(path) files_excel=self.foreach(path) #print(files_excel) for file_name in files_excel: #excel_name=r"..\input\33-006(1).xlsx" excel_name=file_name.split('\\')[-1] print(excel_name) self.get_excel_data(file_name) def get_excel_data(self,file_name): data = xlrd.open_workbook(file_name) # 打开excel #SPU表 sheetName = data.sheet_names()[0] table = data.sheets()[0] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 print(sheetName,nrows) for a in range (1,nrows): row_info = table.row_values(a) #print(row_info) insert_into_spu_table(row_info) #SKU表 sheetName = data.sheet_names()[1] table = data.sheets()[1] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 print(sheetName,nrows) for a in range (1,nrows): row_info = table.row_values(a) #print(row_info) insert_into_sku_table(row_info) #销售属性表 sheetName = data.sheet_names()[2] table = data.sheets()[2] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 print(sheetName,nrows) for a in range (1,nrows): row_info = table.row_values(a) #print(row_info) insert_into_sale_attributes_table(row_info) #普通属性表 sheetName = data.sheet_names()[3] table = data.sheets()[3] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 print(sheetName,nrows) for a in range (1,nrows): row_info = table.row_values(a) #print(row_info) insert_into_pt_attributes_table(row_info) def insert_into_spu_table(row_info): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into spu表 (spu_id,二级类目ID,二级类目名称,三级类目ID,三级类目名称,系列名称,品牌名称,SPU标题)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s')" \ %(row_info[0],row_info[1],row_info[2],row_info[3],row_info[4],row_info[5],row_info[6],row_info[7]) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_into_spu_table--------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_into_sku_table(row_info): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into sku表 (SKU_ID,对应SPU_ID,订货号,面价,重量_千克,装箱数,排序_数字,SKU标题,SKU副标题)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ %(row_info[0],row_info[1],row_info[2],row_info[3],row_info[4],row_info[5],row_info[6],row_info[7],row_info[8]) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_into_sku_table---------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_into_sale_attributes_table(row_info): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into 销售属性表 (ID,对应SKU_ID,销售属性ID,销售属性名称,销售属性值ID,销售属性值,销售属性顺序_数字)"\ "values('%s','%s','%s','%s','%s','%s','%s')" \ %(row_info[0],row_info[1],row_info[2],row_info[3],row_info[4],row_info[5],row_info[6]) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_into_sale_attributes_table--------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_into_pt_attributes_table(row_info): db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into 普通属性表 (ID,对应SPU_ID,普通属性ID,普通属性名称,普通属性值ID,普通属性值,普通属性顺序_数字)"\ "values('%s','%s','%s','%s','%s','%s','%s')" \ %(row_info[0],row_info[1],row_info[2],row_info[3],row_info[4],row_info[5],row_info[6]) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_into_pt_attributes_table--------Error------Message--------:' + str(err)) cursor.close() db.close() def delete_original_data(): print("cleaning original table data") db = pymysql.connect("localhost", "root", "123456", "product") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "delete from 普通属性表;delete from 销售属性表;delete from spu表;delete from sku表;" try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_into_pt_attributes_table--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": delete_original_data() excel_operation=excel_operation() excel_operation.get_excel_name()<file_sep>/工品汇/伊顿电气-20170831/VIPMRO-伊顿电气-详情页数据获取.py from selenium import webdriver import time import pymysql import random def s(a,b): rand=random.randint(a,b) time.sleep(rand) def company_info(): company_name="伊顿电气" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) class get_series_data(): def get_url_cnt(self): db = pymysql.connect("localhost", "root", "123456", "vipmro", charset="utf8") cursor = db.cursor() sql = "select count(prt_url) as cnt from vipmro_data where status=0" try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) cnt = str(cnt).replace("((", "").replace(",),)", "") return cnt except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_prt_url(self): db = pymysql.connect("localhost", "root", "123456", "vipmro", charset="utf8") cursor = db.cursor() sql = "select prt_name,prt_url from vipmro_data where status=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) #url = str(cnt).replace("((", "").replace(",),)", "") return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_prt_detail(self,cate_2_name,cate_2_url,series_name,series_href): db = pymysql.connect("localhost", "root", "123456", "vipmro", charset="utf8") cursor = db.cursor() sql = "insert into series_info " \ " (cate_2_name,cate_2_url,series_name,series_href)" \ " values('%s','%s','%s','%s')" \ % (cate_2_name,cate_2_url,series_name,series_href) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(self,prt_id,prt_url,status): db = pymysql.connect("localhost", "root", "123456", "vipmro", charset="utf8") cursor = db.cursor() sql = "update vipmro_data set status='%d' where prt_id='%s' and prt_url='%s'" \ % (status,prt_id,prt_url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() class detail_data(): def get_main(self,prt_id,prt_url): prt_title=driver.find_element_by_css_selector('.product-main-r-title.ft22.p-bottom10.m-top15.J_productTitle').text print("商品名称%s"%prt_title) price=driver.find_element_by_xpath("//div[@class='product-main-r-price-row']/font/span[@class='ft20']").text print("单价%s"%price) market_price = driver.find_element_by_xpath("//div[@class='product-main-r-price-row']/font[@class='b']").text print("市场价%s" % market_price) prt_infos=driver.find_elements_by_xpath("//div[@class='product-main-r-cont p-top5 J_productCont']/span") brand_name=prt_infos[0].text order_num=prt_infos[1].text prt_type=prt_infos[2].text content=prt_infos[3].text print("品牌%s,订货号%s,商品型号%s,备注%s"%(brand_name,order_num,prt_type,content)) self.insert_main_data(prt_id,prt_url,prt_title,price,market_price,brand_name,order_num,prt_type,content) def get_content(self,prt_id): table=driver.find_element_by_css_selector(".product-introduce.m-top20.fl") table_source=table.get_attribute('innerHTML') self.insert_prt_desc(prt_id,table_source) #print(table_source) def insert_prt_desc(self,prt_id,table_source): db = pymysql.connect("localhost", "root", "123456", "vipmro", charset="utf8") cursor = db.cursor() sql = "insert into prt_desc " \ " (prt_id,prt_desc)" \ " values('%s','%s')" \ % (prt_id,table_source) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_attrs(self): attrs_info=driver.find_element_by_class_name('J_attrsH') attr_names=attrs_info.find_elements_by_css_selector('.produceAttrText.fl') for attr_name in attr_names: print("属性名称%s"%attr_name.text) attr_values = attrs_info.find_elements_by_tag_name('select') for attr_value in attr_values: print("属性值%s" % attr_value.text) def insert_main_data(self,prt_name,prt_url,prt_title,price,market_price,brand_name,order_num,prt_type,content): db = pymysql.connect("localhost", "root", "123456", "vipmro", charset="utf8") cursor = db.cursor() sql = "insert into prt_main_info " \ " (prt_id,prt_url,prt_title,price,market_price,brand_name,order_num,prt_type,content)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (prt_name,prt_url,prt_title,price,market_price,brand_name,order_num,prt_type,content) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_img(self,prt_id): have_big_img=0 img_num=0 ul_imgs=driver.find_elements_by_xpath("//ul[@class='J_smallImage smallImage']/li/img") for ul_img in ul_imgs: small_img_url=ul_img.get_attribute('src') small_img_name=small_img_url[small_img_url.rindex("/")+1:1000] print("small_img_url: " + small_img_url) print("small_img_name: " + small_img_name) img_num+=1 self.insert_img_data(prt_id,small_img_name,"","侧图-小",small_img_url,img_num) #不一定会有这个属性 try: big_img_url = ul_img.get_attribute('attr-bigimageurl') big_img_name = big_img_url[big_img_url.rindex("/") + 1:1000] print("big_img_url: " + big_img_url) print("big_img_name: " + big_img_name) img_num += 1 self.insert_img_data(prt_id, small_img_name, "", "侧图-大", small_img_url, img_num) except: have_big_img = 0 #如果没有大图的属性 if have_big_img==0: div_img=driver.find_element_by_xpath("//div[@class='detail-goods-left-image un-select J_bigImage']/img").get_attribute('src') large_img_url=div_img large_img_name=large_img_url[large_img_url.rindex("/")+1:1000] print("large_img_url: "+large_img_url) print("large_img_name: " + large_img_name) img_num += 1 self.insert_img_data(prt_id, large_img_name, "", "侧图-大", large_img_url, img_num) #存储大图 #详情内容中的图片 table = driver.find_element_by_css_selector(".product-introduce.m-top20.fl") img_datas=table.find_elements_by_tag_name('img') for img_data in img_datas: img_url=img_data.get_attribute('src') if "data:image" in img_url: continue print(img_url) img_name=img_url[img_url.rindex("/")+1:1000] img_num+=1 self.insert_img_data(prt_id, img_name, "", "详情", img_url, img_num) def insert_img_data(self,prt_id,img_name,img_path,type,original_url,img_num): db = pymysql.connect("localhost", "root", "123456", "vipmro", charset="utf8") cursor = db.cursor() sql = "insert into prt_img_info " \ " (prt_id,img_name,img_path,type,original_url,img_num)" \ " values('%s','%s','%s','%s','%s','%d')" \ % (prt_id,img_name,img_path,type,original_url,img_num) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": driver=webdriver.Firefox() url = "http://www.vipmro.com/login" driver.get(url) s(3,5) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) driver.get("http://www.vipmro.com/search?keyword=%25E4%25BC%258A%25E9%25A1%25BF%25E7%25A9%2586%25E5%258B%2592&brandId=210") s(3,5) driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() s(3,5) #遍历url,进入详情页 mysql=get_series_data() cnt=mysql.get_url_cnt() print("total %s records"%cnt) for i in range (int(cnt)): data=mysql.get_prt_url() prt_name=data[0][0] prt_url=data[0][1] prt_id=prt_url[prt_url.index("product/")+8:100] print(prt_id,prt_name,prt_url) try: driver.get(prt_url) s(3,5) #可以获取的数据 #商品标题、单价、市场价、品牌、订货号、商品型号、备注、属性 #1. 获取商品标题附近的数据 data=detail_data() #获取商品既有属性 data.get_main(prt_id,prt_url) s(2,4) #获取详情页的数据html内容 data.get_content(prt_id) s(2,4) #获取图片信息,大概要分为侧图、详情页图片 data.find_img(prt_id) s(5, 10) #因为html又经过js加载,选择不到正确的下拉框内容 #data.get_attrs() #s(5,10) status=1 except: status=2 mysql.update_status(prt_id, prt_url, status) print("--------------完成状态反馈----------------------------") <file_sep>/untitled/Selenium/test4+翻页2.py #coding=utf-8 import re import time import bs4 import xlsxwriter from untitled.Selenium import webdriver def main_info(page_source): bs_obj = bs4.BeautifulSoup(page_source, "html.parser") bs_div_title = bs_obj.findAll('div', attrs={'class': 'tit mt5'}) bs_div_price = bs_obj.findAll('div', attrs={'class': 'price clearfix'}) page_title = [[] for num in range(len(bs_div_title))] page_price = [[] for num in range(len(bs_div_price))] for i in range(0, len(bs_div_title)): page_title[i].append(bs_div_title[i].text) page_price[i].append(bs_div_price[i].text) page_title[i].append(page_price[i]) # 将title和price两个一维数组的数据整合成一个二维数组 return page_title #因为采用了先收集数据,然后一次性导入的方式,所以本处没有考虑到excel数据擦除问题 def save_excel(fin_result, file_name): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\%s.xlsx' % file_name) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') row_num = len(fin_result) for i in range(0, row_num): #print('##############') fin_a=fin_result[i] #从50*2的二维数组中,遍历i后获取的每个一维数组 for j in range(0, len(fin_a)): fin_b = fin_result[i][j] #print(fin_b) for k in fin_b: #print(k) tmp.write(i, j, k) tmp.write(i, 0, fin_result[i][0]) if __name__ == '__main__': driver = webdriver.PhantomJS() driver.get("http://search.mmbao.com") #1. 跳转到尾页 #2. 获取尾页的页码 #3. 将页码取出,作为最大的页数 driver.find_element_by_xpath("//div[@class='pagination pagewidget mt20']/a[contains(text(),'尾页')]").click() source=driver.page_source pages = bs4.BeautifulSoup(source,"html.parser") page=pages.findAll('div',attrs={'class':'pagination pagewidget mt20'}) page_num=pages.findAll('span',attrs={'class':'current'}) page_no=0 page_data=[] for i in range (0,1): page_no=re.sub('<[^>]+>','',str(page_num[i])) #通过substring将span标签去除,保留数字页码 print('共 %s 页记录' %(int(page_no))) driver.find_element_by_xpath("//div[@class='pagination pagewidget mt20']/a[contains(text(),'首页')]").click() #返回首页,从第一页重新开始 for i in range (0,int(page_no)): driver.find_element_by_xpath("//div[@class='pagination pagewidget mt20']/a[contains(text(),'下一页')]").click() time.sleep(3) page_source = driver.page_source print('第 %s 页列表记录' %(i+1)) page_title=main_info(page_source) print(page_title) page_data=page_data+page_title print(page_data) save_excel(page_data,'test1') <file_sep>/地址拆分/地址验证.py location_str = ["徐汇区虹漕路461号58号楼5楼", "泉州市洛江区万安塘西工业区", "朝阳区北苑华贸城"] from chinese_province_city_area_mapper.transformer import CPCATransformer cpca = CPCATransformer() df = cpca.transform(location_str) print(df)<file_sep>/ZYDMALL/zydmall产品价格调整监控/zydmall-列表内容获取V1.0.py #来源:"http://www.zydmall.com/brand/list_84.html" import requests import pymysql from bs4 import BeautifulSoup class sql_data(): def insert_goods_lists(self,good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand): db = pymysql.connect("localhost", "root", "123456", "zydmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into goods_lists_info(good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def find_prt_lists(html): soup = BeautifulSoup(html, 'html.parser') div_data = soup.find("div", attrs={'class': 'clearfix com_show_list listc333'}) div_lists = div_data.find_all("div", attrs={'class': 'item'}) # 获取数据 for div_list in div_lists: # good(SPU)商品详情url good_url = div_list.find('a', attrs={'class': 'pic'}).get('href').replace(" ", "") good_url = "http://www.zydmall.com" + good_url # good商品ID good_id = good_url[good_url.rindex('good_') + 5:good_url.rindex('.html')] list_img = div_list.find('a', attrs={'class': 'pic'}).find('img') original_pic = list_img.get('src').replace(" ", "") # 图片名称 pic_name = original_pic[original_pic.rindex('/') + 1:100] # 图片原始url original_pic_url = original_pic # 更新后的图片路径 pic_path = "/upload/prt/zyd/" + good_id + "/" + pic_name # print("","good_id:",good_id,"\n","good_url:",good_url,"\n","original_pic_url:",original_pic_url,"\n","pic_name:",pic_name,"\n","pic_path:",pic_path) title = div_list.find('a', attrs={'class': 'title'}).text good_price = div_list.find('span').text.replace(" ", "") cnt = div_list.find('i', attrs={'class': 'fl'}).text.replace(" ", "") brand = div_list.find('i', attrs={'class': 'fr'}).text.replace(" ", "") # print("", "title:", title, "\n", "good_price:", good_price, "\n", "cnt:", cnt, "\n", "brand:", brand,"\n") mysql_data = sql_data() mysql_data.insert_goods_lists(good_id, good_url, original_pic_url, pic_name, pic_path, title, good_price, cnt, brand) def get_pid(url): s = requests.get(url) content = s.content.decode('utf-8') print(content) return content if __name__=="__main__": #abb,79,12 #phoenix,85,10 #常熟,82,10 #人民,81,8 #施耐德,78,20 #西门子,80,16 #杭申,84,4 brand_id="78" #改ajax请求 page=18 for i in range (1,page+1): print("page%s"%str(i)) if i==1: url = "https://www.zydmall.com/ashx/brand_product_list.ashx?br=" + brand_id else: url="https://www.zydmall.com/ashx/brand_product_list.ashx?br="+brand_id+"&page="+str(i) content=get_pid(url) find_prt_lists(content) <file_sep>/MD5算法/MD5比较图片-1.py import hashlib image_file=open('C:\\Users\Administrator\PycharmProjects\MD5算法\\test3.jpg','rb').read() #print(image_file) checkcode1_md5=hashlib.md5(image_file).hexdigest() checkcode1_sha1=hashlib.sha1(image_file).hexdigest() print(checkcode1_md5,checkcode1_sha1) image_file2=open('C:\\Users\Administrator\PycharmProjects\MD5算法\\test2.jpg','rb').read() #print(image_file) checkcode2_md5=hashlib.md5(image_file2).hexdigest() checkcode2_sha1=hashlib.sha1(image_file2).hexdigest() print(checkcode2_md5,checkcode2_sha1) <file_sep>/Scrapy/tutorial/tutorial/spiders/DmozSpider.py import scrapy class DmozSpider(scrapy.Spider):#类的继承 #必须定义 name="dmoz" start_urls = [ "https://news.cnblogs.com/" ] # 默认response处理函数 def parse(self, response): # 把结果写到文件中 filename = response.url.split("/")[-2] with open(filename, 'wb') as f: f.write(response.body) <file_sep>/工品汇/伊顿电气-20170831/VIPMRO-伊顿电气-数据获取.py import pymysql from selenium import webdriver import time def login_url(uid,pwd): driver.find_element_by_css_selector('.login-name.u-b.J_name').send_keys(uid) driver.find_element_by_css_selector('.login-pwd.p-b.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.main-background-color.login-but.cursor.J_button').click() time.sleep(5) def t(seconds): time.sleep(seconds) def get_category(): cates1_name=[] cates1_url=[] a_cates_1=driver.find_elements_by_xpath("//li[@class='J_lb']/a") for a_cate_1 in a_cates_1: cate1_name=a_cate_1.text cate1_url=a_cate_1.get_attribute('href') #print(cate1_name,cate1_url) cates1_name.append(cate1_name) cates1_url.append(cate1_url) return cates1_name,cates1_url def insert_into_categorys(cate0_name,cate0_url,cate1_name,cate1_url): #再导入数据表之前,还需要拼个url存着 db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into vipmro_com_url " \ " (company_name,cate_0_name,cate_0_url,cate_1_name,cate_1_url)" \ " values('正泰','%s','%s','%s','%s')" \ % (cate0_name,cate0_url,cate1_name,cate1_url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) cursor.close() db.close() if __name__=="__main__": url="http://www.vipmro.com/login" browser="Firefox" if browser=="Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser=="Firefox": driver=webdriver.Firefox() else: driver=webdriver.PhantomJS() driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) print("------finish the login step---------") #开始正规数据 url="http://www.vipmro.com/search/?ram=0.13897850987391758&keyword=%25E6%25AD%25A3%25E6%25B3%25B0&brandId=105" driver.get(url) cates1_name, cates1_url=get_category() #进行第二批循环 print('进行第二批循环') for i in range(len(cates1_name)): driver.get(cates1_url[i]) t(1) cates2_name, cates2_url=get_category() print(len(cates2_name),len(cates2_url) ) if len(cates2_name)==0: insert_into_categorys(cates1_name[i], cates1_url[i], cates1_name[i], cates1_url[i]) else: for x in range(len(cates2_name)): insert_into_categorys(cates1_name[i],cates1_url[i],cates2_name[x],cates2_url[x]) <file_sep>/untitled/Selenium/测试select的用法.py import time import pymysql import xlsxwriter from untitled.Selenium import webdriver def prt_content(): driver.get(r"file:///C:/Users/Administrator/Desktop/TEST.html") time.sleep(2) prt_info=driver.find_elements_by_xpath("//div[@id='listContents']/table[@id='ListTable']/tbody/tr/td[@class='model']") print(str(len(prt_info))) for i in range(len(prt_info)): prt_name=prt_info[i].text print(prt_name) mysql_insert(prt_name) #上面是一页结束 #判断当前的页数 page_num1=driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text print(page_num1) if next_pg!="none": next_page(page_num1) page_num1=page_num1+1 print(page_num1) def next_page(page_num): try: driver.find_element_by_id('detail_codeList_pager_lower_right').click() time.sleep(10) page_num2 = driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text print(page_num2) if page_num2!=page_num: prt_content() else: time.sleep(20) prt_content() except: next_pg="none" print("error,已到底页") def save_prt_name(fin_result1): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'D:\BI\米思米\test_prt_name.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet1') for i in range(0, len(fin_result1)): tmp.write(i, 0, fin_result1[i]) def mysql_insert(prt_name): db = pymysql.connect("192.168.180.147","root","1<PASSWORD>","test01" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql="insert into misumi" \ " (PRT_NAME)" \ " values('%s')" \ % (prt_name) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() #print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:'+err) # 关闭数据库连接 db.close() if __name__=="__main__": prt_1=[] next_pg="" driver=webdriver.Firefox() print('loading...进入品牌页面...') prt_content() save_prt_name(prt_1) <file_sep>/TMALL/罗格朗/将详情url调整图片增补.py import pymysql from bs4 import BeautifulSoup def get_prt_desc(): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select prt_id,prt_desc from legrand_prt_desc " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_prt_desc(prt_id,img_url,new_img_url): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update legrand_prt_desc set prt_desc=replace(prt_desc,'%s','%s') where prt_id='%s'" %(img_url,new_img_url,prt_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_prt_img(prt_id,img_url,img_type): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into legrand_prt_img (prt_id,img_url,img_type) values('%s','%s','%s')" %(prt_id,img_url,img_type) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": data_desc=get_prt_desc() for i in range (len(data_desc)): prt_id=data_desc[i][0] prt_desc=data_desc[i][1] print(prt_id) html="<html><head></head><body>"+prt_desc+"</body></html>" soup=BeautifulSoup(html,'html.parser') imgs=soup.find_all("img") for x in range (len(imgs)): img_url=imgs[x].get('data-ks-lazyload') print(img_url) insert_prt_img(prt_id,img_url,"desc_img") <file_sep>/untitled/Selenium/工品汇/main.py from Login import login if __name__ == '__main__': url='http://www.vipmro.net/login' uid='18861779873' pwd='<PASSWORD>' #完成登录 source=login.login_url(url,uid,pwd) <file_sep>/工品汇/工品汇-获取库存数据/工品汇2.1-main.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver def company_info(): company_name="正泰" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) def get_main_data(company_name,url): J_searchLists=driver.find_elements_by_xpath("//div[@class='J_searchList']/ul") for Searchlist in J_searchLists: img_url=Searchlist.find_element_by_xpath("./li[@class='a']/a/img").get_attribute('src') prt_name=Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").text prt_url =Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").get_attribute('href') prt_id = prt_url[prt_url.index("product/") + 8:100] prt_type=Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[0].text order = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[1].text try: price=Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='a']").text except: price="" try: market_price = Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='b']").text except: market_price="" stock=Searchlist.find_element_by_xpath("./li[@class='f']").text print(img_url,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock) insert_data1(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock,url) def insert_data1(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock,url): #company_name=company_info() db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into vipmro_net_data (company_name,prt_id,prt_name,prt_url,prt_type,order_,price,market_price,stock,cate_2_url)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,stock,url) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def next_page(j): time.sleep(4) xpath_data="//div[@class='saas-paging J_paging']/a[@class='J_page_turn'][@page-id='"+str(j+2)+"']" print(xpath_data) driver.find_element_by_xpath(xpath_data).click() time.sleep(4) def get_url_status(): #company_name=company_info() db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select case when cate_2_url='' then cate_1_url else cate_2_url end as url,company_name from vipmro_net_url where status=0 order by table_id limit 1 " try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(url,last_page): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_net_url set status=1,total_page='%s' where cate_2_url='%s' or cate_1_url='%s' " \ % (last_page,url,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() if __name__=="__main__": browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() url = "http://www.vipmro.net/login" driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) #完成登录 #点击一下搜索按钮,使页面正确加载url #driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() driver.get("http://www.vipmro.net/search?keyword=%25E6%2596%25BD%25E8%2580%2590%25E5%25BE%25B7") time.sleep(2) driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() time.sleep(4) for i in range (800): data=get_url_status() url=data[0][0] company_name=data[0][1] #url=str(url_t).replace("(('","").replace("',),)","") print(company_name,url) #url=u'http://www.vipmro.net/search?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&categoryId=50101811' driver.get(url) time.sleep(5) last_page=driver.find_element_by_css_selector('.J_page_sum.t_num').text print(last_page) for j in range(15): get_main_data(company_name,url) try: next_page(j) except: print("没有下一页") break update_status_to_run_log(url,last_page) <file_sep>/javmoo/magnet_search.py import pymysql import requests import time import urllib import random from bs4 import BeautifulSoup from urllib import parse class magnet_data(): def s(self,a,b): x_time=random.randint(a,b) time.sleep(x_time) # 从url中获取json的那块源码,以及整体的html源码 def get_content(self, url): s = requests.get(url, headers=headers) content = s.content.decode('utf-8') #print(content) return content def get_basic_info(self): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select table_id,film_id,designation from film_basic_info where status=1" # print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as e: db.rollback() print('------get_basic_info---------Error------Message--------:' + str(e)) cursor.close() db.close() def get_float_data(self,hash_size): if "GB" in hash_size: size = float(hash_size.split('GB')[0]) * 1024 #print(size) elif "MB" in hash_size: size = float(hash_size.split('MB')[0]) else: size=float(0) #print(size) return size def find_hash_info(self,table_id,film_id,content): soup=BeautifulSoup(content,'html.parser') try: rows=soup.find('div',attrs={'class':'data-list'}).find_all('div',attrs={'class':'row'}) except AttributeError as e: rows="" if str(rows)!="": print(str(len(rows))) original_hash_size = rows[1].find('div', attrs={'class': 'col-sm-2 col-lg-1 hidden-xs text-right size'}).text original_size = self.get_float_data(original_hash_size) original_hash_href = rows[1].find('a').get('href') for x in range(len(rows)): # print(rows[x]) try: hash_href = rows[x].find('a').get('href') hash_title = rows[x].find('a').get('title') hash_size = rows[x].find('div', attrs={'class': 'col-sm-2 col-lg-1 hidden-xs text-right size'}).text hash_date = rows[x].find('div', attrs={'class': 'col-sm-2 col-lg-2 hidden-xs text-right date'}).text print(hash_href, hash_title, hash_size, hash_date) magnet_txt = "magnet:?xt=urn:btih:" + hash_href.split("/")[-1] + "&dn=" + urllib.parse.quote(hash_title) # print(magnet_txt) # 对数据进行比较 size = self.get_float_data(hash_size) if original_size > size: pass else: original_size = size original_hash_href = hash_href self.insert_magnet_data(table_id, film_id, hash_href, hash_title, hash_size, hash_date, magnet_txt) except AttributeError as e: pass self.update_optimum_record(original_hash_href) def insert_magnet_data(self,table_id,film_id,hash_href,hash_title,hash_size,hash_date,magnet_txt): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into magnet_info (table_id,film_id,hash_href,hash_title,hash_size,hash_date,magnet_txt)"\ "values('%s','%s','%s','%s','%s','%s','%s')"\ %(table_id,film_id,hash_href,hash_title,hash_size,hash_date,magnet_txt) # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------insert_magnet_data---------Error------Message--------:' + str(e)) cursor.close() db.close() def update_optimum_record(self,optimum_hash_href): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update magnet_info set status=1 where hash_href='%s' " %optimum_hash_href # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------update_optimum_record---------Error------Message--------:' + str(e)) cursor.close() db.close() def update_status(self,table_id,status): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update film_basic_info set status='%d' where table_id='%d' "%(status,table_id) # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------update_status---------Error------Message--------:' + str(e)) cursor.close() db.close() if __name__=="__main__": headers = { "Host": "btso.pw", "Accept": "text/html,application/xhtml+xml,application/xml;", "Accept-Encoding": "gzip", "Accept-Language": "zh-CN,zh;q=0.8", "Referer": "https://javmoo.net/", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } #从mysql获取影片的基础信息 detail=magnet_data() basic_data=detail.get_basic_info() for i in range (len(basic_data)): print(str(i+1)) table_id = basic_data[i][0] film_id = basic_data[i][1] designation = basic_data[i][2] #designation="IPZ-921" #通过这三个字段,去获取详情页内容 bt_url="https://btso.pw/search/"+designation print(bt_url) content=detail.get_content(bt_url) detail.find_hash_info(table_id,film_id,content) # 修改状态 status = 2 detail.update_status(table_id, status) detail.s(1,6)<file_sep>/JD/列表页数据获取/列表页销量评价获取.py import pymysql from bs4 import BeautifulSoup from selenium import webdriver import time import re def get_useful_data(html): soup=BeautifulSoup(html,'html.parser') prt_divs=soup.find_all('li',attrs={'class':re.compile('gl-item')}) print("current page have %s records"%str(len(prt_divs))) for prt_div in prt_divs: prt_price=prt_div.find('div',attrs={'class':'p-price'}).text print("prt_price",prt_price) prt_title = prt_div.find('div', attrs={'class': 'p-name p-name-type-2'}).find('em').text print("prt_title", prt_title) prt_url = prt_div.find('div', attrs={'class': 'p-name p-name-type-2'}).find('a').get('href') print("prt_url", prt_url) #//detail.tmall.com/item.htm?id=524785657239&skuId=3573590028479&areaId=320200&user_id=923873351&cat_id=50067923&is_b=1&rn=a36346c54fc20f2a4d2dbed860331aa9 prt_id = prt_url.split('/')[-1].replace(".html","") print("prt_id", prt_id) #print("prt_id",prt_id) prt_shop = prt_div.find('div', attrs={'class': 'p-shop'}).find('a').text print("prt_shop", prt_shop) #prt_sales = prt_div.find('div', attrs={'class': 'deal-cnt'}).text prt_evaluations = prt_div.find('div', attrs={'class': 'p-commit'}).find('a').text print("prt_sales,prt_evaluations", "",prt_evaluations) insert_prt_lists_data(prt_id, prt_url, prt_title, prt_price, prt_shop, "", prt_evaluations) def insert_prt_lists_data(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations): prt_title=prt_title.replace("\n","") prt_shop=prt_shop.replace("\n","") db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_lists_info (prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) values('%s','%s','%s','%s','%s','%s','%s')" \ %(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_prt_lists_data--------Error------Message--------:' + str(err)) cursor.close() db.close() def next_page(num): driver.find_element_by_class_name('fp-next').click() time.sleep(3) try: page_num=driver.find_element_by_class_name("ui-page-s-len").text print(page_num) page_num=page_num.split("/")[0] current_page=num+2 if current_page==page_num: print("success") except: temp = input("tmp") if __name__=="__main__": url="https://search.jd.com/Search?keyword=%E7%BD%97%E6%A0%BC%E6%9C%97&enc=utf-8&wq=%E7%BD%97%E6%A0%BC%E6%9C%97&pvid=2638176df320407fad9e5310a9c38c20" #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) temp = input("tmp") #将html带入到函数进行分析 for i in range(100): html = driver.page_source get_useful_data(html) next_page(i) <file_sep>/untitled/Selenium/dq123/dq123商品信息2.0-大版本更新.py import pymysql import time import re import logging logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(levelname)s - %(message)s') from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait def swith_tab(): logging.debug("开始切换标签") try: tab=wait1.until(EC.presence_of_element_located((By.ID,"showhidediv1"))) tab.click() except TimeoutException: return swith_tab() def click_catgory(): list = driver.find_element_by_id("classlibiao") list.find_element_by_link_text(category1).click() if __name__=="__main__": #定义函数 category1="互感器" category2 = "限流电抗器" ##这里使用PhantomJS,并配置了一些参数 driver = webdriver.Firefox() ##窗口的大小,不设置的话,默认太小,会有问题 #driver.set_window_size(1400, 900) #载入url,点击列表选型 driver.get("http://www.dq123.com/price/index.php") wait1 = WebDriverWait(driver, 15) time.sleep(15) swith_tab() #time.sleep(3) #click_catgory() # 1. 选择对应的产品目录 #点击到二级类目下的列表 <file_sep>/OA_FEGROUP/日报提醒助手_1.0.py import requests import base64 from bs4 import BeautifulSoup from utils import AliyunSMS import pymysql import time import random def s(a,b): time_=random.randint(a,b) time.sleep(time_) def get_content(url): s = requests.get(url,headers=headers) content = s.content.decode('gbk') print(content) cookie = s.cookies #print(cookie) return content,cookie def find_data_from_content(content): soup=BeautifulSoup(content,'html.parser') liNoSubmit=soup.find('li',attrs={'id':'liNoSubmit'}).text #print(liNoSubmit.replace(" ","")) liNo=liNoSubmit.replace("未提交(","").replace(")","") return liNo def get_login_data(): db = pymysql.connect("localhost", "root", "123456", "oa_msg") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select user_name,password,hidEpsKeyCode,phone_num from oa_login_info where status=1 " #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as e: db.rollback() print('------table_data_delete---------Error------Message--------:' + str(e)) cursor.close() db.close() if __name__=="__main__": headers = { "Host" : "oa.fegroup.cn:8090", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer" : "http://oa.fegroup.cn:8090/c6/jhsoft.web.ydmh/myindex.aspx?moduleid=01400030", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" } # post发送的数据 #从mysql获取oa登录信息 login_data=get_login_data() for i in range (len(login_data)): user_name=login_data[i][0] password=login_data[i][1] hidEpsKeyCode=login_data[i][2] phone_num=login_data[i][3] #用户名密码作BASE64处理 loginCode=base64.b64encode(user_name.encode(encoding='utf-8')) pwd=base64.b64encode(password.encode(encoding='utf-8')) loginCode=str(loginCode).split("'")[1] pwd=str(pwd).split("'")[1] #print(loginCode,pwd) url=u'http://oa.fegroup.cn:8090/c6/Jhsoft.Web.login/AjaxForLogin.aspx?type=login&loginCode=%s&pwd=%s&hidEpsKeyCode=%s' %(loginCode,pwd,hidEpsKeyCode) #print(url) content,cookie=get_content(url) report_url="http://oa.fegroup.cn:8090/c6/JHSoft.web.Aging/ReportMG.aspx" result=requests.get(report_url,cookies=cookie) content=result.content.decode('gbk') liNo=find_data_from_content(content) if int(liNo)>=1: print("有%s条未提交的报表"%str(int(liNo))) times=str(int(liNo)) sms = AliyunSMS() params = {"times": times } # 这就是随机生成的6位数 sms.send_single(phone=phone_num, sign="小旋风", template='SMS_130913150', params=params) s(1,8) <file_sep>/untitled/Selenium/米思米/从保存到本地的结果集中获得list.py import time import pymysql from untitled.Selenium import webdriver def mysql_insert(prt_num, prt_name, prt_brand, sale_price, face_price): db = pymysql.connect("192.168.180.147", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 # sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql = "insert into misumi_price " \ " (name_1,name_2,cate,brand,price_1,price_2)" \ " values('%s','%s','%s','%s','%s','%s')" \ % (prt_num, prt_num, prt_name, prt_brand, sale_price, face_price) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + err) # 关闭数据库连接 db.close() def main(num): table = driver.find_element_by_xpath("//div[@class='tableGreen marginT10']/table[@class='marginT1']") for i in range(num): print( str(i +1) + '/' + str(num) ) # price price = table.find_element_by_xpath("//tbody[@id='detail_" + str(i) + "']/tr/td[6]").text #print(price) price = price.split("\n") try: price_1 = price[0] except: price_1 = "NULL" try: price_2 = price[1] except: price_2 = "NULL" # product_name product_name = table.find_element_by_xpath("//tbody[@id='detail_" + str(i) + "']/tr/td[3]").text #print(product_name) product_name = product_name.split("\n") try: product_name_1 = product_name[0] except: product_name_1 = "NULL" # prt_no prt_num = table.find_element_by_id("detailList_" + str(i) + ".customerSubReference2").get_attribute("value") #print(prt_num) # brand brand_name = table.find_element_by_id("detailList_" + str(i) + ".brandName").get_attribute("value") #print(brand_name) #print("\n") # 筛选出所有的有用字段,然后进行数据库的操作 mysql_insert(prt_num, product_name_1, brand_name, price_1, price_2) if __name__=="__main__": num=[500,500,500,500,484,500,383] for i in range(6,7): driver=webdriver.Firefox() url=r"file:///C:/Users/Administrator/Documents/temp_MISIMI/"+str(i+1)+".html" driver.get(url) page=driver.page_source #print(page) time.sleep(5) main(num[i]) #print(price_1+'>'+price_2+'>'+name_1) <file_sep>/javmoo/film_detail.py import pymysql from bs4 import BeautifulSoup import requests import time class detail_data(): # 从url中获取json的那块源码,以及整体的html源码 def get_content(self, url): s = requests.get(url, headers=headers) content = s.content.decode('utf-8') # print(content) return content def get_basic_info(self): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select table_id,film_id,film_href from film_basic_info where status=0" # print(sql) try: execute=cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as e: db.rollback() print('------get_basic_info---------Error------Message--------:' + str(e)) cursor.close() db.close() def find_useful_details(self,table_id,film_id,content): soup=BeautifulSoup(content,'html.parser') try: big_img=soup.find('a',attrs={'class':'bigImage'}).get('href') div_p=soup.find('div',attrs={'class':'col-md-3 info'}).find_all('p') #一般来说,会有四个 for x in range (len(div_p)): #print(div_p[x]) pass film_length=div_p[2].text try: film_director = div_p[3].text film_producer = div_p[5].text film_publisher = div_p[7].text film_series = div_p[9].text film_type = div_p[11].text except IndexError as e: film_director = '' film_producer = '' film_publisher = '' film_series = '' film_type = div_p[-1].text print(film_length,film_director,film_producer,film_publisher,film_series,film_type) self.insert_film_detail(table_id,film_id,big_img,film_length,film_director,film_producer,film_publisher,film_series,film_type) except AttributeError as e: pass #simple images simple_imgs=soup.find_all('a',attrs={'class':'sample-box'}) for x in range (len(simple_imgs)): img_url=simple_imgs[x].get('href') img_title=simple_imgs[x].get('title') #print(img_url,img_title) img_num=x+1 #将详情图保存到表 self.insert_simple_imgs(table_id,film_id,img_url,img_title,img_num) def insert_simple_imgs(self,table_id,film_id,img_url,img_title,img_num): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into film_simple_imgs(table_id,film_id,img_url,img_title,img_num)" \ "values('%s','%s','%s','%s','%d')" \ %(table_id,film_id,img_url,img_title,img_num) # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------insert_simple_imgs---------Error------Message--------:' + str(e)) cursor.close() db.close() def insert_film_detail(self,table_id,film_id,big_img,film_length,film_director,film_producer,film_publisher,film_series,film_type): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into film_detail_info(table_id,film_id,big_img,film_length,film_director,film_producer,film_publisher,film_series,film_type)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(table_id,film_id,big_img,film_length,film_director,film_producer,film_publisher,film_series,film_type) # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------insert_film_detail---------Error------Message--------:' + str(e)) cursor.close() db.close() def update_status(self,table_id,status): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update film_basic_info set status='%d' where table_id='%d' "%(status,table_id) # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------update_status---------Error------Message--------:' + str(e)) cursor.close() db.close() if __name__=="__main__": headers = { "Host": "javmoo.net", "Accept": "text/html,application/xhtml+xml,application/xml;", "Accept-Encoding": "gzip", "Accept-Language": "zh-CN,zh;q=0.8", "Referer": "https://javmoo.net/", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } #从mysql获取影片的基础信息 detail=detail_data() basic_data=detail.get_basic_info() for i in range (len(basic_data)): print(str(i+1)) table_id = basic_data[i][0] film_id = basic_data[i][1] film_href = basic_data[i][2] #通过这三个字段,去获取详情页内容 content=detail.get_content(film_href) #print(content) detail.find_useful_details(table_id,film_id,content) #修改状态 status=1 detail.update_status(table_id,status) <file_sep>/MMBAO/众业达价格更新/众业达价格更新-V1.0.py import pymysql import cx_Oracle def get_mysql_data(): db = pymysql.connect("localhost", "root", "123456", "zyd", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select spu_id,spu_title,po_number,type_name,face_price from face_price_update where brand_name like '%西门子%' " #where attr_name!='系列' and attr_val_id='' try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('-------get_data_from_mysql--------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_attr_id(po_number): #db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.mmbao.com:21252/mmbao2b2c') db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.31.10:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "select id,prt_id,old_price,sku_title FROM mmbao2.t_prt_sku WHERE po_number='"+po_number+"' AND sku_title LIKE '%西门子%' " # and create_date>to_date('%s','yy/MM/dd') # 因为还得分为新增和更新 # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data if __name__=="__main__": mysql_data=get_mysql_data() for i in range (len(mysql_data)): spu_id=mysql_data[i][0] spu_title=mysql_data[i][1] po_number=mysql_data[i][2] type_name=mysql_data[i][3] face_price=mysql_data[i][4] #到oracle进行查询 oracle_data=find_attr_id(po_number) try: sku_id=oracle_data[0][0] prt_id=oracle_data[0][1] old_price=oracle_data[0][2] sku_title=oracle_data[0][3] if round(float(face_price),2)==float(old_price): pass else: print(spu_id,po_number,sku_id,prt_id,old_price,face_price,sku_title) except IndexError as e: pass <file_sep>/suning/罗格朗/legrand-数据获取(美涵)v1.0.py #https://legrand.suning.com/ #罗格朗官方旗舰店 #有逸景、逸典、 #美涵在旗舰店上有,不过可能要根据数据进行调整 import pymysql import urllib.request import requests from selenium import webdriver from bs4 import BeautifulSoup import time #使用request处理 class get_data_from_suning(): # 获取html函数,参数:url def getHtml(self, url): req = urllib.request.Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/47.0") response = urllib.request.urlopen(req) html = response.read().decode('utf-8') # print(html) return html def get_lists(self,html): soup=BeautifulSoup(html,'html.parser') prt_lists=soup.find('div',attrs={'class':'sf-product sf-product2'}).find_all('p',attrs={'class':'sf-proName'}) print("当前页一共%s条记录"%str(len(prt_lists))) for prt_list in prt_lists: prt_href=prt_list.find('a').get_text() prt_hrefs.append(prt_href) if __name__=="__main__": suning_data=get_data_from_suning() url="https://tcl-legrang.suning.com/search/%E7%BE%8E%E6%B6%B5.html" #url = "https://product.suning.com/0070162407/616881924.html" prt_hrefs=[] browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) html=driver.page_source #print(html) for i in range (2): suning_data.get_lists(html) try: driver.find_element_by_class_name('sf-nfilterPageNext').click() time.sleep(3) except: pass html=driver.page_source for prt_href in prt_hrefs: print(prt_href) <file_sep>/untitled/Selenium/dq123/dq123商品信息1.0.py #1.0 版本,完成基本的数据获取/导入MYSQL操作 #1.1版本,需要加入翻页功能,设定20页数据即可(用于多主机分布获取) from selenium import webdriver import time from selenium.webdriver.support.ui import WebDriverWait import pymysql def insert_mysql(id,prt_name,price,company,issuedate,series,detail): try: tmp0=detail[0] except: tmp0="NULL" try: tmp1=detail[1] except: tmp1="NULL" try: tmp2=detail[2] except: tmp2="NULL" try: tmp3=detail[3] except: tmp3="NULL" try: tmp4=detail[4] except: tmp4="NULL" try: tmp5=detail[5] except: tmp5="NULL" try: tmp6=detail[6] except: tmp6="NULL" try: tmp7=detail[7] except: tmp7="NULL" try: tmp8=detail[8] except: tmp8="NULL" try: tmp9=detail[9] except: tmp9="NULL" try: tmp10=detail[10] except: tmp10="NULL" try: tmp11=detail[11] except: tmp11="NULL" try: tmp12=detail[12] except: tmp12="NULL" try: tmp13=detail[13] except: tmp13="NULL" try: tmp14=detail[14] except: tmp14="NULL" try: tmp15=detail[15] except: tmp15="NULL" try: tmp16=detail[16] except: tmp16="NULL" try: tmp17=detail[17] except: tmp17="NULL" try: tmp18=detail[18] except: tmp18="NULL" try: tmp19=detail[19] except: tmp19="NULL" db = pymysql.connect("192.168.180.147", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into DQ123PRTINFO" \ " (PRT_ID,PRT_NAME,PRICE,COMPANY,RELEASE_DATE,SERIES,TYPE1,VALUE1,TYPE2,VALUE2,TYPE3,VALUE3,TYPE4,VALUE4,TYPE5,VALUE5,TYPE6,VALUE6,TYPE7,VALUE7,TYPE8,VALUE8,TYPE9,VALUE9,TYPE10,VALUE10)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (id,prt_name,price,company,issuedate,series,tmp0,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9,tmp10,tmp11,tmp12,tmp13,tmp14,tmp15,tmp16,tmp17,tmp18,tmp19,) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + err) # 关闭数据库连接 db.close() if __name__=="__main__": #定义函数 detail=[] #载入url,点击列表选型 driver=webdriver.Firefox() driver.get("http://www.dq123.com/price/index.php") time.sleep(10) driver.find_element_by_id("showhidediv1").click() time.sleep(10) page=driver.page_source print(driver.current_url) #1. 获取整个产品目录,然后进行遍历,一个脚本循环20次,防止异常 list_1=driver.find_element_by_xpath("//table[@class='yjtbs']/tbody[@id='part_list']") tr=list_1.find_elements_by_tag_name("tr") print(len(tr)) for i in range(len(tr)): try: colunm = tr[i].find_elements_by_tag_name("td") except: time.sleep(5) colunm = tr[i].find_elements_by_tag_name("td") #print(len(colunm)) # 获取序号、商品名、价格、制造商 td1=colunm[0].text td2 = colunm[1].text td3 = colunm[2].text td4 = colunm[3].text print(td1+"//"+td2+"//"+td3+"//"+td4) #点击事件 colunm[1].find_element_by_tag_name("a").click() time.sleep(5) #准备获取商品的规格信息 #发布日期 issuedate=driver.find_element_by_id("fissuedate").text series=driver.find_element_by_xpath("//input[@id='classSelele']").get_attribute("value") print(series) body=driver.find_element_by_id("Part_MainProp") #规格属性所在的div type=body.find_elements_by_xpath("div[@class='prop_part']") #print("total "+str(len(type))+" for type") for x in range(len(type)): # 规格属性 type_name=type[x].find_element_by_tag_name("label").text type_value=type[x].find_element_by_xpath("div[@class='prop_list']/span[@class='opt_s opt_s opt_s_ch']").text detail.append(type_name) detail.append(type_value) #print(type_name+" : "+type_value) #print(detail) print("共"+str(len(detail)/2)+"条规格属性") insert_mysql(td1,td2,td3,td4,issuedate,series,detail) print("此条记录已导入") detail=[] #返回整个产品目录 driver.find_element_by_id("showhidediv1").click() time.sleep(5) <file_sep>/SIMON商城/模拟登陆.py import requests from bs4 import BeautifulSoup from selenium import webdriver import time,random import pymysql def s(a,b): tt=random.randint(a,b) time.sleep(tt) def get_lists(): db = pymysql.connect("localhost", "root", "123456", "simon_shop") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select table_id,url from simon_prt_lists where status=0 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_img_info(prt_id,img_name,img_path): db = pymysql.connect("localhost", "root", "123456", "simon_shop") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into simon_prt_imgs (prt_id,img_name,img_path) values('%s','%s','%s')" %(prt_id,img_name,img_path) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_basic_info(prt_id,prt_title,po_number,erp_price): db = pymysql.connect("localhost", "root", "123456", "simon_shop") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into simon_prt_info (prt_id,prt_title,po_number,erp_price) values('%s','%s','%s','%s')" % (prt_id,prt_title,po_number,erp_price) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(table_id): db = pymysql.connect("localhost", "root", "123456", "simon_shop") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update simon_prt_lists set status=1 where table_id='%s' " %table_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": browser = "Chrome" if browser == "Chrome": driver = webdriver.Chrome() else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() login_url="http://c9.simon.com.cn/Login.aspx" driver.get(login_url) s(2,5) driver.find_element_by_id("txtUserName").clear() driver.find_element_by_id("txtUserName").send_keys("c1-2488") driver.find_element_by_id("txtPassWord").clear() driver.find_element_by_id("txtPassWord").send_keys("123456") s(2,4) driver.find_element_by_id("btn_login").click() s(5, 8) prt_data=get_lists() for i in range(len(prt_data)): table_id=prt_data[i][0] prt_url=prt_data[i][1] driver.get(prt_url) s(11, 15) prt_title=driver.find_element_by_id("dProductTitle").text erp_price = driver.find_element_by_id("tdPrice").text po_number=driver.find_element_by_id("tdItemCode").text img_lists=driver.find_elements_by_xpath("//ul[@id='ulImageList']/li") for x in range (len(img_lists)): img_name=img_lists[x].get_attribute('pic') img_path="http://c9.simon.com.cn/uploadImage/ProImgForDetailSlide/"+img_name insert_img_info(table_id,img_name,img_path) insert_basic_info(table_id,prt_title,po_number,erp_price) update_status(table_id) <file_sep>/JD后台/VC后台/获取前台的京东价.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 driver = webdriver.Chrome() else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) prt_data=self.get_sku_id() for i in range (len(prt_data)): sku_id=prt_data[i][0] print(sku_id) driver.find_element_by_id('wareId').clear() driver.find_element_by_id('wareId').send_keys(sku_id) self.s(1,2) driver.find_element_by_css_selector('.btn.btn-primary').click() self.s(2,3) nowhandle = driver.current_window_handle # 在这里得到当前窗口句柄 btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_wareId']/div/button[@class='btn btn-default']" driver.find_element_by_xpath(btn_down_path).click() self.s(5, 6) # 需要获取新弹开的窗口 allhandles = driver.window_handles # 获取所有窗口句柄 for handle in allhandles: # 在所有窗口中查找弹出窗口 if handle != nowhandle: driver.close() driver.switch_to.window(handle) current_url = driver.current_url print(current_url) driver.get(current_url) content = driver.page_source # print(content) self.s(3, 4) driver.find_element_by_id('cid3Submit').click() self.s(3, 5) # 获取京东价市场价 market_price = driver.find_element_by_xpath( "//tr[@class='sensitiveField'][5]/td").text jd_price = driver.find_element_by_xpath( "//tr[@class='sensitiveField'][6]/td").text print(jd_price, market_price) self.update_caigou_price(sku_id,jd_price,market_price) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) def get_sku_id(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 主商品编号 from jiazhuang_caigoujia where 市场价 is null" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_caigou_price(self,sku_id,jd_price,market_price): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update jiazhuang_caigoujia set 京东价='%s',市场价='%s' where 主商品编号 ='%s'" %(jd_price,market_price,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/suning/罗格朗/从数据表中的ID复制文件到新文件夹.py import os import urllib.request import pymysql import sys import shutil def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "legrand") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select spu_id from spu表 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName return totalPath if __name__=="__main__": data = get_prt_data() for i in range (len(data)): prt_id = data[i][0] print(prt_id) file_path = u"D:\BI\LEGRAND\\upload-suning\prt\good_img" file_path2 = u"D:\BI\LEGRAND\\upload-suning\prt\good_img_逸典" old = file_path +"\\"+prt_id new=file_path2+"\\"+prt_id print("old",old,"new",new) shutil.copytree(old, new) <file_sep>/待自动化运行脚本/zydmall_数据监控/数据转换_brand_list.py import pymysql def get_brand_name(): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select brand_name from brand_list group by brand_name" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_brand_info(brand_name): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select brand_name,page_num,total_num,md5,control_date from brand_list where brand_name='%s' order by control_date" %brand_name try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_d_value(brand_name,d_value,control_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update brand_list set d_value='%s' where brand_name='%s' and control_date='%s' " % (d_value,brand_name,control_date) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": brand_names=get_brand_name() for i in range (len(brand_names)): brand_name=brand_names[i][0] brand_info=get_brand_info(brand_name) #print(brand_info) original_total_num=brand_info[0][2] for x in range (len(brand_info)): page_num=brand_info[x][1] total_num = brand_info[x][2] control_date=brand_info[x][4] d_value=int(total_num)-int(original_total_num) print(d_value) update_d_value(brand_name,d_value,control_date) <file_sep>/untitled/Selenium/test-fanye.py #存在漏洞,第三页翻不了 # -*- coding: utf-8 -*- import time from untitled.Selenium import webdriver if __name__ == "__main__": driver = webdriver.Firefox() driver.maximize_window() driver.get('http://www.baidu.com') driver.implicitly_wait(5) driver.find_element_by_id('kw').send_keys('selenium') driver.find_element_by_id('su').click() page = driver.find_element_by_id('page') pages = page.find_elements_by_tag_name('a') #查找所有翻页跳转链接 #设置滚动条位置为底部 js = 'document.documentElement.scrollTop=10000' for each in pages: driver.execute_script(js) #拖动滚动条到底部 each.click() driver.execute_script(js) time.sleep(3) driver.quit()<file_sep>/TMALL/数据分析架构模式化/针对legrand进行流交互尝试/test2.py import pymysql import time import logging import requests import random import re import json import html import urllib.parse from bs4 import BeautifulSoup def s(a, b): t = random.randint(a, b) time.sleep(t) class dispose_of_history_data(): # 将所有的状态都置为0 def update_original_executable_data_status(self): db = pymysql.connect("localhost", "root", "<PASSWORD>", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_lists set status=0" try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------update_original_executable_data_status---------Error------Message--------:' + str(e)) cursor.close() db.close() def filed_data(self): # 因为有多张表,所以就要单独设计一个通用的delete,insert函数 new_table_name_lists = ['tmall_simon.prt_lists', 'tmall_simon.prt_attribute', 'tmall_simon.prt_img', 'tmall_simon.sku_info', 'tmall_simon.spu_info'] old_table_name_lists = ['tmall.prt_lists', 'tmall.prt_attribute', 'tmall.prt_img', 'tmall.sku_info', 'tmall.spu_info'] for i in range(len(new_table_name_lists)): new_table_name = new_table_name_lists[i] old_table_name = old_table_name_lists[i] self.create_new_table(new_table_name, old_table_name) self.table_operation(new_table_name, old_table_name) self.table_data_delete(old_table_name) time.sleep(0.1) def table_data_delete(self, old_table_name): if old_table_name == "tmall.prt_lists": pass else: db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "delete from " + old_table_name # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------table_data_delete---------Error------Message--------:' + str(e)) cursor.close() db.close() def table_operation(self, new_table_name, old_table_name): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into " + new_table_name + " select * from " + old_table_name # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------update_original_executable_data_status---------Error------Message--------:' + str(e)) cursor.close() db.close() def create_new_table(self, new_table_name, old_table_name): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "create table " + new_table_name + " like " + old_table_name # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print(str(e)) cursor.close() db.close() class tmall_data_procurement(): # 从url中获取json的那块源码,以及整体的html源码 def get_content(self, url): s = requests.get(url, headers=headers) content = s.content.decode('gbk') cookie = s.cookies print(cookie) try: data = re.findall('TShop.Setup[\s\S]+J_SpuMore_Act', content) # print(data) data = data[0].replace("TShop.Setup(\r\n\t \t", "").replace("\r\n", "").replace("\n", "").replace( ' );})();</script></div><!-- ruleBanner--> <script id="J_SpuMore_Act', "") print(data) # 完成json的整体取出 except IndexError as e: data = '' pass return data, content, cookie # 从json中获取数据 def find_json_info(self, json_data, content): items = json.loads(json_data) prt_title = items['itemDO']['title'] print("prt_title", prt_title) ############################################################# sellerNickName = items['itemDO']['sellerNickName'] # 解码 sellerNickName = urllib.parse.unquote(sellerNickName) print("sellerNickName", sellerNickName) ############################################################# provience = items['itemDO']['prov'] print("provience", provience) ############################################################# brand_name = items['itemDO']['brand'] brand_name = html.unescape(brand_name) print("brand_name", brand_name) ############################################################# brand_id = items['itemDO']['brandId'] print("brand_id", brand_id) ############################################################# sell_count_url = items['initApi'] sell_count_url = "https:" + sell_count_url # 调用请求 print(sell_count_url) sell_count = self.find_sell_count(sell_count_url, cookie) ############################################################# itemId = items['itemDO']['itemId'] spuId = items['itemDO']['spuId'] sellerId = items['rateConfig']['sellerId'] _ksTS = '' callback = "jsonp253" ajax_url = "https://dsr-rate.tmall.com/list_dsr_info.htm?itemId=" + itemId s2 = requests.get(ajax_url, headers=headers) content2 = s2.content.decode('gbk') content2 = content2.split("(")[-1].split(")")[0] # print(content2) rate_data = json.loads(content2) rate_total = rate_data['dsr']['rateTotal'] print("rate_total", rate_total) ###################################################### # 通过正则,获取pvs_id的集合 pvs_img_url = items['valItemInfo']['skuMap'] pvs_data = re.findall(';\d+:\d+;', str(pvs_img_url)) print(pvs_data) if len(pvs_data) != 0: # 反过来根据json格式,将pvs_id代入属性名称,反倒是能快点,不用思考正则 spu_data = [] for pvs_id in pvs_data: sku_data = [] # img_url = items['valItemInfo']['skuMap'][pvs_id] # print(img_url) # sku数据 # sku_price = items['valItemInfo']['skuMap'][pvs_id]['price'] sku_id = items['valItemInfo']['skuMap'][pvs_id]['skuId'] sku_stock = items['valItemInfo']['skuMap'][pvs_id]['stock'] print(pvs_id, sku_id, sku_stock) original_pvs_id = pvs_id try: face_price, sale_price = self.find_two_price(sell_count_url, sku_id) except: face_price = '' sale_price = '' sku_data.append(pvs_id.replace(";", "")) sku_data.append(face_price) sku_data.append(sale_price) sku_data.append(sku_id) sku_data.append(sku_stock) # if len(img_url)==0: sku_data.append('') spu_data.append(sku_data) # SPU默认的商品图片 try: default_img = items['propertyPics']['default'] print("default_img", default_img) except: default_img = [] print("........") img_num = 1 for x in range(len(default_img)): img_name = default_img[x].split("/")[-1] original_url = default_img[x] img_num += 1 self.insert_img_data(prt_id, "", img_name, original_url, img_num, "spu_img") # 获取SKU的名称信息 soup = BeautifulSoup(content, 'html.parser') for i in range(len(pvs_data)): pvs_id = pvs_data[i].replace(";", "") sku_name = soup.find('li', attrs={"data-value": pvs_id}).get('title') # print(sku_name) spu_data[i].append(sku_name) print("spu_data", spu_data) ############################################################# for sku_info in spu_data: face_price = sku_info[1] sale_price = sku_info[2] sku_id = sku_info[3] sku_stock = sku_info[4] img_url = sku_info[5] img_name = img_url.split('/')[-1] sku_name = sku_info[6] self.insert_sku_data(sku_id, original_pvs_id, prt_id, sku_name, face_price, sale_price, sku_stock) img_num += 1 self.insert_img_data(prt_id, sku_id, img_name, img_url, img_num, "sku_img") else: print("单SKU商品-else") itemId = items['itemDO']['itemId'] try: face_price, sale_price = self.find_two_price(sell_count_url, 'def') except: face_price = '' sale_price = '' quantity = items['itemDO']['quantity'] print("itemId", itemId) print("face_price", face_price) print("sale_price", sale_price) print("quantity", quantity) self.insert_sku_data(itemId, prt_id, "", face_price, sale_price, quantity) # 单个SKU,图片要通过解析content获得 self.get_img_info(content) ''' except KeyError as e: print("单SKU商品-except", e) itemId = items['itemDO']['itemId'] #reservePrice = items['itemDO']['reservePrice'] #经过查验,单SKU盾数据,就是def try: face_price, sale_price = self.find_two_price(sell_count_url, 'def') except: face_price = '' sale_price = '' quantity = items['itemDO']['quantity'] print("itemId", itemId) print("face_price", face_price) print("sale_price", sale_price) print("quantity", quantity) print("........") self.insert_sku_data(itemId, prt_id, "", face_price,sale_price, quantity) self.get_img_info(content) ''' # 存储spu数据 self.insert_spu_data(prt_id, prt_title, sellerNickName, provience, brand_id, brand_name, rate_total, sell_count) def get_img_info(self, content): soup = BeautifulSoup(content, 'html.parser') img_lis = soup.find('ul', attrs={'class': 'tb-thumb tm-clear'}).find_all('li') print("默认图片有%s张" % str(len(img_lis))) for i in range(len(img_lis)): img_url = img_lis[i].find('img').get('src') img_url = img_url.replace("_60x60q90.jpg", "") img_name = img_url.split("/")[-1] img_num = i + 1 self.insert_img_data(prt_id, "", img_name, img_url, img_num, "spu_img") def get_lists(self): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select table_id,prt_url from prt_lists where status=0 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('------get_lists---------Error------Message--------:' + str(err)) db.close() cursor.close() def find_attributes(self, content): soup = BeautifulSoup(content, 'html.parser') ul = soup.find('ul', attrs={'id': 'J_AttrUL'}) attr_lis = ul.find_all('li') print("共有%s条属性" % str(len(attr_lis))) for i in range(len(attr_lis)): attribute_info = attr_lis[i].text # 通过关键字分类 if "证书编号" in attribute_info: zhengshu_no = attribute_info print(zhengshu_no) self.insert_attributes(prt_id, zhengshu_no) elif "3C产品型号" in attribute_info: sanc_type = attribute_info print(sanc_type) self.insert_attributes(prt_id, sanc_type) elif "型号" in attribute_info and "3C" not in attribute_info: prt_type = attribute_info print(prt_type) self.insert_attributes(prt_id, prt_type) elif "插座类型" in attribute_info: chazuo_leixing = attribute_info print(chazuo_leixing) self.insert_attributes(prt_id, chazuo_leixing) elif "插孔类型" in attribute_info: chakong_leixing = attribute_info print(chakong_leixing) self.insert_attributes(prt_id, chakong_leixing) elif "额定电流" in attribute_info: eding_dianliu = attribute_info print(eding_dianliu) self.insert_attributes(prt_id, eding_dianliu) elif "颜色" in attribute_info and "分类" not in attribute_info: color = attribute_info print(color) self.insert_attributes(prt_id, color) def insert_spu_data(self, prt_id, prt_title, sellerNickName, provience, brand_id, brand_name, rate_total, sell_count): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into spu_info(prt_id,prt_title,sellerNickName,provience,brand_id,brand_name,rate_total,sell_count)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s')" \ % (prt_id, prt_title, sellerNickName, provience, brand_id, brand_name, rate_total, sell_count) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_sku_data(self, sku_id, pvs_id, prt_id, sku_name, face_price, sale_price, stock): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into sku_info(sku_id,pvs_id,prt_id,sku_name,face_price,sale_price,stock)" \ "values('%s','%s','%s','%s','%s','%s','%s')" \ % (sku_id, pvs_id, prt_id, sku_name, face_price, sale_price, stock) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_sku_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_img_data(self, prt_id, sku_id, img_name, original_url, img_num, img_type): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_img(prt_id,sku_id,img_name,original_url,img_num,img_type)" \ "values('%s','%s','%s','%s','%s','%s')" \ % (prt_id, sku_id, img_name, original_url, img_num, img_type) # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_img_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_attributes(self, prt_id, attribute_value): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_attribute(prt_id,attribute_name)" \ "values('%s','%s')" \ % (prt_id, attribute_value) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------insert_img_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def update_status(self, status, table_id): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_lists set status='%d' where table_id='%s'" % (status, table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------update_status---------Error------Message--------:' + str(err)) db.close() cursor.close() def find_desc_imgs(self, json_data): # 用来处理desc的图片 items = json.loads(json_data) desc_url = items['api']['descUrl'] desc_url = "http:" + desc_url # print("desc_url", desc_url) # requests请求desc_url s = requests.get(desc_url, headers=headers) desc_data = s.content.decode('gbk') desc_data = desc_data.split("'")[1] # print(desc_data) soup = BeautifulSoup(desc_data, 'html.parser') img_data = soup.find_all('img') for i in range(len(img_data)): try: img_url = img_data[i].get('src') print(img_url) img_name = img_url.split('/')[-1] img_num = i + 1 print(prt_id, img_name, img_url, img_num) self.insert_img_data(prt_id, "", img_name, img_url, img_num, "desc_img") except AttributeError as e: pass def find_sell_count(self, sell_count_url, cookie): # requests请求desc_url s = requests.Session() s = requests.get(sell_count_url, headers=headers2) sell_count_data = s.content.decode('gbk') sell_count_data = sell_count_data print(sell_count_data) items = json.loads(sell_count_data) sell_count = items['defaultModel']['sellCountDO']['sellCount'] print("sell_count", sell_count) return sell_count def find_two_price(self, sell_count_url, sku_id): # requests请求desc_url s = requests.get(sell_count_url, headers=headers) sell_count_data = s.content.decode('gbk') sell_count_data = sell_count_data # print(sell_count_data) items = json.loads(sell_count_data) try: face_price = items['defaultModel']['itemPriceResultDO']['priceInfo'][sku_id]['price'] except: try: a = [] for v in items['defaultModel']['itemPriceResultDO']['priceInfo'].values(): a.append(v['price']) face_price = a[0] except KeyError as e: face_price = '' try: sale_price = items['defaultModel']['itemPriceResultDO']['priceInfo'][sku_id]['promotionList'][0]['price'] except: try: b = [] for v in items['defaultModel']['itemPriceResultDO']['priceInfo'].values(): b.append(v['promotionList'][0]['price']) sale_price = b[0] except KeyError as e: sale_price = '' print("face_price", face_price, "sale_price", sale_price) return face_price, sale_price if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) history_data = dispose_of_history_data() # 控制下是否进行数据表归档 status = 0 if status == 1: # 1. 归档各表的数据内容,并清除原始数据 history_data.filed_data() logger.info('finished the filed_data,including insert/delete') # 2. 更新元数据的status状态,先归档,再更新更好 history_data.update_original_executable_data_status() logger.info('finished the update_original_executable_data_status') else: pass # 3. 执行主体部分的数据获取脚本 headers = { "Accept": "text/html,application/xhtml+xml,application/xml;", "Accept-Encoding": "gzip", "Accept-Language": "zh-CN,zh;q=0.8", "Referer": "http://www.taobao.com/", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } # 对从mysql里面获取的详情页url进行解析 data_procurement = tmall_data_procurement() url_data = data_procurement.get_lists() print(str(len(url_data))) for i in range(len(url_data)): table_id = url_data[i][0] url = url_data[i][1] # prt_id=url.split('id=')[-1].split("&")[0] prt_id = table_id print(url, prt_id) headers2 = { "Host": "mdskip.taobao.com", "Accept": "*/*", "Accept-Encoding": "gzip", "Accept-Language": "zh-CN,zh;q=0.8", "Cookie":"l=AurqcPuigwQdnQv7WvAfCoR1OlrRQW7h; isg=BHp6mNB79CHqYXpVEiRteXyyyKNcg8YEwjgLqoRvCI3ddxqxbLtOFUBGwwOrZ3ad; thw=cn; cna=VsJQERAypn0CATrXFEIahcz8; t=0eed37629fe7ef5ec0b8ecb6cd3a3577; tracknick=tb830309_22; _cc_=UtASsssmfA%3D%3D; tg=0; ubn=p; ucn=unzbyun; x=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0%26__ll%3D-1%26_ato%3D0; miid=981798063989731689; hng=CN%7Czh-CN%7CCNY%7C156; um=0712F33290AB8A6D01951C8161A2DF2CDC7C5278664EE3E02F8F6195B27229B88A7470FD7B89F7FACD43AD3E795C914CC2A8BEB1FA88729A3A74257D8EE4FBBC; enc=1UeyOeN0l7Fkx0yPu7l6BuiPkT%2BdSxE0EqUM26jcSMdi1LtYaZbjQCMj5dKU3P0qfGwJn8QqYXc6oJugH%2FhFRA%3D%3D; ali_ab=58.215.20.66.1516409089271.6; mt=ci%3D-1_1; cookie2=104f8fc9c13eb24c296768a50cabdd6e; _tb_token_=<PASSWORD>; v=0", "Referer": url, "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" } print(headers2) if "detail.tmall.com" in url: # url="https://detail.tmall.com/item.htm?id=560516117660&scene=taobao_shop" # url="https://detail.tmall.com/item.htm?id=538218198610&scene=taobao_shop" # prt_id="538218198610" # 首先,测试用的这条数据是多SKU的版面样式,后面也需要找一个单SKU的进行测试 json_data, content, cookie = data_procurement.get_content(url) print(cookie) if json_data == '': soup = BeautifulSoup(content, 'html.parser') error_msg = soup.find('div', attrs={'class': 'errorDetail'}).text if "找不到" in error_msg: status = 3 else: status = 4 data_procurement.update_status(status, table_id) else: data_procurement.find_json_info(json_data, content) data_procurement.find_attributes(content) data_procurement.find_desc_imgs(json_data) status = 1 #data_procurement.update_status(status, table_id) else: status = 2 #data_procurement.update_status(status, table_id) s(1, 4) # httpsDescUrl <file_sep>/untitled/Requests/抓取斗图2.0.py import urllib.request import urllib.error from bs4 import BeautifulSoup from lxml import etree import re import os #根据文件名创建文件 def createFileWithFileName(localPathParam,fileName): totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath def getAndSaveImg(imgUrl): if (len(imgUrl) != 0): fileName = imgUrl fileName = re.sub('[\/:*?"<>|]', '-', fileName) try: urllib.request.urlretrieve(imgUrl, createFileWithFileName("C:\\Downloads", fileName)) except: print("这图我没法下载") def getHtml(url): #print("正在打开网页并获取....") headers = { 'Host': 'static.doutula.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Accept': 'text/html, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0', 'DNT': '1', 'Cookie':'UM_distinctid=15b9383310948-0002cb8d0502a88-1262694a-1fa400-15b9383310a307; _ga=GA1.2.26294925.1492828501; _gid=GA1.2.2135841525.1498612877; _gat=1', 'Referer': 'http://www.doutula.com/article/list?page=1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' } data=None req=urllib.request.Request(url,data) try: response=urllib.request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") #print(Html) except urllib.error.URLError as e: print(e.reason) Html="" return Html if __name__=="__main__": for i in range (1,1000): url="http://www.doutula.com/article/list?page="+str(i+1) html=getHtml(url) soup=BeautifulSoup(html,"lxml") lists=soup.find_all("img",attrs={"class":"lazy image_dtb"}) for img in lists: img_url=img.get('data-original') print(img_url) getAndSaveImg(img_url) <file_sep>/MMBAO筛选所有的搜索词/筛选所有的搜索词(多线程).py import urllib.parse import pymysql import threading from time import sleep,ctime from urllib import request from bs4 import BeautifulSoup def get_keywords1(): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao", charset="utf8") cursor = db.cursor() sql = "select keyword from MMBAO_KEYWORDS where pre_status=0 and status=0 order by table_id limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_keywords2(): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "mmbao", charset="utf8") cursor = db.cursor() sql = "select keyword from MMBAO_KEYWORDS where pre_status=0 and status=0 order by table_id desc limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() # 获取html函数,参数:url def getHtml(url): req = request.Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/47.0") response = request.urlopen(req) html = response.read().decode('utf-8') # print(html) return html def find_data(html): soup=BeautifulSoup(html,'html.parser') try: prt_text=soup.find('div',attrs={'class':'mt crumbs clearfix'}).find('div',attrs={'class':'fl'}).find_all('span')[1].text prt_cnt=prt_text[prt_text.rindex("商品")+2:prt_text.rindex("个")] print(prt_text) return prt_text,prt_cnt except Exception as AttributeError: prt_text="AttributeError" prt_cnt=0 print(prt_text) return prt_text, prt_cnt def update_status(key_word,prt_cnt,prt_text): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") cursor = db.cursor() sql = "update MMBAO_KEYWORDS set status=1,cnt='%s',content='%s' where pre_status=1 and status=0 and keyword='%s'" %(prt_cnt,prt_text,key_word) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_pre_status(key_word): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") cursor = db.cursor() sql = "update MMBAO_KEYWORDS set pre_status=1 where pre_status=0 and keyword='%s'" %(key_word) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def loop1(): data = get_keywords1() key_word = data[0][0] update_pre_status(key_word) print(key_word) keywords = urllib.parse.quote(key_word) search_url = u"http://search.mmbao.com/?keywords=" + keywords + "&searchSource=1" html = getHtml(search_url) # print(html) prt_text, prt_cnt = find_data(html) update_status(key_word, prt_cnt,prt_text) def loop2(): data = get_keywords2() key_word = data[0][0] update_pre_status(key_word) print(key_word) keywords = urllib.parse.quote(key_word) search_url = u"http://search.mmbao.com/?keywords=" + keywords + "&searchSource=1" html = getHtml(search_url) # print(html) prt_text, prt_cnt = find_data(html) update_status(key_word, prt_cnt,prt_text) def main(): print("starting at:", ctime()) threads = [] nloops = range(2) t1 = threading.Thread(target=loop1) t2 = threading.Thread(target=loop2) threads.append(t1) threads.append(t2) for i in nloops: threads[i].start() for i in nloops: threads[i].join() print("all done at:", ctime()) if __name__=="__main__": for i in range (50000): main() sleep(1) <file_sep>/ZYDMALL/zydmall_德力西/检查有多少系列已经包含在目前的数据中.py #因为数据量并不多,所以直接遍历判断是新增还是复制吧 #抄当时vipmro里面的获取图片的函数 #尽量将一些经常使用的函数打包成库的方法使用,省的老是复制粘贴 #将数据表中,所有is_repeat为1的 import os import urllib.request import pymysql import sys import shutil import time #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(product_id,img_url, img_name): if (len(img_url) != 0): fileName = img_name file_path=u"Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+product_id try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) status=1 except: print("这图我没法下载") status=2 return status #复制图片 def copy_Img(prt_id_exist,prt_id,img_name): #暂时不加异常捕捉机制,试运行 src="Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id_exist+"\\"+img_name dst="Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id+"\\"+img_name print("waiting for "+src+" =>=>=>=>=>=> "+dst) file_path = u"Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\" + prt_id createFileWithFileName(file_path, img_name) shutil.copyfile(src,dst) print("复制成功") def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,table_id,original_url from prt_img_info where download_status=1 and is_use=1 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def is_existed_files(prt_id,img_name): path="Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id file="Z:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\"+prt_id+"\\"+img_name state1=os.path.exists(path) print("已找到目录"+str(state1)) state2=os.path.isfile(file) print("已找到文件"+str(state2)) if state1 is True: if state2 is True: state=1 return state state=0 return state def is_existed(table_id,img_name,url): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,original_url from prt_img_info where download_status=2 and table_id <>'%s' and img_name='%s' and original_url='%s' limit 1" %(table_id,img_name,url) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_state(prt_id,url,status): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update prt_img_info set download_status='%d' where prt_id='%s' and original_url='%s' and is_use=1" %(status,prt_id,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #首先把303个系列遍历,对目前的利息的数据进行like查询 import pymysql def delixi_series(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select series_name from prt_entity " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_same_data(series_name): db = pymysql.connect("localhost", "root", "123456", "de-ele") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select count(*) from mmbao_delixi_data_1017 where prt_title like '%"+series_name+"%' or po_number like '%"+series_name+"%'" #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": data=delixi_series() for i in range (len(data)): series_name=data[i][0] #拿着series_name去那张表查,查出有多少条相似的数据 cnt_tmp=find_same_data(series_name) cnt=cnt_tmp[0][0] print(cnt,"条相似数据") <file_sep>/untitled/Selenium/米思米/商品获取模块.py #解决一页只取28条的BUG import time import pymysql import xlsxwriter from untitled.Selenium import webdriver def login(): print('准备页面跳转--登录') driver.get('https://cn.misumi-ec.com/mydesk2/s/login') time.sleep(3) #1. 点击LOGO driver.find_element_by_class_name('header__logo').click() time.sleep(3) #2. 切换到Login页面 handles = driver.window_handles driver.switch_to.window(handles[0]) time.sleep(1) #3. 登录 driver.find_element_by_class_name('id').send_keys('<PASSWORD>') driver.find_element_by_class_name('pass').send_keys('<PASSWORD>') driver.find_element_by_css_selector('.loginBtn.VN_opacity').click() time.sleep(10) #4. 刷新页面 #driver.get('http://cn.misumi-ec.com/vona2') time.sleep(5) driver.get('http://cn.misumi-ec.com') #2. #source=driver.page_source #print(source) def Get_category_1(): print('loading...进入品牌页面...') driver.get('http://cn.misumi-ec.com/vona2/maker/chint/') time.sleep(2) prt_link=driver.find_elements_by_xpath("//div[@class='crmCategoryOtherList_box']/ul/li[@class='list']/a[@class='clearfix']") for i in range(len(prt_link)): prt_link1=prt_link[i].text #print('saving...category_name...to the arraylist-->prt_1') prt_1.append(prt_link1) prt_link2=prt_link[i].get_attribute('href') #print('saving...category_url...to the arraylist-->prt_2') prt_2.append(prt_link2) print('url:'+prt_link2) #print('-----------------分割线-------------------') print('Finished Category_1...') def Get_category_2(): #遍历所有url for i in range(len(prt_2)): driver.get(prt_2[i]) time.sleep(2) prt_link=driver.find_elements_by_xpath("//div[@class='crmCategoryOtherList_box']/ul/li/a") for i in range(len(prt_link)): prt_link3 = prt_link[i].text #print('saving...category_name_2...to the arraylist-->prt_3') prt_3.append(prt_link3) prt_link4 = prt_link[i].get_attribute('href') #print('saving...category_url_2...to the arraylist-->prt_4') prt_4.append(prt_link4) print('url:' + prt_link4) #print('-----------------分割线-------------------') print('Finished Category_2...') def Get_category_3(): #遍历所有url for i in range(len(prt_4)): driver.get(prt_4[i]) time.sleep(4) page=driver.page_source #print(page) prt_link = driver.find_elements_by_css_selector(".wrap.clearfix") print('共'+str(len(prt_link))+'种商品类别') for i in range(len(prt_link)): prt_link1 = prt_link[i].find_element_by_class_name('mainArea__productlist--txt').find_element_by_tag_name('a') #print('saving...category_name_2...to the arraylist-->prt_5') prt_link5 =prt_link1.text prt_5.append(prt_link5) print(prt_link1.text) #print('saving...category_url_2...to the arraylist-->prt_6') prt_link6=prt_link1.get_attribute('href') prt_6.append(prt_link6) print('url:' + prt_link6) #print('---------------------------------------分割线--------------------------------------') print('Finished Category_3...') def save_excel(fin_result1, fin_result2,fin_result3, fin_result4,fin_result5, fin_result6): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'D:\BI\米思米\test_url.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result1)): tmp.write(i, 1, fin_result1[i]) for i in range(0, len(fin_result2)): tmp.write(i, 2, fin_result2[i]) for i in range(0, len(fin_result3)): tmp.write(i, 3, fin_result3[i]) for i in range(0, len(fin_result4)): tmp.write(i, 4, fin_result4[i]) for i in range(0, len(fin_result5)): tmp.write(i, 5, fin_result5[i]) for i in range(0, len(fin_result6)): tmp.write(i, 6, fin_result6[i]) def prt_content(url): print('GET-->'+url) driver.get(url) time.sleep(5) prt_info = driver.find_elements_by_xpath("//div[@id='listContents']/table[@id='ListTable']/tbody/tr/td[@class='model']") print(str(len(prt_info))) for i in range(len(prt_info)): prt_name = prt_info[i].text #print(prt_name) mysql_insert(prt_name) if next_pg!="none": next_page() def prt_content2(): prt_info = driver.find_elements_by_xpath("//div[@id='listContents']/table[@id='ListTable']/tbody/tr/td[@class='model']") print(str(len(prt_info))) for i in range(len(prt_info)): prt_name = prt_info[i].text #print(prt_name) mysql_insert(prt_name) page_num1=driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text print('当前页面-->'+page_num1) if next_pg!="none": next_page(page_num1) page_num1=page_num1+1 print('自加1='+page_num1) def next_page(page_num): try: driver.find_element_by_id('detail_codeList_pager_lower_right').click() page_num2 = driver.find_element_by_xpath("//div[@class='pageNav']/div/ul/li[@class='on']").text print('当前页面-->' + page_num2) if page_num2!=page_num: prt_content() else: time.sleep(20) prt_content() except: next_pg="none" print("error,已到底页") def save_prt_name(fin_result1): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'D:\BI\米思米\test_prt_name.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet1') for i in range(0, len(fin_result1)): tmp.write(i, 0, fin_result1[i]) def mysql_insert(prt_name): db = pymysql.connect("192.168.180.147","root","123456","test01" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 #sql="insert into Cables_Company_Info_test (Company_ID,Company_Name,Province,City,Address,Leader,Phone,Company_Category) values(2,'Company_Name','Province','City','Address','Leader','Phone','Company_Category') " sql="insert into misumi " \ " (PRT_NAME)" \ " values('%s')" \ % (prt_name) # 使用 fetchone() 方法获取单条数据. #data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() #print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:'+err) # 关闭数据库连接 db.close() if __name__=="__main__": #存放一级类目 prt_1=[] #存放一级类目对应的url prt_2=[] # 存放二级类目 prt_3=[] # 存放二级类目对应的url prt_4=[] # 存放三级类目 prt_5=[] # 存放三级类目对应的url prt_6=[] next_pg="" driver=webdriver.Firefox() #登录 login() #获取产品一级类目 Get_category_1() #通过一级类目的url,遍历所有的类目,获取二级类目 Get_category_2() Get_category_3() save_excel(prt_1,prt_2,prt_3,prt_4,prt_5,prt_6) for i in range(len(prt_6)): prt_content(prt_6[i]) print('结束一个三级类目商品的名称获取') <file_sep>/工品汇/德力西大版本更新-2017年10月13日/二级类目获取.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver from bs4 import BeautifulSoup ''' def company_info(): company_name="德力西" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-name.u-b.J_name').send_keys(uid) driver.find_element_by_css_selector('.login-pwd.p-b.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.main-background-color.login-but.cursor.J_button').click() time.sleep(5) def get_main_data(url): J_searchLists=driver.find_elements_by_xpath("//div[@class='J_searchList']/ul") for Searchlist in J_searchLists: img_url=Searchlist.find_element_by_xpath("./li[@class='a']/a/img").get_attribute('src') prt_name=Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").text prt_url =Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").get_attribute('href') prt_id = prt_url[prt_url.index("product/") + 8:100] prt_type=Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[0].text order = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[1].text price=Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='a']").text market_price = Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='b']").text print(img_url,prt_id,prt_name,prt_url,prt_type,order,price,market_price) insert_data1(prt_id,prt_name,prt_url,prt_type,order,price,market_price,url) def insert_data1(prt_id,prt_name,prt_url,prt_type,order,price,market_price,url): company_name=company_info() db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into vipmro_data (company_name,prt_id,prt_name,prt_url,prt_type,order_,price,market_price,cate_2_url)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,url) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def next_page(j): time.sleep(4) xpath_data="//div[@class='saas-paging J_paging']/a[@class='J_page_turn'][@page-id='"+str(j+2)+"']" print(xpath_data) driver.find_element_by_xpath(xpath_data).click() time.sleep(4) def get_url_status(): company_name=company_info() db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select case when cate_2_url='' then cate_1_url else cate_2_url end as url from vipmro_url where status=0 and company_name='"+company_name+"' order by table_id limit 1 " try: execute=cursor.execute(sql) category_url=cursor.fetchmany(execute) return category_url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(url): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_url set status=1 where cate_2_url='%s' or cate_1_url='%s' " \ % (url,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def find_series_cate(html): soup=BeautifulSoup(html,'html.parser') divs=soup.find('div',attrs={'class':'J_attr'}).find_all('div',attrs={'class':'search-menu-li'}) for div in divs: name=div.find('span',attrs={'class':'a m-top10 weight'}).text series = div.find('span', attrs={'class': 'b p-left10 no-border'}).find_all('a') for a in series: series_url = a.get('href') series_name = a.text print(name, series_name, series_url) def get_lists(): list_divs=driver.find_elements_by_xpath("//div[@class='list-main-box J_list J_car_box']/ul/li") print('当前页一共%s条数据'%str(len(list_divs))) for list_div in list_divs: #列表页小图 list_prt_img=list_div.find_element_by_xpath("./div[@class='list-main-box-img']/a/img") list_prt_img_url=list_prt_img.get_attribute('src') list_prt_img_name=list_prt_img_url[list_prt_img_url.rindex("/")+1:list_prt_img_url.rindex("jpg")+3] print(list_prt_img_name,list_prt_img_url) #SKU_TITLE list_prt_info=list_div.find_element_by_xpath("./div[@class='list-main-box-cont']/a") list_prt_url=list_prt_info.get_attribute('href') list_prt_title = list_prt_info.find_element_by_xpath("./span[@class='title']").text list_prt_type = list_prt_info.find_element_by_xpath("./span[@class='model m-top5']").text list_prt_order = list_prt_info.find_element_by_xpath("./span[@class='model']").text.replace(" ","") list_prt_sale_price = list_prt_info.find_element_by_xpath("./span[@class='price_color m-top5']/font/font[@class='weight ft14']").text prt_id=list_prt_url[list_prt_url.rindex("/"):100] print(prt_id,list_prt_title,list_prt_url,list_prt_type,list_prt_order,list_prt_sale_price) insert_vipmro_delixi_lists(prt_id,list_prt_title,list_prt_url,list_prt_type,list_prt_order) def insert_vipmro_delixi_lists(prt_id,prt_name,prt_url,prt_type,po_number): company_name=company_info() db = pymysql.connect("localhost", "root", "123456", "de-ele") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_order_type_link (prt_id,prt_name,prt_url,prt_type,po_number)"\ "values('%s','%s','%s','%s','%s')"\ %(prt_id,prt_name,prt_url,prt_type,po_number) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() ''' def s(a,b): rand=random.randint(a,b) time.sleep(rand) def get_category(html): soup=BeautifulSoup(html,'html.parser') lis = soup.find('div', attrs={'class': 'in-ul'}).find('ul').find_all('li', attrs={'class': 'J_lb'}) category_urls=[] category_ids=[] category_names=[] for li in lis: category_name = li.find('a').text category_url = li.find('a').get('href') category_id = category_url[category_url.rindex("=") + 1:1000] #print(category_id, category_name,category_url) category_urls.append(category_url) category_ids.append(category_id) category_names.append(category_name) return category_ids,category_names,category_urls def get_category_2(html,category_id,category_name,category_url): soup=BeautifulSoup(html,'html.parser') category_2s=soup.find_all('li',attrs={'class':'J_lb'}) print("还有%s条二级类目"%str(len(category_2s))) mysql = mysql_data() #如果没有二级类目 if len(category_2s)==0: mysql.insert_category(category_id, category_name, category_url, category_id, category_name, category_url) for i in range (len(category_2s)): category_2_name= category_2s[i].find('a').text category_2_url = category_2s[i].find('a').get('href') category_2_id = category_2_url[category_2_url.rindex("=") + 1:1000] print(category_2_id,category_2_name,category_2_url) mysql.insert_category(category_id,category_name,category_url,category_2_id,category_2_name,category_2_url) class mysql_data(): def insert_category(self,category_id,category_name,category_url,category_2_id,category_2_name,category_2_url): db = pymysql.connect("localhost", "root", "123456", "de-ele") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into delixi_category_info (category_id,category_name,category_url,category_2_id,category_2_name,category_2_url)" \ "values('%s','%s','%s','%s','%s','%s')" \ % (category_id,category_name,category_url,category_2_id,category_2_name,category_2_url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": driver=webdriver.Firefox() url = 'http://www.vipmro.com/search/?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&brandId=104' print(url) driver.get(url) time.sleep(5) html = driver.page_source # 获取二级类目后,判断页面上是否有系列这个词 #print(html) category_ids, category_names, category_urls=get_category(html) print("共%s条一级类目数据"%str(len(category_urls))) for i in range(len(category_urls)): category_id=category_ids[i] category_name = category_names[i] category_url = category_urls[i] print(category_id,category_name,category_url) driver.get(category_url) time.sleep(2) html=driver.page_source #print(html) get_category_2(html,category_id,category_name,category_url) s(1,3) <file_sep>/企查查/下载xls_demo.py import pymysql from selenium import webdriver from bs4 import BeautifulSoup import time,random import requests if __name__=="__main__": href="http://report.qichacha.com/ReportEngine/20180719131764357766034359_9627816.xls" print(href) if '.xls' in href: print("downloading with requests") xls_name = href.split("/")[-1] r = requests.get(href) with open(xls_name, "wb") as code: code.write(r.content) <file_sep>/untitled/BAIDU翻译1.0.py import urllib.request import urllib.parse import json url='http://fanyi.baidu.com/v2transapi' head={} head['User-Agent']='Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0' data={} data['from']='en' data['to']='zh' data['query']='I PROMISE I NEED YOU' data['simple_means_flag']='3' data=urllib.parse.urlencode(data).encode('utf-8') req=urllib.request.Request(url,data,head) response=urllib.request.urlopen(req) html=response.read().decode('utf-8') print(html) target=json.loads(html) tmp=target['trans_result']['data'][0]['dst'] print(tmp)<file_sep>/JD后台/VC后台/0619后台整体采购价调价/SKU编号生成匹配采购价格V1.1.py import pymysql #获取所有的型号对应的价格/千米 def get_lists(): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 型号,规格,红本价,结算价,采购价,京东价 from yddl_price " # print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def find_data(xinghao,guige): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 主商品编号,主商品名称 from jd_export_prt_info where vc_shop='工业品' and REPLACE(主商品名称,' ','') like '%)"+str(xinghao)+str(guige)+"%'" print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def update_price(sku_id,xinghao,guige,hongben,jiesuan,caigou,jd_price): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update jd_export_prt_info set 型号='%s',规格='%s',红本价='%s',结算价='%s',采购价='%s',京东价='%s' where 主商品编号='%s'" \ %(xinghao,guige,hongben,jiesuan,caigou,jd_price,sku_id) print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": yddl_data=get_lists() for i in range (len(yddl_data)): xinghao=yddl_data[i][0] guige = yddl_data[i][1] hongben = yddl_data[i][2] jiesuan = yddl_data[i][3] caigou=yddl_data[i][4] jd_price = yddl_data[i][5] print(str(i+1),xinghao,guige,hongben,jiesuan,caigou,jd_price) #将型号和规格带入到数据表进行查询 data=find_data(xinghao,guige) for i in range (len(data)): sku_id=data[i][0] sku_name=data[i][1] #主要问题是,还是要将型号提取出来做二次判断,不然很容易出现BVR1匹配到了BVR1.5身上,容易出事故 print(sku_id,sku_name) #按照传统的命名规范来讲,去掉“(FAR EAST CABLE)”,去掉“1米、50米、100米,”,去掉“/” update_price(sku_id,xinghao,guige,hongben,jiesuan,caigou,jd_price) <file_sep>/ZYDMALL/zydmall_德力西/图片筛选、给予美工.py import os import urllib.request import pymysql import sys import shutil def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_id,img_name,original_url from prt_img_info where download_status=1 and is_repeat=0 and is_use=1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(product_id,img_url, img_name): if (len(img_url) != 0): fileName = img_name file_path=u"D:\\BI\\ZYD_DELIXI\\filter\\upload\\prt\\zyd\\"+product_id try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) status=1 except: print("这图我没法下载") status=2 return status if __name__=="__main__": data = get_prt_data() for i in range (4000): prt_id = data[i][0] img_name = data[i][1] url = data[i][2] print(prt_id, img_name, url) getAndSaveImg(prt_id, url, img_name) #copy_Img(prt_id,img_name) #status=1 #update_state(prt_id,url,status)<file_sep>/untitled/Requests/远东协同.py import time from selenium import webdriver if __name__=="__main__": driver=webdriver.Firefox() driver.get("http://oa.fegroup.cn:8090/c6/Jhsoft.Web.login/PassWordSlide.aspx") page=driver.page_source() print(str(page))<file_sep>/JD后台/VC后台/调整商品名称中的加工定制字样.py import pymysql def get_lists(): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select type,change_text from changed_text" print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def find_changed_data(type): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select sku_id,sku_name,new_sku_name from sku_name_change where sku_name like '%"+type+"%' " print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def update_sku_name(sku_id,new_sku_name): db = pymysql.connect("localhost", "root", "123456", "jd_shop") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update sku_name_change set new_sku_name='%s' where sku_Id='%s' " %(new_sku_name,sku_id) print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": data=get_lists() for i in range (len(data)): type=data[i][0] change_text=data[i][1] print(type,",",change_text) #对sku-Name进行判断 sku_data =find_changed_data(type) for x in range (len(sku_data)): sku_id=sku_data[x][0] sku_name = sku_data[x][1] new_sku_name = sku_data[x][2] if "定制预售" in sku_name: new_sku_name=sku_name.replace("加工/","").replace("加工","").replace("定制预售",change_text).replace("(FAR EAST CABLE)"," ") #new_sku_name=new_sku_name+change_text update_sku_name(sku_id,new_sku_name) <file_sep>/TMALL/获取整个不规则列表页的所有url/按照本地html获取url链接.py import requests import os import pymysql from bs4 import BeautifulSoup if __name__=="__main__": url=r"D:\\abb2.html" html_content=open(url,'r',encoding="utf-8") content=html_content.read() #print(content) soup = BeautifulSoup(content, "html.parser") # 实例化一个BeautifulSoup对象 prt_lists=soup.find_all('a') print("current page have %s records"%(str(len(prt_lists)))) for i in range (len(prt_lists)): prt_href=prt_lists[i].get('href') print(prt_href) <file_sep>/Scrapy/jiandan/jiandan/main.py from scrapy import cmdline cmdline.execute("scrapy crawl jiandan".split())<file_sep>/untitled/Selenium/众业达/众业达-V1.0.py #思路 #1. 分类:分为一级类目,二级类目 #点击类目<a>后,页面部分刷新,可以直接获取list内容 #1. 一级类目<a>,可获取 #2. 二级类目 #list_一级类目=driver.find(a) #for i in range (len(list_一级类目)): # list[i].click() # list_二级类目 = driver.find(a) # for j in range ():sa's # list[j].click() #通过循环来获取 #分析一波url #http://www.zydmall.com/search/search.aspx?tag=%E8%A5%BF%E9%97%A8%E5%AD%90&cid=45&bid=80 # tag=西门子 #cid=category_id=45,二级类目的标签中的data属性值 #bid=brand_id=80,品牌ID,在属性也有 import time import random from selenium import webdriver import pymysql def company_info(): company_name="德力西" return company_name def s(a,b): rand=random.randint(a,b) time.sleep(rand) def insert_mysql_cate_info(cate1_name,cate1_data,cate2_name,cate2_data): company_name=company_info() #再导入数据表之前,还需要拼个url存着 cate2_url="http://www.zydmall.com/search/search.aspx?tag="+company_name+"&cid="+cate2_data print(cate2_url) db = pymysql.connect("192.168.128.3","root","123456","zhongyeda",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_category_info " \ " (company_name,cate1_name,cate1_data,cate2_name,cate2_data,cate2_url)" \ " values('%s','%s','%s','%s','%s','%s')" \ % (company_name,cate1_name,cate1_data,cate2_name,cate2_data,cate2_url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() def get_category(): cate1_list=driver.find_elements_by_xpath("//div[@class='search_type']/a") print("共 "+str(len(cate1_list))+" 一级类目") for i in range(len(cate1_list)): cate1_name=cate1_list[i].text cate1_name=cate1_name[0:cate1_name.index("(")] cate1_data=cate1_list[i].get_attribute("data") print(cate1_name+"--"+cate1_data) cate1_list[i].click() #获取二级类目 cate2_list = driver.find_elements_by_xpath("//div[@class='search_t_list']/div[@class='clearfix']/a[@type='fl']") print("共 "+str(len(cate2_list))+" 二级类目") for j in range (len(cate2_list)): cate2_name=cate2_list[j].text cate2_data=cate2_list[j].get_attribute("data") #print(cate2_name + "--" + cate2_data) insert_mysql_cate_info(cate1_name,cate1_data,cate2_name,cate2_data) print("------------------------------") #从数据表读取一条状态为0的记录,返回url def get_url_from_mysql(): company_name=company_info() db = pymysql.connect("192.168.128.3","root","123456","zhongyeda",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select cate2_url from zyd_category_info where company_name='%s' and status=0 limit 1" %(company_name) try: execute=cursor.execute(sql) url=cursor.fetchmany(execute) return url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() #获取count数 def get_count_from_mysql(): company_name=company_info() db = pymysql.connect("192.168.128.3","root","123456","zhongyeda",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select count(cate2_url) as cnt from zyd_category_info where company_name='%s' and status=0 " %(company_name) try: execute=cursor.execute(sql) cnt=cursor.fetchmany(execute) return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def insert_mysql_title(category_id,type,title): company_name = company_info() db = pymysql.connect("192.168.128.3","root","123456","zhongyeda",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into list_title " \ " (company_name,category_id,title_id,title)" \ " values('%s','%s','%s','%s')" \ % (company_name,category_id,type,title) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() def update_status_for_mysql(url): company_name=company_info() db = pymysql.connect("192.168.128.3","root","123456","zhongyeda",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update zyd_category_info " \ " set status=1 where cate2_url='%s' and company_name='%s'" \ % (url,company_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() def get_list_content(): category_id=driver.find_element_by_xpath("//div[@class='search_t_list']/div[@class='clearfix ']/a[@class='crently']").get_attribute("data") #print("category_id="+category_id) list_titles=driver.find_elements_by_xpath("//div[@class='search_table mt20']/table/tbody[1]/tr[1]/th") print("共"+str(len(list_titles))+"个title") for i in range (len(list_titles)): title=list_titles[i].text type="type"+str(i+1) insert_mysql_title(category_id,type,title) prt_cnt=driver.find_element_by_id("goodsTotal").text #修改一下,之前是10条一页,改为50条一页 driver.find_element_by_xpath("//div[@class='fl f14 c999 searhc_page']/span[@class='mr10']/a[3]").click() print("改为50行一页") s(5,7) if int(prt_cnt)%50==0: page_num=int(prt_cnt)/50 else: page_num = int(int(prt_cnt) / 50+1) print("共"+prt_cnt+"件商品,共"+str(page_num)+"页数据") for j in range(1,int(page_num)): get_list_data(category_id) s(2,3) next_page(j) get_list_data(category_id) def next_page(num): driver.find_element_by_xpath("//div[@class='fl f14 c999 searhc_page']/b/a[@class='page_next']").click() s(5,7) current_page=driver.find_element_by_xpath("//span[@class='mini_nub']/i[@class='ceb6161']").text print("当前第"+current_page+"页") if int(current_page)!=num+1: s(7,9) def get_list_data(category_id): list_content = driver.find_elements_by_xpath("//div[@class='search_table mt20']/table/tbody[@id='product_list']/tr[contains(@class,'pro_list bg')]") for i in range (len(list_content)): list_info=list_content[i].find_elements_by_xpath("./td") #print(len(list_info)) prt_name=list_info[0].find_element_by_xpath("./div[@class='table_pro']/a[@class='title c333']").text prt_url = list_info[0].find_element_by_xpath("./div[@class='table_pro']/a[@class='title c333']").get_attribute("href") img_url = list_info[0].find_element_by_xpath("./div[@class='table_pro']/a[@class='img']/img").get_attribute("src") order_id = list_info[0].find_element_by_xpath("./div[@class='table_pro']/p[1]/b").text model_name = list_info[0].find_element_by_xpath("./div[@class='table_pro']/p[2]/b").text type2=list_info[1].text type3=list_info[2].text try: type4=list_info[3].text except: type4 ="" try: type5=list_info[4].text except: type5="" try: type6=list_info[5].text except: type6="" try: type7=list_info[6].text except: type7="" try: type8=list_info[7].text except: type8="" try: type9=list_info[8].text except: type9="" try: type10=list_info[9].text except: type10="" try: type11=list_info[10].text except: type11="" try: type12=list_info[11].text except: type12="" try: type13=list_info[12].text except: type13="" try: type14=list_info[13].text except: type14 ="" try: type15=list_info[14].text except: type15="" try: type16=list_info[15].text except: type16="" try: type17=list_info[16].text except: type17="" try: type18=list_info[17].text except: type18="" try: type19=list_info[18].text except: type19="" try: type20=list_info[19].text except: type20="" try: type21=list_info[20].text except: type21="" insert_mysql_prt_data(category_id,prt_name,prt_url,img_url,order_id,model_name,type2,type3,type4,type5,type6,type7,type8,type9,type10,type11,type12,type13,type14,type15,type16,type17,type18,type19,type20,type21) s(2,3) print("当前页共"+str(len(list_content))+"条数据") def insert_mysql_prt_data(category_id,prt_name,prt_url,img_url,order_id,model_name,type2,type3,type4,type5,type6,type7,type8,type9,type10,type11,type12,type13,type14,type15,type16,type17,type18,type19,type20,type21): company_name = company_info() db = pymysql.connect("192.168.128.3","root","123456","zhongyeda",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into zyd_prt_data " \ " (company_name,category_id,prt_name,order_id,model_name,type2,type3,type4,type5,type6,type7,type8,type9,type10,type11,type12,type13,type14,type15,type16,type17,type18,type19,type20,type21,prt_url,img_url)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (company_name,category_id,prt_name,order_id,model_name,type2,type3,type4,type5,type6,type7,type8,type9,type10,type11,type12,type13,type14,type15,type16,type17,type18,type19,type20,type21,prt_url,img_url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() if __name__=="__main__": #j进入众业达数据 company_name=company_info() url="http://www.zydmall.com/search/search.aspx?tag="+company_name driver=webdriver.Firefox() driver.get(url) #driver.implicitly_wait(20) #s(2,4) #生成类目数据,插入数据表 get_category() cnt=get_count_from_mysql() cnt=str(cnt[0]).replace("(","").replace(",)","") ##print(cnt) ##重新获取数据表的数据,加入status,然后遍历,断点续传功能 for i in range (int(cnt)): url=get_url_from_mysql() url=str(url[0]).replace("('","").replace("',)","") print(url) driver.get(url) s(4,6) #获取列表的title,content get_list_content() #更新状态 update_status_for_mysql(url) <file_sep>/test.py def func((x1,y1),(x2,y2)): k=(y1-y2)/(x1-x2) y=pi/2-arctan(k) return y p=array([(572.1,1137,1),(866.6,967.7),(1664.2,529.0),(1179.2,166.6),(495.2,423.4),(428.2,769.0)]) S=[] for i in range(6): for j in range(i): s=func(p[i],p[j]) print (s) S.append(s) S=asarray(S)<file_sep>/日常工作/统计1-3月份新增买家客户.py import pymysql def get_useful_data(): start_time="2018-01-01" end_time="2018-02-01" db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select name from 20180412_filter where time between date('"+start_time+"') and date('"+end_time+"')" #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as e: db.rollback() print('------table_data_delete---------Error------Message--------:' + str(e)) cursor.close() db.close() def get_earlier_data(buyer_name): end_time="2018-01-01" db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select name from 20180412_filter where name='"+buyer_name+"' and time < date('"+end_time+"') " #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as e: db.rollback() print('------table_data_delete---------Error------Message--------:' + str(e)) cursor.close() db.close() if __name__=="__main__": data=get_useful_data() #print(data) for i in range (len(data)): buyer_name=data[i][0] earlier_data=get_earlier_data(buyer_name) if len(earlier_data)>=1: pass else: print(buyer_name) <file_sep>/MMBAO/产品库数据校验/产品库数据发布校验商品表V1.0.py #分为两块,一块是从mysql取出整个产品库模板的数据 #另一块是从oracle的产品库数据表,对每条数据进行核对 #1. excel数据存储,新建数据库,专门存放 import pymysql import cx_Oracle import time class mysql_data(): def mysql_spu_data(self): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select spu_id,spu标题 from spu表 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def mysql_sku_data(self,spu_id, spu_title, date_time): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select sku_id from SKU表 where 对应SPU_ID='%s' " %spu_id try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def mysql_sku_attr_data(self,sku_id): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select * from 销售属性表 where 对应sku_id ='%s' " %sku_id try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_log(table_name,error_id,content): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into log (table_name,error_id,content) values('%s','%s','%s')" %(table_name,error_id,content) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() class oracle_data(): def oracle_spu_data(self,spu_id,spu_title,date_time): db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.mmbao.com:21252/mmbao2b2c') #print(db.version) cursor = db.cursor() sql = "SELECT * FROM mmbao2.t_dqs_product where dqs_prt_id='%s' and is_delete=0 " %(spu_id) #and create_date>to_date('%s','yy/MM/dd') #因为还得分为新增和更新 #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def oracle_sku_data(self,spu_id, spu_title, date_time): db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.<EMAIL>.com:21252/mmbao2b2c') #print(db.version) cursor = db.cursor() sql = "select * FROM mmbao2.t_dqs_product_sku where dqs_prt_id='%s' and is_delete=0 and create_date>to_date('%s','yy/MM/dd')" %(spu_id,date_time) #and create_date>to_date('%s','yy/MM/dd') #因为还得分为新增和更新 #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def oracle_spu_attr_data(self,spu_id, spu_title,date_time): db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.mmbao.com:21252/mmbao2b2c') #print(db.version) cursor = db.cursor() sql = "select * FROM mmbao2.t_dqs_product_attr_val where dqs_prt_id='%s' and is_delete=0 and create_date>to_date('%s','yy/MM/dd')" %(spu_id,date_time) #and create_date>to_date('%s','yy/MM/dd') #因为还得分为新增和更新 #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def oracle_sku_attr_data(self,sku_id): db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.mmbao.com:21252/mmbao2b2c') #print(db.version) cursor = db.cursor() sql = "select * FROM mmbao2.t_dqs_product_sku_item where dqs_sku_id='%s' and is_delete=0 " %(sku_id) #and create_date>to_date('%s','yy/MM/dd') #因为还得分为新增和更新 #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data if __name__=="__main__": #想了想还是得标注日期进行筛选 date_time='2017/11/29' mysql=mysql_data() oracle=oracle_data() ################################################################## #spu表数据 data=mysql.mysql_spu_data() print(data) for i in range (len(data)): spu_id=data[i][0] spu_title=data[i][1] print(spu_id,spu_title) #data2=oracle.oracle_spu_data(spu_id,spu_title,date_time) #print('搜索出结果%s条',str(len(data2))) #time.sleep(5) ################################################################## #检查当前这条SPU对应的SKU有多少条 data_mysql_sku = mysql.mysql_sku_data(spu_id, spu_title, date_time) print("mysql共%s条SKU记录" % str(len(data_mysql_sku))) data_oracle_sku = oracle.oracle_sku_data(spu_id, spu_title, date_time) print("oracle共%s条SKU记录"%str(len(data_oracle_sku))) if len(data_mysql_sku)==len(data_oracle_sku): print("sku数据检查--pass") else: time.sleep(0.5) print("sku数据检查--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") error_log="SPU数据%s检查失败,SKU记录总数异常,%s,%s"%(spu_id,str(len(data_mysql_sku)),str(len(data_oracle_sku))) table_name="SKU表" insert_log(table_name,spu_id,error_log) ################################################################## #普通属性值 data_oracle_spu_attr = oracle.oracle_spu_attr_data(spu_id, spu_title,date_time) print("oracle共%s条SPU记录" % str(len(data_oracle_spu_attr))) if len(data_oracle_spu_attr)==1: print("SPU—ATTR记录--PASS") else: time.sleep(0.5) print("SPU—ATTR记录--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") error_log="SPU_ATTR数据%s检查失败,普通销售属性异常,1,%s"%(spu_id,str(len(data_oracle_spu_attr))) table_name="普通属性表" insert_log(table_name,spu_id,error_log) ################################################################## #销售属性值 #因为spu_id,sku_id都已经匹配更新完毕,所以后面就可以采用这些ID进行验证 for j in range(len(data_mysql_sku)): sku_id=data_mysql_sku[j][0] print(sku_id) data_mysql_sku_attr = mysql.mysql_sku_attr_data(sku_id) print("%s在mysql共%s条销售属性"%(sku_id,str(len(data_mysql_sku_attr)))) data_oracle_sku_attr = oracle.oracle_sku_attr_data(sku_id) print("%s在oracle共%s条销售属性" % (sku_id, str(len(data_oracle_sku_attr)))) if len(data_oracle_sku_attr)==len(data_mysql_sku_attr): print("SKU_ATTR记录--PASS") else: time.sleep(0.5) print("SKU_ATTR记录--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") error_log="SKU_ATTR数据%s检查失败,SKU对应的属性数量异常,%s,%s"%(sku_id,str(len(data_oracle_sku_attr)),str(len(data_mysql_sku_attr))) table_name="销售属性表" insert_log(table_name,sku_id,error_log) print("_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_~_") <file_sep>/MMBAO/对SKU进行属性的获取补充/PART1-数据导入到数据库.py #将excel模板中的数据导入到指定的数据表 import pymysql import xlrd def get_data_from_excel(): data=xlrd.open_workbook(r"D:\BI\SKU-title添加关键属性_2017年10月30日092004\数据整理模板.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 data=[] for i in range(1,nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print(ss) data.append(ss) return data def insert_data(table_id,category_name,attribute_name,order_number): db = pymysql.connect("localhost", "root", "123456", "mmbao_sku_title") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into category_filter_attribute(table_id,category_name,attribute_name,num)"\ "values('%s','%s','%s','%s')"\ %(table_id,category_name,attribute_name,order_number) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #获取excel的数据 data = get_data_from_excel() print(len(data)) for row in data: table_id=row[0] category_name=row[1] attribute_name=row[2] order_number=row[3] print(table_id,category_name,attribute_name,order_number) insert_data(table_id,category_name,attribute_name,order_number) <file_sep>/工品汇/查找德力西商品型号/通过订货号查找德力西商品型号.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver def s(a,b): rand=random.randint(a,b) time.sleep(rand) def company_info(): company_name="德力西" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) def next_page(j): time.sleep(4) xpath_data="//div[@class='saas-paging J_paging']/a[@class='J_page_turn'][@page-id='"+str(j+2)+"']" print(xpath_data) driver.find_element_by_xpath(xpath_data).click() time.sleep(4) def get_url_status(): company_name=company_info() db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select po_number from prt_exception_order_num where status=0 order by table_id limit 1 " try: execute=cursor.execute(sql) po_number=cursor.fetchmany(execute) return po_number except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(po_number): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update prt_exception_order_num set status=1 where po_number='%s'" \ % (po_number) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def search_prt(po_number): driver.find_element_by_css_selector(".index-sel-text.J_selectText").clear() driver.find_element_by_css_selector(".index-sel-text.J_selectText").send_keys(po_number) driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() s(5,7) try: exceptions=driver.find_element_by_css_selector(".openLogis-cont.J_openCont") print(exceptions) while 1==1: print("waiting") s(1,2) try: exceptions = driver.find_element_by_css_selector(".openLogis-cont.J_openCont") except: break except: pass while 1 == 1: try: cnt = driver.find_element_by_css_selector('.J_page_sum.t_num').text cnt = int(cnt) if cnt >= 0: break except: try: error_msg = driver.find_element_by_css_selector('.ft20.weight.s-p').text if '已下架' in error_msg: break except: pass get_main_data(po_number) ''' for j in range (15): get_main_data(po_number) try: next_page(j) except: print("没有下一页") break ''' def insert_data1(prt_id,prt_name,prt_url,prt_type,po_number): company_name=company_info() db = pymysql.connect("localhost", "root", "<PASSWORD>", "de-ele") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_order_type_link (prt_id,prt_name,prt_url,prt_type,po_number)"\ "values('%s','%s','%s','%s','%s')"\ %(prt_id,prt_name,prt_url,prt_type,po_number) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def get_main_data(po_number): J_searchLists=driver.find_elements_by_xpath("//div[@class='J_searchList']/ul") for Searchlist in J_searchLists: #img_url=Searchlist.find_element_by_xpath("./li[@class='a']/a/img").get_attribute('src') prt_name=Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").text prt_url =Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").get_attribute('href') prt_id = prt_url[prt_url.index("product/") + 8:100] prt_type=Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[1].text order_tmp = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[0].text order=str(order_tmp).replace("订 货 号 :","") print(order) #price=Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='a']").text #market_price = Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='b']").text #print(prt_id,prt_name,prt_url,prt_type,po_number) if po_number==order: print("找到一致的数据") insert_data1(prt_id,prt_name,prt_url,prt_type,po_number) break if __name__=="__main__": driver=webdriver.Firefox() url = "http://www.vipmro.com/search?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&brandId=104" driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) #完成登录 #点击一下搜索按钮,使页面正确加载url driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() time.sleep(10) for i in range (834): #通过搜索功能,对所有未关联到的数据进行获取,还是存放到那张表里 data=get_url_status() po_number=data[0][0] print(po_number) search_prt(po_number) update_status_to_run_log(po_number) <file_sep>/日常工作/企查查公司筛选.py import pymysql def get_company_info(): db = pymysql.connect("localhost", "root", "123456", "qichacha") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select 序号,企业名称,统一社会信用代码 from qichacha_company_info where status=0" # print(sql) try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('-------get_company_info--------Error------Message--------:' + str(err)) cursor.close() db.close() def find_repeat(table_id,company_name,company_code): db = pymysql.connect("localhost", "root", "123456", "qichacha") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update qichacha_company_info set status=1 where 企业名称='%s' and status=0 and 统一社会信用代码='%s' and 序号<>'%s' "%(company_name,company_code,table_id) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------find_repeat--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": company_data=get_company_info() for i in range (len(company_data)): table_id=company_data[i][0] company_name=company_data[i][1] company_code = company_data[i][2] print(table_id,company_name,company_code) find_repeat(table_id,company_name,company_code) <file_sep>/JD/JD-德力西开关/获取详情数据-test.py import pymysql from selenium import webdriver from bs4 import BeautifulSoup import time def get_prt_url(): db = pymysql.connect("localhost", "root", "123456", "delixi_diangong", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select prt_name,prt_url,type from jd_delixi_lists where status=0" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_img(prt_id,img_name,img_data_url,img_src,img_num,img_type): db = pymysql.connect("localhost", "root", "123456", "delixi_diangong", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into prt_img_info(prt_id,img_name,img_data_url,img_src,img_num,img_type)"\ " values('%s','%s','%s','%s','%s','%s')" %(prt_id,img_name,img_data_url,img_src,img_num,img_type) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_prt_data(prt_id,prt_name,prt_url,type,prt_num,prt_shop,prt_weight,price,original_content): db = pymysql.connect("localhost", "root", "123456", "delixi_diangong", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into prt_info(prt_id,prt_name,prt_url,type,prt_num,prt_shop,prt_weight,price,original_content)"\ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" %(prt_id,prt_name,prt_url,type,prt_num,prt_shop,prt_weight,price,original_content) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_details(prt_id, prt_name, prt_url, type): driver = webdriver.Firefox() driver.get(prt_url) html = driver.page_source soup=BeautifulSoup(html,'html.parser') class_data="price J-p-"+prt_id price=soup.find('span',attrs={'class':class_data}).text print("价格%s"%price) parameters_li=soup.find('div',attrs={'class':'p-parameter'}).find('ul',attrs={'class':'parameter2 p-parameter-list'}).find_all('li') prt_name=parameters_li[0].text prt_num=parameters_li[1].text prt_shop=parameters_li[2].text prt_weight=parameters_li[3].text print(prt_name,prt_num,prt_shop,prt_weight) original_content=soup.find('div',attrs={'id':'J-detail-content'}) insert_prt_data(prt_id,prt_name,prt_url,type,prt_num,prt_shop,prt_weight,price,original_content) driver.quit() imgs_desc=original_content.find_all('img') for i in range (len(imgs_desc)): img_id=imgs_desc[i].get('id') img_url=imgs_desc[i].get('data-lazyload') img_name=img_url[img_url.rindex('/')+1:1000] img_url="http:"+img_url img_type="img_desc" print(img_id,img_name,img_url,img_type) img_num=i+1 insert_img(prt_id,img_name,img_id,img_url,img_num,img_type) good_imgs=soup.find('div',attrs={'id':'spec-list'}).find_all('li') for x in range (len(good_imgs)): img_info=good_imgs[x].find('img') img_alt=img_info.get('alt') img_url=img_info.get('src') img_name = img_url[img_url.rindex('/')+1:1000] img_type="good_img" img_url = "http:" + img_url print(img_alt, img_name, img_url, img_type) img_num=x+1 insert_img(prt_id,img_name,img_alt,img_url,img_num, img_type) if __name__=="__main__": #从mysql获取相关的数据url data=get_prt_url() print("等待处理%s条数据"%str(len(data))) for i in range (len(data)): prt_name=data[i][0] prt_url=data[i][1] type=data[i][2] prt_id=prt_url[prt_url.rindex("/")+1:1000].replace(".html","") print(prt_id, prt_name, prt_url, type) get_details(prt_id, prt_name, prt_url, type) time.sleep(2) <file_sep>/MMBAO/用户搜索分析/用户IP地址分析.py import pymysql import cx_Oracle def get_search_keywords(): db = cx_Oracle.connect('cableex_bi/cableex_bi@172.16.58.3:7018/cableexc') cursor = db.cursor() sql="select * from CABLEEX.T_CMALL_SEARCH_KEYWORDS t "\ "WHERE search_keywords not like '%?%' and search_time>=to_date('2018-01-01','YYYY-MM-DD') and search_ip is not null and rownum < 1001" print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def find_address(search_ip): if __name__=="__main__": data=get_search_keywords() for i in range (len(data)): search_keywords=data[i][2] search_ip=data[i][-1] search_ip=search_ip.split(',')[0] print(search_keywords,search_ip) find_address(search_ip) <file_sep>/SERVER/jd_vc 日志匹配/log录入.py #获取对应路径下的LOG.EXCEL #通过服务获取excel数据,然后整理导入到数据表 <file_sep>/待自动化运行脚本/zydmall_数据监控/spu_detail.py import datetime import hashlib import requests import re from multiprocessing import Pool import time from bs4 import BeautifulSoup import pymysql def get_pid(url,good_id): s = requests.get(url) content = s.content.decode('utf-8') #print(content) #根据分析ajax请求,需要两个参数,一个goods_id,一个pid #goods_id直接可以从url中获取,pid则需要正则分析源码 soup=BeautifulSoup(content,'html.parser') time=1 try: pid=soup.find('input',attrs={'id':'J-basketNum'}).get('data-id') except AttributeError as e: time+=1 print(e) if time>3: exit() pid='' else: return get_pid(url,good_id) return pid def get_json_data(url): s = requests.get(url) content = s.content.decode('utf-8') #print(content) #full_content="<html><head></head><body><table>"+content+"</table></body></html>" content=content.replace("<div>","").replace("</div>","") #print(content) return content def insert_prt_data(prt_id,good_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit,creation_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_data (prt_id,good_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit,creation_date)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" %(prt_id,good_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit,creation_date) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_prt_data-------Error------Message--------:' + str(err)) cursor.close() db.close() def get_content(html,good_id,num): # 里面分为两块,一块是图片的获取,另一块是整个content的获取,包括修改图片路径 # 1.内容html数据 soup = BeautifulSoup(html, 'html.parser') original_content = soup.find('div', attrs={'class': 'tab_contain'}) # 还需要replace掉所有的图片路径 imgs = original_content.find_all('img') print("当前详情内容里面一共有%s张图片" % str(len(imgs))) if len(imgs)==0: update_good_id_status(good_id,2) # num=0 for img in imgs: num += 1 # 图片的属性,需要名称,url img_title = img.get('title') if img_title == None: img_title = img.get('alt') if img_title == None: img_title = img.get('name') img_title = str(img_title).replace(".jpg", "") original_img_url = img.get('src') try: img_url = original_img_url[0:original_img_url.rindex("?")] except: img_url = original_img_url img_name = img_url[img_url.rindex('/') + 1:100] img_path = "/upload/prt/zyd/" + good_id + "/" + img_name #print(num, img_title, img_name, img_path, img_url) img_no = num img_type = "content" if is_only_price==0: insert_prt_img(good_id, img_name, img_path, img_url, img_no, img_type) # 对content数据进行replace original_content = str(original_content).replace(original_img_url, img_path) if is_only_price==0: insert_prt_desc(good_id, original_content) #print(original_content) #print("++++++++++++++++") def get_good_id(solution): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select good_id from goods_lists_info where status=1 and is_executed=0 "+solution+" limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_good_id_status(good_id,status): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update goods_lists_info set is_executed='%d' where status=1 and good_id='%s' " %(status,good_id) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_good_cnt(): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select count(good_id) as cnt from goods_lists_info where status=1 and is_executed=0 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def main(id,creation_date): # 获取good_id if id ==0: solution="order by table_id" else: solution="order by table_id desc" goods_data = get_good_id(solution) good_id = goods_data[0][0] print("loading the %s ......" % good_id) # 尝试requests请求页面的返回结果 # good_id=str(3752) url = "https://www.zydmall.com/detail/good_" + good_id + ".html" pid= get_pid(url,good_id) print(pid) ajax_url = "https://www.zydmall.com/ashx/detail_products.ashx?goods_id=" + good_id + "&pid=" + pid print(ajax_url) content = get_json_data(ajax_url) # 分析html数据 soup = BeautifulSoup(content, 'html.parser') trs = soup.find_all('tr', attrs={'class': 'pro_list'}) print("共%s条SKU数据" % str(len(trs))) for tr in trs: #print(tr) # tr=str(tr).replace("<div>","").replace("</div>","") tds = tr.find_all('td') po_number = tds[0].find('a').text prt_url = tds[0].find('a').get('href') prt_id = prt_url.split('/')[-1].split('.')[0].split('_')[-1] prt_type = tds[1].find('p').text face_price = tds[2].text discount_price = tds[3].text weight = tds[7].text unit = tds[8].text #print(prt_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit) # ---------------------保存商品基础属性---------------------------------------------- insert_prt_data(prt_id, good_id,po_number, prt_url, prt_type, face_price, discount_price, weight, unit,creation_date) update_good_id_status(good_id,1) print("------------------------------ ") def update_prt_data_status(): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_data set status=0 " try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------update_prt_data_status-------Error------Message--------:' + str(err)) cursor.close() db.close() def get_url_md5(content): m2 = hashlib.md5() m2.update(content.encode('gbk')) md5 = m2.hexdigest() print(md5) return md5 def get_current_date(): now = datetime.datetime.now() md = str(now.year) + "-" + str(now.month) + "-" + str(now.day) + " " + str(now.hour) + ":" + str(now.minute) return md if __name__=="__main__": creation_date=get_current_date() is_only_price=1 update_prt_data_status() cnt_data=get_good_cnt() cnt=cnt_data[0][0] for_times=round(int(cnt)/2,0)+1 for x in range (int(for_times)): start = time.time() p = Pool() for i in range(2): p.apply_async(func=main, args=(i,creation_date)) p.close() p.join() end = time.time() <file_sep>/untitled/Selenium/天眼查/天眼查4.0.py import pymysql from selenium import webdriver import time def get_company_name_from_mysql(): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select * from company_info where status=0 " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_data_to_mysql(company_name,check_company_name,register_num,orginization_code,unified_credit_code, company_type,identification_number_of_tax, industry,business_term, issue_date,registration_authority, english_name,registration_address, scope_of_operation,providence,status): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update company_info set check_company_name='%s',register_num='%s',orginization_code='%s',unified_credit_code='%s', company_type='%s',identification_number_of_tax='%s', industry='%s',"\ "business_term='%s', issue_date='%s',registration_authority='%s', english_name='%s',registration_address='%s', scope_of_operation='%s',providence='%s',status='%d' " \ "where company_name='%s'"\ %(check_company_name,register_num,orginization_code,unified_credit_code, company_type,identification_number_of_tax, industry,business_term, issue_date,registration_authority, english_name,registration_address, scope_of_operation,providence,status,company_name) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_data_to_mysql-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #从数据表取出数据 company_name_data=get_company_name_from_mysql() browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get('https://www.tianyancha.com/login') time.sleep(1) driver.find_elements_by_css_selector('._input.input_nor.contactphone')[1].send_keys('15505281667') driver.find_elements_by_css_selector('._input.input_nor.contactword')[1].send_keys('qq111111') driver.find_elements_by_css_selector('.c-white.b-c9.pt8.f18.text-center.login_btn')[1].click() time.sleep(3) for i in range(len(company_name_data)): company_name=company_name_data[i][0] #company_name="北京可视化智能科技股份有限公司" print(company_name) #把company_name带入到url中进行查询 url="https://www.tianyancha.com/search?key="+company_name+"&checkFrom=searchBox" print(url) driver.get(url) html=driver.page_source company_detail_url="" company_providence="" new_company_name="" #html是列表页的数据,我需要三项,公司名称,URL,省份 company_lists=driver.find_elements_by_css_selector('.query_name.sv-search-company.f18.in-block.vertical-middle') company_providence_data=driver.find_elements_by_css_selector('.in-block.vertical-middle.float-right') print("当前页一共%s条数据"%str(len(company_lists))) #如果列表上没有数据,那么就是0,反回结果,标注状态是2,未找到对应数据 if len(company_lists)==0: try: msg=driver.find_element_by_css_selector('.f24.mb40.mt40.sec-c1').text print(msg) if "抱歉" in msg: update_data_to_mysql(company_name, "", "", "", "", "", "", "", "", "", "", "", "", "", "", 2) else: update_data_to_mysql(company_name, "", "", "", "", "", "", "", "", "", "", "", "", "", "", 3) except: update_data_to_mysql(company_name, "", "", "", "", "", "", "", "", "", "", "", "", "", "", 3) else: #因为存在一些问题,所以只取第一条的结果 for j in range (1): tmp_company_name=company_lists[j].find_element_by_tag_name('span').text tmp_company_url=company_lists[j].get_attribute('href') tmp_company_providence=company_providence_data[j].find_elements_by_tag_name('span')[0].text print(tmp_company_name,tmp_company_providence,tmp_company_url) print("找到一致的数据,准备返回结果") #如果公司名称一致,那么就不用填入新的公司名称,反之填写,主要用于数据核对 if tmp_company_name==company_name: new_company_name="" else: new_company_name=tmp_company_name company_detail_url = tmp_company_url company_providence = tmp_company_providence driver.get(company_detail_url) html=driver.page_source table_data=driver.find_elements_by_xpath("//div[@id='_container_baseInfo']/div/div[@class='base0910']/table[@class='table companyInfo-table f14']/tbody/tr") if len(table_data)==7: #if length values 7 ,next,else,except register_num=table_data[0].find_elements_by_tag_name('td')[1].text orginization_code = table_data[0].find_elements_by_tag_name('td')[3].text print(register_num,orginization_code) unified_credit_code = table_data[1].find_elements_by_tag_name('td')[1].text company_type = table_data[1].find_elements_by_tag_name('td')[3].text print(unified_credit_code, company_type) identification_number_of_tax = table_data[2].find_elements_by_tag_name('td')[1].text industry = table_data[2].find_elements_by_tag_name('td')[3].text print(identification_number_of_tax, industry) business_term = table_data[3].find_elements_by_tag_name('td')[1].text issue_date = table_data[3].find_elements_by_tag_name('td')[3].text print(business_term, issue_date) registration_authority = table_data[4].find_elements_by_tag_name('td')[1].text english_name = table_data[4].find_elements_by_tag_name('td')[3].text english_name=pymysql.escape_string(english_name) print(registration_authority, english_name) registration_address = table_data[5].find_elements_by_tag_name('td')[1].text scope_of_operation= table_data[6].find_elements_by_tag_name('td')[1].text print(registration_address, scope_of_operation) update_data_to_mysql(company_name,new_company_name,register_num,orginization_code,unified_credit_code, company_type,identification_number_of_tax, industry,business_term, issue_date,registration_authority, english_name,registration_address, scope_of_operation,company_providence,1) time.sleep(3) <file_sep>/untitled/Selenium/众业达/众业达3.0/zydmall-列表页获取good_idV1.0.py #来源:"http://www.zydmall.com/brand/list_84.html" #输出:hangshen数据库,goods_lists_info表数据,27条 from selenium import webdriver import time from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import random import pymysql from bs4 import BeautifulSoup class sql_data(): def insert_goods_lists(self,good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand): db = pymysql.connect("localhost", "root", "123456", "zydmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into goods_lists_info(good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def s(a,b): rand=random.randint(a,b) time.sleep(rand) def find_prt_lists(page_num): for i in range (int(page_num)): html = driver.page_source soup=BeautifulSoup(html,'html.parser') div_data=soup.find("div",attrs={'class':'clearfix com_show_list listc333'}) div_lists=div_data.find_all("div",attrs={'class':'item'}) print("当前%s页共%s条数据"%(str(i+1),str(len(div_lists)))) #获取数据 for div_list in div_lists: # good(SPU)商品详情url good_url=div_list.find('a',attrs={'class':'pic'}).get('href').replace(" ","") good_url="http://www.zydmall.com"+good_url #good商品ID good_id=good_url[good_url.rindex('good_')+5:good_url.rindex('.html')] list_img=div_list.find('a',attrs={'class':'pic'}).find('img') original_pic=list_img.get('src').replace(" ","") #图片名称 pic_name=original_pic[original_pic.rindex('/')+1:100] #图片原始url original_pic_url=original_pic #更新后的图片路径 pic_path="/upload/prt/zyd/"+good_id+"/"+pic_name #print("","good_id:",good_id,"\n","good_url:",good_url,"\n","original_pic_url:",original_pic_url,"\n","pic_name:",pic_name,"\n","pic_path:",pic_path) title=div_list.find('a',attrs={'class':'title'}).text good_price=div_list.find('span').text.replace(" ","") cnt=div_list.find('i',attrs={'class':'fl'}).text.replace(" ","") brand=div_list.find('i',attrs={'class':'fr'}).text.replace(" ","") #print("", "title:", title, "\n", "good_price:", good_price, "\n", "cnt:", cnt, "\n", "brand:", brand,"\n") mysql_data=sql_data() mysql_data.insert_goods_lists(good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand) next_page() def next_page(): try: driver.find_element_by_xpath("//a[@class='last']").click() s(5,7) except: print("have no next page!") if __name__=="__main__": #url_lists=[ 'https://www.zydmall.com/brand/list_78.html', 'https://www.zydmall.com/brand/list_80.html', 'https://www.zydmall.com/brand/list_79.html', 'https://www.zydmall.com/brand/list_85.html', 'https://www.zydmall.com/brand/list_82.html', 'https://www.zydmall.com/brand/list_81.html' ] url_lists=['https://www.zydmall.com/brand/list_85.html'] #page_nums=[21] #page_nums = [21, 16, 6, 10, 10, 8] page_nums=[10] browser="Firefox" if browser=="Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser=="Firefox": driver=webdriver.Firefox() else: driver=webdriver.PhantomJS() for i in range (len(url_lists)): page_num=page_nums[i] url=url_lists[i] driver.get(url) wait1 = WebDriverWait(driver, 15) s(4,5) #print(html) find_prt_lists(page_num)<file_sep>/测试链接oracle.py #coding:utf-8 import cx_Oracle db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.31.10:7018/mmbao2b2c') print (db.version) cursor=db.cursor() sql="SELECT ID from mmbao2.t_prt_entity where shop_id='1781956' " cursor.execute(sql) row=cursor.fetchall() for f in row: print(f) cursor.close() db.close() <file_sep>/待自动化运行脚本/zydmall_数据监控/brand_list监控.py import pymysql import datetime import requests import hashlib from bs4 import BeautifulSoup class brand_info(): def get_brand_info(self): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select brand_name,brand_url from brand_list where status=1 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def filed_history(self,table_name): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update "+table_name+" set status=0 " try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_current_date(self): now = datetime.datetime.now() md = str(now.year)+"-"+str(now.month)+"-"+str(now.day)+" "+str(now.hour)+":"+str(now.minute) return md def find_basic_list(self,ajax_url): #根据brand_url获取当前页面的html数据 content=self.get_content(ajax_url) soup = BeautifulSoup(content, 'html.parser') page_value=soup.find('input',attrs={'class':'action-pagedata'}).get('value') page_total=page_value.split('pagetotal:')[-1].split('}')[0] total=page_value.split('{total:')[-1].split(',')[0] print("total:%s,page_total:%s"%(total,page_total)) return content,total,page_total def find_list_data(self,ajax_url,current_date): content=self.get_content(ajax_url) soup = BeautifulSoup(content, 'html.parser') items = soup.find_all('div', attrs={'class': 'item'}) print("current page have %s records" % (str(len(items)))) for i in range(len(items)): spu_title = items[i].find('a', attrs={'class': 'title'}).text spu_href = items[i].find('a', attrs={'class': 'title'}).get('href') spu_id = spu_href.split("_")[-1].split(".")[0] spu_price = items[i].find('span').text spu_cnt = items[i].find('i', attrs={'class': 'fl'}).text spu_brand = items[i].find('i', attrs={'class': 'fr'}).text list_img = items[i].find('a', attrs={'class': 'pic'}).find('img') original_pic = list_img.get('src').replace(" ", "") # 图片名称 pic_name = original_pic[original_pic.rindex('/') + 1:100] # 图片原始url original_pic_url = original_pic # 更新后的图片路径 self.insert_goods_lists(spu_id, spu_href, original_pic_url, pic_name, "", spu_title, spu_price, spu_cnt, spu_brand,current_date) def insert_goods_lists(self,good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand,current_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into goods_lists_info(good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand,creation_date)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand,current_date) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def get_content(self,url): s = requests.get(url, headers=headers) content = s.content.decode('utf=8') #print(content) return content def insert_current_brand_data(self,brand_name,brand_url,page_num,total_num,status,md5,control_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into brand_list(brand_name,brand_url,page_num,total_num,status,md5,control_date)" \ "values('%s','%s','%d','%d','%d','%s','%s')" \ % (brand_name,brand_url,int(page_num),int(total_num),status,md5,control_date) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def get_url_md5(self,content): m2 = hashlib.md5() m2.update(content.encode('gbk')) md5=m2.hexdigest() print(md5) return md5 if __name__=="__main__": brand=brand_info() brand_data=brand.get_brand_info() #取出brand_data后,将数据表的数据置为历史,状态变为0,然后重新插入一组数据 brand.filed_history('brand_list') brand.filed_history('goods_lists_info') #循环插入新的待处理brand_list for i in range (len(brand_data)): brand_name=brand_data[i][0] brand_url=brand_data[i][1] #在以上的两个字段中,还需要其他的,所以还是一次性处理后再insert headers = { "Host": "www.zydmall.com", "Accept": "text/html, */*; q=0.01", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer": brand_url, "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" } #获取ajax——url brand_id=brand_url.split("_")[-1].split(".")[0] print(brand_id) ajax_url="https://www.zydmall.com/ashx/brand_product_list.ashx?br="+str(brand_id) #page_num需要提前获取 #page_num,total_num, content,total,page_total=brand.find_basic_list(ajax_url) basic_ajax = ajax_url #current_date current_date=brand.get_current_date() for page in range (int(page_total)): current_page=page+1 if current_page==1: pass else: ajax_url=basic_ajax+"&page="+str(current_page) print(ajax_url) brand.find_list_data(ajax_url,current_date) #md5 md5=brand.get_url_md5(content) #o代表历史记录,1代表新增的有效数据 status=1 brand.insert_current_brand_data(brand_name,brand_url,page_total,total,status,md5,current_date) <file_sep>/MMBAO.COM遍历URL筛选404链接-1.1/层级遍历-分类-店铺列表篇-url_code.py import urllib.request import urllib.error from bs4 import BeautifulSoup import re import os import pymysql import xlrd import requests def insert_data(url,href_up,info,state): db = pymysql.connect("localhost", "root", "123456", "tmp") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into MMB_URL_FILTER(url,href_up,info,state)"\ "values('%s','%s','%s','%s')"\ %(url,href_up,info,state) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def getHtml(url): #print("正在打开网页并获取....") try: headers = { 'Host': 'static.doutula.com', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Accept': 'text/html, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0', 'DNT': '1', 'Cookie':'UM_distinctid=15b9383310948-0002cb8d0502a88-1262694a-1fa400-15b9383310a307; _ga=GA1.2.26294925.1492828501; _gid=GA1.2.2135841525.1498612877; _gat=1', 'Referer': 'http://www.doutula.com/article/list?page=1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' } data=None req=urllib.request.Request(url,data) response = urllib.request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") #print(Html) except: Html="" return Html def filter_404_error(url): code = requests.get(url).status_code print(code) update_url_code_data(url, code) state = 0 return state def update_url_code_data(url,code): db = pymysql.connect("localhost", "root", "123456", "tmp", charset="utf8") cursor = db.cursor() sql = "update url_code set code='%s' where href_current='%s' and status=0 limit 1" %(code,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def filter_url_1(html,state,href_up): if state==0: try: soup=BeautifulSoup(html,"html.parser") error_1=soup.find("div",attrs={"class":"s1"}).text error_1_msg=error_1.replace("\n","").replace(" ","") print(error_1_msg) state=1 insert_data(url,href_up, error_1_msg, state) return state except: print("pass the first fliter solution") state=0 return state else: return state def filter_url_2(html,state,href_up): if state==0: try: soup=BeautifulSoup(html,"html.parser") error_1=soup.find("div",attrs={"class":"good_list clearfix"}).find('div').find('span').text print(error_1.replace("\n","")) if "没有您搜索的商品哦" in error_1: error_1_msg=error_1.replace("\n","") #print(error_1_msg) state = 2 insert_data(url,href_up, error_1_msg, state) else: print("pass the second fliter solution") state = 0 #insert_data(url, error_1, state) return state except: print("pass the second fliter solution") state=0 return state else: return state def filter_url_3(html, state,href_up): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"class": "no-search"}).find('p').text print(error_1) if error_1 == "您搜索的电缆暂无报价,赶紧试试": error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,href_up, error_1_msg, state) else: print("pass the third fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the third fliter solution") state = 0 return state else: return state def filter_url_4(html, state,href_up): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"class": "search-none clearfix yahei mt20 cry-icon"}).find('h2').text print(error_1) if "非常抱歉!没有找到与" in error_1: error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,href_up, error_1_msg, state) else: print("pass the third fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the third fliter solution") state = 0 return state else: return state def filter_url_5(html, state,href_up): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"class": "search-none clearfix yahei mt20 cry-icon"}).find('h2').text print(error_1) if "非常抱歉!没有找到" in error_1: error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,href_up, error_1_msg, state) else: print("pass the fourth fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the fourth fliter solution") state = 0 return state else: return state def filter_url_6(html,href_up, state): if state == 0: try: soup = BeautifulSoup(html, "html.parser") error_1 = soup.find("div", attrs={"id": "SD_content"}).text print(error_1) if "您查看的店铺已关闭或暂时无商品" in error_1: error_1_msg = error_1.replace("\n", "") # print(error_1_msg) state = 2 insert_data(url,href_up, error_1_msg, state) else: print("pass the fifth fliter solution") state = 0 # insert_data(url, error_1, state) return state except: print("pass the fifth fliter solution") state = 0 return state else: return state #从excel中获取url的列表数据 def get_data_from_excel(sheet_num): data=xlrd.open_workbook(r"D:\BI\关键词筛选\竞价URL.xlsx") #打开excel sheetName = data.href_ups()[sheet_num] table=data.sheets()[sheet_num] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 url_lists=[] print(sheetName) for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss url_lists.append(ss) return url_lists,sheetName def get_url(): db = pymysql.connect("localhost", "root", "123456", "tmp", charset="utf8") cursor = db.cursor() sql = "select href_current,href_up from url_code where status=0" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('-------get_url--------Error------Message--------:' + str(err)) db.close() cursor.close() def update_data(href_current): db = pymysql.connect("localhost", "root", "123456", "tmp", charset="utf8") cursor = db.cursor() sql = "update url_code set status=1 where href_current='%s' and status=0 limit 1" %(href_current) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": #url来自数据库,或者excel都可以 data = get_url() for i in range (len(data)): url=data[i][0] href_up=data[0][1] print(str(i+1),url) html = getHtml(url) if html == "": state = '2' insert_data(url, href_up, "have no html", state) else: # 分析一波html state = filter_404_error(url) state = filter_url_1(html, state, href_up) state = filter_url_2(html, state, href_up) state = filter_url_3(html, state, href_up) state = filter_url_4(html, state, href_up) state = filter_url_5(html, state, href_up) if state == 0: info = " " insert_data(url, href_up, info, state) update_data(url) <file_sep>/untitled/Selenium/dq123/公司对应的系列信息.py from selenium import webdriver driver=webdriver.Firefox() #driver.set_window_size(1400,900) driver.get("http://www.dq123.com/price/data2/2/p/1089.js?v=20160411") print(driver.page_source) li=driver.find_elements_by_xpath("//ul[@id='classtreeele']/li[@class='level0']") print("一级目录共"+str(len(li))) for i in range(len(li)): print(li[i].text) a=li[i].find_element_by_xpath("//a[@class='level0']").get_attribute('title') print(a) <file_sep>/suning/罗格朗/legrand-处理详情页的内容获取.py import pymysql import time from selenium import webdriver from bs4 import BeautifulSoup def get_prt_lists(): db = pymysql.connect("localhost", "root", "123456", "legrand_suning", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select prt_id,prt_url from legrand_prt_list where status=0 " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_prt_status(prt_id,status): db = pymysql.connect("localhost", "root", "123456", "legrand_suning", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update legrand_prt_list set status='%d' where prt_id='%s' " %(status,prt_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_html(prt_id,prt_url): driver.get(prt_url) #等待页面相应完成 html=driver.page_source time.sleep(10) return html def find_useful_info(html): soup=BeautifulSoup(html,'html.parser') #prt_name的获取 prt_name=soup.find('h1',attrs={'id':'itemDisplayName'}).get_text() print("prt_name:%s"%prt_name) #参考价,活动价 try: small_price=soup.find('del',attrs={'class':'small-price'}).get_text().replace(" ","") except AttributeError as e: small_price="" main_price=soup.find('span',attrs={'class':'mainprice'}).get_text().replace(" ","") print("small_price:%s,main_price:%s"%(small_price,main_price)) try: #颜色,类型 prt_type_info=soup.find('dl',attrs={'class':'proinfo-color-ex proattr-radio'}).find('li',attrs={'class':'clr-item selected'}) prt_type=prt_type_info.find('a').get_text().replace(" ","") prt_item_id=prt_type_info.find('a').get('name') prt_color_info = soup.find('dl', attrs={'class': 'proinfo-buytype proattr-radio'}).find('li', attrs={'class': 'clr-item selected'}) prt_color=prt_color_info.find('a').get_text().replace(" ","") print("prt_type:%s,prt_item_id:%s,prt_color:%s" % (prt_type, prt_item_id,prt_color)) #详情内容 prt_detail_parts=soup.find('div',attrs={'id':'productDetail'}).find_all('p') print("%s块详情内容"%str(len(prt_detail_parts))) prt_detail='<div id="productDetail" class="pro-detail-pics">' img_desc_data=[]### for i in range(len(prt_detail_parts)): prt_detail=str(prt_detail)+str(prt_detail_parts[i]) prt_detail=prt_detail+"</div>"### print(prt_detail) #详情内容的图片 for i in range(len(prt_detail_parts)): try: img_desc_infos=prt_detail_parts[i].find_all('img',attrs={'class':'err-product'}) except AttributeError as e: pass for j in range(len(img_desc_infos)): img_desc_info=img_desc_infos[j].get('src2') img_desc_data.append(img_desc_info) for x in range(len(img_desc_data)): print(img_desc_data[x]) #商品主图,分为SKU图片和SPU图片 prt_spu_img_info=[] #SKU图片 prt_sku_img=prt_type_info.find('img').get('src') prt_sku_img_url="http:"+prt_sku_img print("sku_img_url:%s"%prt_sku_img_url)### #SPU图片 prt_spu_img_data=soup.find('div',attrs={'class':'imgzoom-thumb-main'}).find_all('img') for i in range (len(prt_spu_img_data)): prt_spu_img="http:"+prt_spu_img_data[i].get('src-large') if prt_spu_img==prt_sku_img_url: pass #不存储 else: prt_spu_img_info.append(prt_spu_img) print(prt_spu_img_info)### #itemParameter,参数部分,因为考虑到数据准确性,只取型号一个 itemParameter=soup.find('table',attrs={'id':'itemParameter'}).find_all('tr') #print(itemParameter) prt_type_name="" prt_leibie="" prt_mingcheng="" prt_kaiguanleixing="" for i in range (len(itemParameter)): try: #print(itemParameter[i]) tmp_name=itemParameter[i].find('div',attrs={'class':'name-inner'}).find('span').get_text() tmp_value=itemParameter[i].find('td',attrs={'class':'val'}).get_text() #print(tmp_name,tmp_value) if "型号" in tmp_name: prt_type_name=tmp_value.replace(" ","") if "类别" in tmp_name: prt_leibie=tmp_value.replace(" ","") if "名称" in tmp_name: prt_mingcheng=tmp_value.replace(" ","") if "开关类型" in tmp_name: prt_kaiguanleixing=tmp_value.replace(" ","") except AttributeError as e: #print(e) pass print(prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing) ####### #数据都已检出,后续是将这些数据插入到数据表中 #insert_data_to_prt_info(prt_id, prt_url, prt_name,small_price,main_price,prt_type, prt_item_id,prt_color,prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing) #详情内容 #insert_data_to_prt_desc(prt_id,prt_detail) #图片 for m in range (len(prt_spu_img_info)): insert_data_to_prt_img(prt_id, prt_spu_img_info[m],'good_img') insert_data_to_prt_img(prt_id, prt_sku_img_url, 'sku_img') for n in range (len(img_desc_data)): insert_data_to_prt_img(prt_id, img_desc_data[n], 'desc_img') status=1 return status except AttributeError as e: status=2 return status def insert_data_to_prt_info(prt_id, prt_url, prt_name,small_price,main_price,prt_type, prt_item_id,prt_color,prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing): db = pymysql.connect("localhost", "root", "123456", "legrand_suning", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into legrand_prt_info (prt_id, prt_url, prt_name,small_price,main_price,prt_type, prt_item_id,prt_color,prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(prt_id, prt_url, prt_name,small_price,main_price,prt_type, prt_item_id,prt_color,prt_type_name,prt_leibie,prt_mingcheng,prt_kaiguanleixing) print(sql) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_data_to_prt_info-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_data_to_prt_desc(prt_id,prt_desc): db = pymysql.connect("localhost", "root", "123456", "legrand_suning", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into legrand_prt_desc (prt_id,prt_desc) values('%s','%s')" %(prt_id,prt_desc) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_data_to_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_data_to_prt_img(prt_id, img_url,img_type): db = pymysql.connect("localhost", "root", "123456", "legrand_suning", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into legrand_prt_img (prt_id,img_url,img_type) values('%s','%s','%s')" %(prt_id,img_url,img_type) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_data_to_prt_img-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() data=get_prt_lists() for i in range(len(data)): #status=1 prt_id=data[i][0] prt_url = data[i][1] print(prt_id,prt_url) #打开url,对数据进行一系列的分析抓取 html=get_html(prt_id,prt_url) #把html的内容通过bs4进行检查 status=find_useful_info(html) time.sleep(10) #处理完成后更新状态 update_prt_status(prt_id,status) <file_sep>/javmoo/film_basic.py import requests import pymysql from bs4 import BeautifulSoup class data_procurement(): #从url中获取json的那块源码,以及整体的html源码 def get_content(self,url): s = requests.get(url, headers=headers) content = s.content.decode('utf-8') #print(content) return content def get_character_info(self): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select character_id,name,url,status from character_url where status=0" # print(sql) try: execute=cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as e: db.rollback() print('------table_data_delete---------Error------Message--------:' + str(e)) cursor.close() db.close() def get_character_basic_info(self,character_id,content): soup=BeautifulSoup(content,'html.parser') basic_div=soup.find('div',attrs={'class':'avatar-box'}) try: photo=basic_div.find('div',attrs={'class':'photo-frame'}).find('img').get('src') except AttributeError as e: photo="" #print(photo) character_name = basic_div.find('div', attrs={'class': 'photo-info'}).find('span').text print(character_name) basic_p=basic_div.find('div',attrs={'class':'photo-info'}).find_all('p') birth_date=basic_p[0].text age = basic_p[1].text bust = basic_p[2].text waist = basic_p[3].text hipline = basic_p[4].text hobby = basic_p[5].text print(birth_date,age,bust,waist,hipline,hobby) status=1 self.insert_basic_character_info(photo,character_name,birth_date,age,bust,waist,hipline,hobby,status,character_id) def insert_basic_character_info(self,photo,character_name,birth_date,age,bust,waist,hipline,hobby,status,character_id): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update character_url set name='%s',photo='%s',birth_date='%s',age='%s',bust='%s',waist='%s',hipline='%s',hobby='%s',status='%d' where character_id='%s' "\ %(character_name,photo,birth_date,age,bust,waist,hipline,hobby,status,character_id) # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------insert_basic_character_info---------Error------Message--------:' + str(e)) cursor.close() db.close() def find_films_info(self,character_id,content): soup=BeautifulSoup(content,'html.parser') div_items=soup.find_all('div',attrs={'class':'item'}) film_num=len(div_items) print("current page have %s records"%str(film_num)) for i in range (len(div_items)): #print(div_items[i]) try: movie_box=div_items[i].find('a',attrs={'class':'movie-box'}) film_href=movie_box.get('href') film_id = film_href.split("/")[-1] #print(film_id,film_href) film_img_url = div_items[i].find('div',attrs={'class':'photo-frame'}).find('img').get('src') #print(film_img_url) film_title = div_items[i].find('div',attrs={'class':'photo-frame'}).find('img').get('title') film_info = div_items[i].find('div', attrs={'class': 'photo-info'}).find('span').find_all('date') designation=film_info[0].text release_date=film_info[1].text #print(film_title,designation,release_date) self.insert_film_basic_info(film_id,character_id,film_href,film_img_url,film_title,designation,release_date) except AttributeError as e: #print(e) pass #print("##############################") return film_num def insert_film_basic_info(self,film_id,character_id,film_href,film_img_url,film_title,designation,release_date): db = pymysql.connect("localhost", "root", "123456", "javmoo") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into film_basic_info (film_id,character_id,film_href,film_img_url,film_title,designation,release_date) values('%s','%s','%s','%s','%s','%s','%s')" \ % (film_id,character_id,film_href,film_img_url,film_title,designation,release_date) # print(sql) try: cursor.execute(sql) db.commit() except Exception as e: db.rollback() print('------insert_film_basic_info---------Error------Message--------:' + str(e)) cursor.close() db.close() if __name__=="__main__": headers = { "Host":"javmoo.net", "Accept": "text/html,application/xhtml+xml,application/xml;", "Accept-Encoding": "gzip", "Accept-Language": "zh-CN,zh;q=0.8", "Referer": "https://javmoo.net/", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } load_data = data_procurement() #获取mysql原始url信息 data=load_data.get_character_info() for i in range (len(data)): character_id=data[i][0] character_name=data[i][1] url=data[i][2] character_status=data[i][3] page_num = 2 while 1==1: content = load_data.get_content(url) #如果状态为0,需要获取基本信息,为1则跳过 if int(character_status)==0: if page_num==2: load_data.get_character_basic_info(character_id,content) #进行影片信息的获取 film_num=load_data.find_films_info(character_id,content) if film_num==0: break #循环内部,实现翻页 url=url+"/page/"+str(page_num) page_num+=1 <file_sep>/ZYDMALL/zydmall_德力西/zydmall-德力西-详情V1.0.py #来源:"http://www.zydmall.com/brand/list_84.html" #输出:hangshen数据库,goods_lists_info表数据,27条 from selenium import webdriver import time from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import random import pymysql from bs4 import BeautifulSoup from urllib import request def s(a,b): rand=random.randint(a,b) time.sleep(rand) def getHtml(url): #print("正在打开网页并获取....") try: headers = { 'Host': 'www.zydmall.com', #'Connection': 'keep-alive', #'Cache-Control': 'max-age=0', #'Accept': 'text/html, */*; q=0.01', #'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0', #'DNT': '1', #'Cookie':'searchshistory1=3287; searchshistory2=3292; _pk_id.1.0aa1=bbf5c91a20434919.1491801107.4.1506132768.1499327581.; Hm_lvt_0d4eb179db6174f7994d97d77594484e=1506132763,1506297666; ASP.NET_SessionId=1hnzbvzsotch0z2wphfu5doe; Hm_lpvt_0d4eb179db6174f7994d97d77594484e=1506304176', #'Referer': 'http://www.doutula.com/article/list?page=1', #'Accept-Encoding': 'gzip, deflate, br', #'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' } data=None req=request.Request(url,data,headers) response = request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") #print(Html) except: print("获取html异常!") Html="" return Html class sql_data(): def insert_goods_lists(self,good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand): db = pymysql.connect("localhost", "root", "<PASSWORD>", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into goods_lists_info(good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_category(self,good_id,cate1_name,cate1_href,cate2_name,cate2_href,cate3_name,cate3_href,cate4_name,cate4_href,prt_name): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_category(prt_id,cate1_name,cate1_href,cate2_name,cate2_href,cate3_name,cate3_href,cate4_name,cate4_href,prt_name)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (good_id,cate1_name,cate1_href,cate2_name,cate2_href,cate3_name,cate3_href,cate4_name,cate4_href,prt_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_base_attrs(self,good_id,prt_title,prt_type,prt_po_Number,discount_price,brand_name,face_price,series_name): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_entity(prt_id,prt_title,prt_type,prt_po_number,brand_name,discount_price,face_price,series_name)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s')" \ % (good_id, prt_title,prt_type,prt_po_Number,brand_name,discount_price,face_price,series_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_prt_img(self,good_id,img_name,img_path,original_img_url,img_no,img_type): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_img_info(prt_id,img_name,img_path,original_url,img_num,img_type)" \ "values('%s','%s','%s','%s','%d','%s')" \ % (good_id,img_name,img_path,original_img_url,img_no,img_type) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_prt_desc(self,prt_id,prt_desc): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_desc(prt_id,prt_desc)" \ "values('%s','%s')" \ % (prt_id,prt_desc) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_sku_data(self,prt_id,sku_id,sku_href,a_title,sku_type,face_price,discount_price,stock,weight,unit,po_number): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_sku(prt_id,sku_id,sku_href,a_title,sku_type,face_price,discount_price,stock,weight,unit,po_number)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (prt_id,sku_id,sku_href,a_title,sku_type,face_price,discount_price,stock,weight,unit,po_number) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_attributes(self,sku_id,attr_name,attr_value,attr_num): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_attribute(sku_id,attribute_name,attribute_value,attribute_num)" \ "values('%s','%s','%s','%s')" \ % (sku_id,attr_name,attr_value,attr_num) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() class prt_detail_data(): #获取类目数据 def get_category(self,html,good_id): soup=BeautifulSoup(html,"html.parser") a_s=soup.find('div',attrs={'class':'page_posit'}).find_all('a') cate1_name=a_s[0].text cate1_href=a_s[0].get('href') cate2_name=a_s[1].text cate2_href=a_s[1].get('href') cate3_name=a_s[2].text cate3_href=a_s[2].get('href') cate4_name=a_s[3].text cate4_href=a_s[3].get('href') prt_name=soup.find('span',attrs={'class':'c333'}).text print(good_id,cate1_name,cate1_href,cate2_name,cate2_href,cate3_name,cate3_href,cate4_name,cate4_href,prt_name) mysql=sql_data() mysql.insert_category(good_id,cate1_name,cate1_href,cate2_name,cate2_href,cate3_name,cate3_href,cate4_name,cate4_href,prt_name) print("++++++++++++++++") #获取基础属性,如订货号,折扣价,面价,系列等 def get_base_attrs(self,html,good_id): soup = BeautifulSoup(html, "html.parser") #商品名称 prt_title=soup.find('h3',attrs={'class':'c333 fw f20 h20'}).text divs_1=soup.find('div',attrs={'class':'pro_desc clearfix mt20'}).find_all('p') #产品型号 prt_type_check = divs_1[0].find('b').text if prt_type_check == "产品型号:": prt_type = divs_1[0].find('span').text else: prt_type = "ERROR!" #订货号 prt_po_Number_check = divs_1[1].find('b').text if "订" in prt_po_Number_check: prt_po_Number = divs_1[1].find('span', attrs={'class': 'ceb6161'}).text else: prt_po_Number = "ERROR!" print("", "prt_title:", prt_title, "\n", "prt_type:", prt_type, "\n", "prt_po_Number:", prt_po_Number) divs_2=soup.find('div',attrs={'class':'pro_price clearfix'}).find_all('p') #验证 if len(divs_2)==4: # 折扣价 # 验证 discount_price_check = divs_2[0].find('b').text if discount_price_check=="折扣价:": discount_price = divs_2[0].find('span', attrs={'class': 'f30 ceb6161 fw t-count'}).text else: discount_price="ERROR!" #品牌 brand_check = divs_2[1].find('b').text if brand_check=="品牌:": brand_name = divs_2[1].find('span', attrs={'class': 'mr10'}).text else: brand_name="ERROR!" #面价 face_price_check = divs_2[2].find('b').text if face_price_check=="面价:": face_price = divs_2[2].find('span', attrs={'class': 'c333 mline'}).text else: face_price="ERROR!" #系列 series_check = divs_2[3].find('b').text if series_check=="系列:": series_name = divs_2[3].find('span').text else: series_name="ERROR!" print("", "discount_price:", discount_price, "\n", "brand_name:", brand_name, "\n", "face_price:", face_price, "\n", "series_name:", series_name) mysql = sql_data() mysql.insert_base_attrs(good_id,prt_title,prt_type,prt_po_Number,discount_price,brand_name,face_price,series_name) else: print("出现异常,只有%s条基础属性"%str(len(divs_2))) print("++++++++++++++++") #获取销售属性,如壳架电流,分断能力等 def get_sale_attrs(self,html): soup=BeautifulSoup(html,'html.parser') divs_3=soup.find('div',attrs={'class':'pro_desc clearfix'}).find_all('p') print("共%s条销售属性"%str(len(divs_3))) for div_3 in divs_3: attr_name=div_3.find('b').text.replace(" ","") attr_value=div_3.find('span').text print("attr_name,attr_value:",attr_name,attr_value) print("++++++++++++++++") #获取商品图片 def get_prt_imgs(self,html,good_id): soup=BeautifulSoup(html,'html.parser') thumblists=soup.find('ul',attrs={'id':'thumblist'}).find_all('li') num=0 for li in thumblists: num+=1 img=li.find('img').get('big') original_img_url=img img_name=img[img.rindex("/")+1:100] img_path="/upload/prt/zyd/" + good_id + "/" + img_name img_no=num img_type="prt_img" print(img_no,img_name,img_path,original_img_url) mysql = sql_data() mysql.insert_prt_img(good_id,img_name,img_path,original_img_url,img_no,img_type) print("++++++++++++++++") return num #获取详情内容+里面的图片 def get_content(self,html,good_id,num): #里面分为两块,一块是图片的获取,另一块是整个content的获取,包括修改图片路径 #1.内容html数据 soup=BeautifulSoup(html,'html.parser') original_content=soup.find('div',attrs={'class':'tab_contain'}) #还需要replace掉所有的图片路径 imgs=original_content.find_all('img') print("当前详情内容里面一共有%s张图片"%str(len(imgs))) #num=0 for img in imgs: num+=1 #图片的属性,需要名称,url img_title=img.get('title') if img_title==None: img_title = img.get('alt') if img_title ==None: img_title = img.get('name') img_title=str(img_title).replace(".jpg","") original_img_url=img.get('src') try: img_url=original_img_url[0:original_img_url.rindex("?")] except: img_url=original_img_url img_name=img_url[img_url.rindex('/')+1:100] img_path="/upload/prt/zyd/" + good_id + "/" + img_name print(num,img_title,img_name,img_path,img_url) img_no=num img_type="content" mysql = sql_data() mysql.insert_prt_img(good_id, img_name, img_path, img_url, img_no, img_type) #对content数据进行replace original_content=str(original_content).replace(original_img_url,img_path) mysql = sql_data() mysql.insert_prt_desc(good_id, original_content) #print(original_content) print("++++++++++++++++") def get_spu_link(self,html,good_id,count): soup=BeautifulSoup(html,'html.parser') product_lists=soup.find('tbody',attrs={'id':'product_list'}).find_all('tr') soup = BeautifulSoup(html, 'html.parser') table=soup.find('div',attrs={'class':'product_table'}).find_all('tbody')[0] ths=table.find_all('tr')[0].find_all('th') print("共%s条销售属性"%str(len(ths)-9)) try: s(3, 5) po_number = product_lists[0].find_all('td')[0].find('a').text except: print("waiting...") s(10,15) for product_list in product_lists: prt_tds=product_list.find_all('td') po_number = prt_tds[0].find('a').text prt_href = prt_tds[0].find('a').get('href') prt_id=prt_href[prt_href.rindex("_")+1:prt_href.rindex(".html")] prt_href='http://www.zydmall.com'+prt_href a_title=prt_tds[0].find('a').get('title')#我也不知道干嘛的,留着再讲 prt_type=prt_tds[1].find('p').text face_price=prt_tds[2].text discount_price = prt_tds[3].find('b').text stock=prt_tds[4].text weight = prt_tds[7].text unit = prt_tds[8].text.replace(" ","") print(po_number,prt_id,prt_href,a_title,prt_type,face_price,discount_price,stock,weight,unit) mysql=sql_data() mysql.insert_sku_data(good_id,prt_id,prt_href,a_title,prt_type,face_price,discount_price,stock,weight,unit,po_number) #销售属性 attr_num=0 for i in range (9,len(ths)): attr_num+=1 attr_name=ths[i].text attr_value=prt_tds[i].text #print(attr_name,attr_value) mysql=sql_data() mysql.insert_attributes(prt_id,attr_name,attr_value,attr_num) class get_prt_info(): def get_prt_data(self): db = pymysql.connect("localhost", "root", "<PASSWORD>", "zydmall_delixi", charset="utf8") cursor = db.cursor() sql = "select good_id,good_url,cnt from goods_lists_info where status=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def update_status(self,good_id,status): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "zydmall_delixi") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update goods_lists_info set status='%d' where good_id='%s'" \ % (status,good_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": for x in range(300): prt_info=get_prt_info() data=prt_info.get_prt_data() good_id=data[0][0] url=data[0][1] count=data[0][2] #url="http://www.zydmall.com/detail/good_3292.html" #good_id='3292' count=int(count.replace("种商品","")) print(good_id,url,count) browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) while 1 == 1: html = driver.page_source soup = BeautifulSoup(html, 'html.parser') cnt = soup.find('i', attrs={'id': 'goodsTotal'}).text cnt=int(cnt) print("共有%s条相关产品" % str(cnt)) print('waiting...') if cnt > (count - 1): print("共有%s条相关产品" % str(cnt)) break s(2, 3) ''' html=getHtml(url) print(html) ''' detail_data=prt_detail_data() #获取类目数据 detail_data.get_category(html,good_id) #get s(1,3) #获取基础属性,如订货号,折扣价,面价,系列等 detail_data.get_base_attrs(html,good_id)#get #获取销售属性,如壳架电流,分断能力等 detail_data.get_sale_attrs(html)#get #获取商品图片 num=detail_data.get_prt_imgs(html,good_id)#get #获取详情内容+里面的图片 detail_data.get_content(html,good_id,num) #get #获取spu_sku关系 detail_data.get_spu_link(html,good_id,count) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") s(1,2) status=1 prt_info.update_status(good_id, status) driver.quit() s(3,7) <file_sep>/untitled/test1.py url="http://trade.mmbao.com/p_2015062600001827.html" href="/p_201507300000000002492.html" url=url[0:url.index("/",7)] print(url+href)<file_sep>/ZYDMALL/zydmall_德力西/将两份文件夹中的图片区分为主图和详情图.py import os import urllib.request import pymysql import sys import shutil def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_id,img_name,img_type from prt_img_info " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName return totalPath if __name__=="__main__": data = get_prt_data() for i in range (3615): prt_id = data[i][0] img_name = data[i][1] img_type = data[i][2] print(prt_id, img_name, img_type) file_path = u"D:\BI\德力西商品导入—zyd\德力西----------------PART2\第二批图片\图片处理\zyd" file_path2 = u"D:\BI\德力西商品导入—zyd\德力西----------------PART2\第二批图片\图片处理\good_img" file_path3 = u"D:\BI\德力西商品导入—zyd\德力西----------------PART2\第二批图片\图片处理\img_desc" old = file_path +"\\"+prt_id+ "\\" + img_name print("old",old) try: if img_type=="prt_img": new = file_path2 + "\\" + prt_id + "\\" + img_name print(new) shutil.copyfile(old,new) else: new = file_path3 + "\\" + prt_id + "\\" + img_name print(new) shutil.copyfile(old,new) except FileNotFoundError as e: print(e) <file_sep>/untitled/Selenium/test2.py # coding:utf-8 from untitled.Selenium import webdriver driver = webdriver.Firefox() driver.get('http://www.tianyancha.com/') <file_sep>/TMALL/秋叶原/列表页数据获取.py #https://choreal.tmall.com/i/asynSearch.htm?_ksTS=1522040482187_125&callback=jsonp126&mid=w-15397480883-0&wid=15397480883&path=/search.htm&search=y&spm=a1z10.3-b-s.w4011-15397480883.130.5c8d3f29Ifd7LK&user_number_id=398685027&rn=de7c7a61dcb4ad481cf8a40ed0c449e2&keyword=ÇïÒ¶Ô­&pageNo=1&tsearch=y #https://choreal.tmall.com/i/asynSearch.htm?_ksTS=1522040530693_116&callback=jsonp117&mid=w-15397480883-0&wid=15397480883&path=/search.htm&search=y&spm=a1z10.3-b-s.w4011-15397480883.130.65393f29FWhLIY&user_number_id=398685027&rn=de7c7a61dcb4ad481cf8a40ed0c449e2&keyword=ÇïÒ¶Ô­&pageNo=2&tsearch=y #https://choreal.tmall.com/i/asynSearch.htm?_ksTS=1522040574553_125&callback=jsonp126&mid=w-15397480883-0&wid=15397480883&path=/search.htm&search=y&spm=a1z10.3-b-s.w4011-15397480883.131.41643f294L8gSe&user_number_id=398685027&rn=de7c7a61dcb4ad481cf8a40ed0c449e2&keyword=ÇïÒ¶Ô­&pageNo=3&tsearch=y import pymysql import requests import re from bs4 import BeautifulSoup from selenium import webdriver import time def get_content(url): s=requests.get(url) content=s.content.decode("gbk") print(content) return content def find_useful_data(html): soup=BeautifulSoup(html,'html.parser') items=soup.find_all('dl',attrs={'class':re.compile('item')}) print("当前页面一共%s条商品记录"%str(len(items))) for item in items: #获取data-id data_id=item.get('data-id') #dl标签里面的数据获取 item_detail=item.find('dd',attrs={'class':'detail'}) prt_title=item_detail.find('a').text prt_url=item_detail.find('a').get('href') #总销量,评价 prt_sales=item_detail.find('div',attrs={'class':'sale-area'}).text try: prt_rates=item_detail.find('dd',attrs={'class':'rates'}).find('span').text except AttributeError as e: prt_rates='0' print(data_id,'@@',prt_title,'@@',prt_url,'@@',prt_sales,'@@',prt_rates) if __name__=="__main__": url=["https://choreal.tmall.com/search.htm?spm=a1z10.3-b-s.w4011-15397480883.130.713c3f29TCwJpg&search=y&user_number_id=398685027&rn=de7c7a61dcb4ad481cf8a40ed0c449e2&keyword=%C7%EF%D2%B6%D4%AD&pageNo=1&tsearch=y#anchor", "https://choreal.tmall.com/search.htm?spm=a1z10.3-b-s.w4011-15397480883.130.4e5b3f29PPywrb&search=y&user_number_id=398685027&rn=de7c7a61dcb4ad481cf8a40ed0c449e2&keyword=%C7%EF%D2%B6%D4%AD&pageNo=2&tsearch=y#anchor", "https://choreal.tmall.com/search.htm?spm=a1z10.3-b-s.w4011-15397480883.131.113b3f29q0gogg&search=y&user_number_id=398685027&rn=de7c7a61dcb4ad481cf8a40ed0c449e2&keyword=%C7%EF%D2%B6%D4%AD&pageNo=3&tsearch=y#anchor"] #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() for i in range (len(url)): driver.get(url[i]) time.sleep(20) content=driver.page_source #print(content) #content=get_content(url) find_useful_data(content)<file_sep>/untitled/Requests/QSBK.py from urllib import request from bs4 import BeautifulSoup def getHtml(url): req=request.Request(url) req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0") response=request.urlopen(req) html=response.read().decode('utf-8') return html def get_data(html): soup=BeautifulSoup(html,'lxml') data_divs=soup.find_all("div",attrs={"class":"content"}) for data_div in data_divs: span_data=data_div.find("span") data=span_data.text data=data.replace("\n","") print(data) if __name__=="__main__": url="http://www.qiushibaike.com/hot/page/2" html=getHtml(url) print(html) get_data(html)<file_sep>/TAOBAO/远东电线-店铺数据/淘宝店铺-远东电线-1.0.py import time import random from selenium import webdriver from bs4 import BeautifulSoup import re import pymysql def s(a,b): x=random.randint(a,b) time.sleep(x) #1. 打开淘宝,远东电线 def insert_prt_data(prt_id,prt_title,prt_url,zhanggui_name,shop_url,location,market_price,sale_person): db = pymysql.connect("localhost", "root", "1<PASSWORD>6", "taobao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into cable_yuandong_prt_lists(prt_id,prt_title,prt_url,zhanggui_name,shop_url,location,market_price,sale_person) values('%s','%s','%s','%s','%s','%s','%s','%s')" %(prt_id,prt_title,prt_url,zhanggui_name,shop_url,location,market_price,sale_person) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_prt_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_data(html): soup=BeautifulSoup(html,'html.parser') #prt_title print("find_data...") prt_info = soup.find_all('div', attrs={'class': re.compile('J_MouserOnverReq')}) for i in range (len(prt_info)): prt_title_info = prt_info[i].find('a', attrs={'id': re.compile('J_Itemlist_TLink_')}) prt_title=prt_title_info.text.replace("\n","") prt_url=prt_title_info.get('href').replace("\n","") prt_id=prt_url[0:prt_url.rindex("&")] shop_info = prt_info[i].find('a', attrs={'class': 'shopname J_MouseEneterLeave J_ShopInfo'}) shop_url=shop_info.get('href') zhanggui_name=shop_info.text.replace("\n","") print(prt_id,prt_title,prt_url,zhanggui_name,shop_url) #付款人数、金额、地区 location=prt_info[i].find('div',attrs={'class':'location'}).text market_price=prt_info[i].find('div',attrs={'class':'price g_price g_price-highlight'}).text sale_person=prt_info[i].find('div',attrs={'class':'deal-cnt'}).text print(location,market_price,sale_person) insert_prt_data(prt_id,prt_title,prt_url,zhanggui_name,shop_url,location,market_price,sale_person) if __name__=="__main__": url="https://s.taobao.com/search?q=%E8%BF%9C%E4%B8%9C%E7%94%B5%E7%BA%BF&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20180209&ie=utf8" # 载入url,获取详情数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) s(3,5) for x in range (39): #获取页面上的相关数值 html=driver.page_source find_data(html) #换页 s(1,2) driver.find_elements_by_xpath("//ul[@class='items']/li[@class='item']")[2].click() s(5,8) <file_sep>/MMBAO/电工电气订单周报/查询电工电气周期内订单情况.py import cx_Oracle import pymysql import time import os import xlrd import xlwt def foreach(rootDir): files_excel = [] for root, dirs, files in os.walk(rootDir): for file in files: file_name = os.path.join(root, file) if 'xlsx' in file_name: files_excel.append(file_name) for dir in dirs: foreach(dir) return files_excel def find_exclusive_shop_lists(): excel_dir = ".\Dic" path = os.path.abspath(excel_dir) # print(path) files_excel = foreach(path) #print(files_excel) for file_name in files_excel: # excel_name=r"..\input\33-006(1).xlsx" excel_name = file_name.split('\\')[-1] #print(excel_name) data = xlrd.open_workbook(file_name) # 打开excel # print("当前excel共有%s个SHEET" % str(len(data.sheets()))) #第一个sheet,专卖店名单 sheetName = data.sheet_names()[0] #print("sheetName",sheetName) for i in range(1, int(data.sheets()[0].nrows)): row_info = data.sheets()[0].row_values(i) zmd_no.append(row_info[0]) zmd_name.append(row_info[1]) #print(row_info[0],row_info[1]) # 第二个sheet,营销经理名单 sheetName2 = data.sheet_names()[1] print("sheetName",sheetName2) for i in range(1, int(data.sheets()[1].nrows)): row_info = data.sheets()[1].row_values(i) jl_no.append(row_info[0]) jl_name.append(row_info[1]) #print(row_info[0], row_info[1]) # 第三个sheet,黑名单 sheetName3 = data.sheet_names()[2] print("sheetName",sheetName3) for i in range(1, int(data.sheets()[2].nrows)): row_info = data.sheets()[2].row_values(i) black_list.append(row_info[0]) #print(row_info[0]) def find_orders(): db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@192.168.3.11:7018/mmbao2b2c') cursor = db.cursor() sql=" SELECT "\ " O.ORDER_ID, "\ " O.ORDER_NUM 订单编号, "\ " O.member_id, LOGIN_NAME 买家名称, "\ " sell_name 卖家名称, "\ " TO_CHAR(O.create_date,'YYYY-MM-DD HH24:MI:SS') 提交时间, "\ " order_total 订单金额, "\ " DECODE(STATUS,1,'未付款',2,'已付款',3,'已发货',5,'申请取消',6,'交易成功',7,'交易关闭',8,'锁定状态',9,'已付款待确认-线下支付') 订单状态, "\ " TO_CHAR(PAY_DATE,'YYYY-MM-DD HH24:MI:SS') 付款时间, "\ " DECODE(BG_STATUS,0,'无类型',1,'跟进订单',2,'测试订单',3,'无效订单',4,'成功订单',5,'放弃订单',6,'退款订单',7,'内部刷单',8,'京东订单',9,'天猫订单',10,'其他第三方订单') 订单类型, "\ " O.product_num 商品数量, "\ " LOGISTICS_ID 物流单号, "\ " logistics_companay 物流公司, "\ " receive_addr 收货地址, "\ " receive_member 收货人, "\ " RECEIVE_PHONE 收货人手机号码, "\ " TO_CHAR(RECEIVE_DATE,'YYYY-MM-DD HH24:MI:SS') 买家收货日期, "\ " DECODE(ORDER_SOURCE,0,'pc端',1,'android',2,'ios',3,'h5') 订单来源, "\ " DECODE(PAY_PLATFORM,0,'pc',1,'手机端') 支付来源, "\ " DECODE(PAY_SOURCE,0,'支付宝',1,'财付通',2,'快钱',3,'线下支付',4,'微信') 支付方式, "\ " DECODE(ORDER_TYPE,0,'买卖宝订单',7,'电工电气') 业务类型 , "\ " BLONG_SERVICENAME 所属客服, "\ " decode(juderstatus,0,'默认状态',1,'待评论',2,'已评论') 评论状态 "\ " FROM mmbao2.T_XMALL_ORDER O "\ " WHERE LOGIN_NAME NOT LIKE '%测试%' "\ " AND O.BG_STATUS <> 2 "\ " AND O.CREATE_DATE BETWEEN TO_DATE('2018-04-01','YYYY-MM-DD') AND TO_DATE('2018-04-08','YYYY-MM-DD') "\ " AND ORDER_TYPE = 7 "\ " ORDER BY O.CREATE_DATE DESC,ORDER_ID DESC " # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def general_excel(data): wbk = xlwt.Workbook() sheet1=create_sheet(wbk,'周期内所有电工电气订单') save_all_data(sheet1,data) sheet2=create_sheet(wbk,'专卖店订单') save_zmd_data(sheet2,data) sheet3=create_sheet(wbk,'外部订单') save_out_data(sheet3,data) new_path = "./tmp.xls" wbk.save(new_path) def create_sheet(wbk,sheet_name): sheet1 = wbk.add_sheet(sheet_name) sheet1.write(0, 0, "ORDER_ID") sheet1.write(0, 1, "订单编号") sheet1.write(0, 2, "MEMBER_ID") sheet1.write(0, 3, "买家名称") sheet1.write(0, 4, "卖家名称") sheet1.write(0, 5, "提交时间") sheet1.write(0, 6, "订单金额") sheet1.write(0, 7, "订单状态") sheet1.write(0, 8, "付款时间") sheet1.write(0, 9, "订单类型") sheet1.write(0, 10, "商品数量") sheet1.write(0, 11, "物流单号") sheet1.write(0, 12, "物流公司") sheet1.write(0, 13, "收货地址") sheet1.write(0, 14, "收货人") sheet1.write(0, 15, "收货人手机号码") sheet1.write(0, 16, "买家收货日期") sheet1.write(0, 17, "订单来源") sheet1.write(0, 18, "支付来源") sheet1.write(0, 19, "支付方式") sheet1.write(0, 20, "业务类型") sheet1.write(0, 21, "所属客服") sheet1.write(0, 22, "评论状态") return sheet1 def save_zmd_data(sheet_name,data): num=0 for i in range (len(data)): buyer_name=data[i][3] for x in range (len(zmd_name)): if buyer_name==zmd_name[x]: num+=1 for j in range (22): sheet_name.write(num, j, data[i][j]) for y in range(len(zmd_name)): if buyer_name == jl_no[y]: num += 1 for j in range(22): sheet_name.write(num, j, data[i][j]) def save_out_data(sheet_name,data): num=0 out_data=[] for i in range (len(data)): buyer_name=data[i][3] for x in range (len(zmd_name)): if buyer_name==zmd_name[x]: out_data.append(buyer_name) else: for y in range (len(jl_no)): if buyer_name == jl_no[y]: out_data.append(buyer_name) print(out_data) for a in range(len(data)): print(data[a]) state=0 for b in range (len(out_data)): if out_data[b]==data[a][3]: state+=1 #print(out_data[b], data[a][3]) else: pass if state==0: num += 1 print(data[a][3]) for j in range(22): sheet_name.write(num, j, data[a][j]) def save_all_data(sheet_name,data): for i in range (len(data)): for j in range (22): sheet_name.write(i + 1, j, data[i][j]) if __name__=="__main__": title = "./logs.txt" current_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) with open(title, "w") as f: f.write(current_date) f.write('\n') zmd_no = [] zmd_name = [] jl_no = [] jl_name = [] black_list = [] #将专卖店名单、营销经理名单、黑名单都存放到list中 find_exclusive_shop_lists() #5个list已经赋值 #进行数据库查询 data=find_orders() #print(data) #将data中的数据存放到excel中 #把总的数据,保存到总表中 general_excel(data) <file_sep>/untitled/抓取斗图3.0.py import urllib.request from bs4 import BeautifulSoup from selenium import webdriver import time import re import uuid import os #生成一个文件名字符串 def generateFileName(): return str(uuid.uuid1()) #根据文件名创建文件 def createFileWithFileName(localPathParam,fileName): totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath def getAndSaveImg(imgUrl,img_name): if (len(imgUrl) != 0): file_extension_name=imgUrl[imgUrl.rindex("."):100] fileName = img_name + file_extension_name print(fileName) fileName = re.sub('[\/:*?"<>|]', '-', fileName) try: urllib.request.urlretrieve(imgUrl, createFileWithFileName("C:\\做头发", fileName)) except: print("这图我没法下载") def getHtml(url): #print("正在打开网页并获取....") try: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0', } data=None req=urllib.request.Request(url,data,headers) response = urllib.request.urlopen(req) html = response.read().decode('utf-8') Html = str(html) print("成功获取....") #print(Html) except: Html="" return Html def find_img(html): soup=BeautifulSoup(html,'html.parser') img_data=soup.find_all('a',attrs={'class':'col-xs-6 col-md-2'}) for i in range (len(img_data)): img_url=img_data[i].find('img',attrs={'class':'img-responsive lazy image_dtb'}).get('data-original') img_name=img_data[i].find('p').text img_name=img_name+str(i) print(img_url) getAndSaveImg(img_url, img_name) if __name__=="__main__": #driver=webdriver.PhantomJS() for i in range(50): page_num=i+1 url="http://www.doutula.com/search?keyword=%E5%81%9A%E5%A4%B4%E5%8F%91&page="+str(page_num) html=getHtml(url) #driver.get(url) #time.sleep(3) #html=driver.page_source find_img(html) <file_sep>/工品汇/正泰/工品汇2.0-main.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver from selenium.common.exceptions import NoSuchElementException def company_info(): company_name="德力西" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-name.u-b.J_name').send_keys(uid) driver.find_element_by_css_selector('.login-pwd.p-b.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.main-background-color.login-but.cursor.J_button').click() s(3, 5) def s(a,b): t=random.randint(a,b) time.sleep(t) def insert_data1(table_id,prt_id,prt_url): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into vipmro_com_data (cate_id,prt_id,prt_url)"\ "values('%s','%s','%s')"\ %(table_id,prt_id,prt_url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_url_status(): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select table_id,cate_1_name,cate_1_url from vipmro_com_url where status=0 and company_name='正泰' order by table_id" try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_status_to_run_log(table_id): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_com_url set status=1 where table_id='%s' " \ % (table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def get_current_page(table_id): #获取当前页面上的商品信息 page_num = 1 while 1 == 1: divs=driver.find_elements_by_xpath("//div[@class='list-main-box-cont']/span[@class='price_color m-top5']/a") print("当前页面共%s条商品数据"%str(len(divs))) for i in range(len(divs)): prt_url=divs[i].get_attribute('href') prt_id=prt_url[prt_url.rindex('/')+1:100] print(prt_id, prt_url) insert_data1(table_id,prt_id,prt_url) page_num+=1 try: driver.find_element_by_xpath("//div[@class='list-page J_page']/a[@page-id="+str(page_num)+"]").click() s(4,6) except NoSuchElementException as e: print(e) break def find_series(): divs=driver.find_elements_by_class_name('list-nav-li') print(str(len(divs))) series_names=[] series_urls=[] series_info = driver.find_elements_by_xpath("//div[@class='list-nav-li'][2]/ul/li/a") for i in range(len(series_info)): series_name=series_info[i].text series_url=series_info[i].get_attribute('href') #print(series_name,series_url) series_names.append(series_name) series_urls.append(series_url) return series_names,series_urls if __name__=="__main__": url="http://www.vipmro.com/login" browser="Firefox" if browser=="Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser=="Firefox": driver=webdriver.Firefox() else: driver=webdriver.PhantomJS() driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' #login_url(uid,pwd) print("------finish the login step---------") #完成登录 #点击一下搜索按钮,使页面正确加载url data = get_url_status() for i in range (len(data)): table_id=data[i][0] cate_1_name=data[i][1] cate_1_url =data[i][2] print(table_id,cate_1_name,cate_1_url) #cate_1_url='http://www.vipmro.com/search/?ram=0.5041790683059719&keyword=%25E6%25AD%25A3%25E6%25B3%25B0&categoryId=50111011&brandId=105' driver.get(cate_1_url) #判断当前类目一共有多少数据,等于100则需要细化 total_cnt_text=driver.find_element_by_xpath("//div[@class='list-main-total J_t_html']/span").text total_cnt=total_cnt_text.replace("共","").replace("件相关商品","") print(total_cnt) if int(total_cnt)==100: #如果是100,则需要调用函数,便利下系列这一层 series_names, series_urls=find_series() for x in range(len(series_names)): driver.get(series_urls[x]) s(3,5) get_current_page(table_id) else: get_current_page(table_id) update_status_to_run_log(table_id) s(5,10) <file_sep>/工品汇/正泰.NET/获取图片-v1.py #因为数据量并不多,所以直接遍历判断是新增还是复制吧 #抄当时vipmro里面的获取图片的函数 #尽量将一些经常使用的函数打包成库的方法使用,省的老是复制粘贴 import os import urllib.request import pymysql import sys import shutil import time #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg2(product_id,img_url, img_name,img_path): if (len(img_url) != 0): fileName = img_name file_path=u"D:\\BI\\VIPMRO"+img_path print(file_path) try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) status=1 except: print("这图我没法下载") status=2 return status # 保存图片 def getAndSaveImg(product_id, img_url, img_name, img_path): if (len(img_url) != 0): fileName = img_name file_path = u"D:/BI/VIPMRO"+img_path print(file_path) createFileWithFileName(file_path, fileName) response = urllib.request.urlopen(url) img=response.read() with open(file_path+fileName, 'wb') as f: f.write(img) print("success") status = 1 return status #复制图片 def copy_Img(prt_id_exist,prt_id,img_name): #暂时不加异常捕捉机制,试运行 src="D:\\BI\\VIPMRO\\upload\\prt\\zyd\\"+prt_id_exist+"\\"+img_name dst="D:\\BI\\VIPMRO\\upload\\prt\\zyd\\"+prt_id+"\\"+img_name print("waiting for "+src+" =>=>=>=>=>=> "+dst) file_path = u"D:\\BI\\ZYD_DELIXI\\upload\\prt\\zyd\\" + prt_id createFileWithFileName(file_path, img_name) shutil.copyfile(src,dst) print("复制成功") def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "vipmro_chint") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,table_id,original_url,img_type from vipmro_net_img_info where download_status=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def is_existed(table_id,img_name,url): db = pymysql.connect("localhost", "root", "123456", "vipmro_chint") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,original_url from vipmro_net_img_info where download_status=1 and img_name='%s' and original_url='%s' limit 1" %(img_name,url) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_state(prt_id,url,status,is_repeat): db = pymysql.connect("localhost", "root", "123456", "vipmro_chint") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update vipmro_net_img_info set download_status='%d',is_repeat='%d' where prt_id='%s' and original_url='%s'" %(status,is_repeat,prt_id,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #从数据表获取prt_id,img_url,img_name for i in range(810): data = get_prt_data() prt_id=data[0][0] table_id=data[0][2] url=data[0][3] img_name=url[url.rindex("/")+1:1000] img_path=url.replace(img_name,"").replace("https://image.vipmro.net","") print(table_id,prt_id,img_name,url,img_path) #判断是否已经存在相同的图片,进行复制,而不是重新下载 print("不存在相同的耶") status = getAndSaveImg(prt_id, url, img_name,img_path) if status == 1: is_repeat = 0 update_state(prt_id, url, status, is_repeat) else: is_repeat = 0 update_state(prt_id, url, status, is_repeat) # time.sleep(1000) # 返回path路径,更新到数据表字段 <file_sep>/JD后台/VC后台/检查各商品是否包含地图那张图.py import pymysql import time from selenium import webdriver def get_prt_code(): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 商品编号,商品状态 from prt_info where status=0" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_data(prt_code,pt): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") if pt=="pc": sql = "update prt_info set pc='1' where 商品编号='%s' " %prt_code else: sql = "update prt_info set mobile='1' where 商品编号='%s' " % prt_code print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() data=get_prt_code() pc_img_info="//img10.360buyimg.com/imgzone/jfs/t4666/154/4572725365/182310/90510460/590fcc0bNd65edb82.jpg" m_img_info="//img11.360buyimg.com/imgzone/jfs/t4627/362/4630065428/186557/1c0c0238/59111c67Nf4322e9e.jpg" m_img_info2="//img10.360buyimg.com/imgzone/jfs/t7690/142/2025175497/186557/1c0c0238/59a69effN30378da0.jpg" for i in range (len(data)): prt_code=data[i][0] pc_url="https://item.jd.com/%s.html"%prt_code m_url="https://item.m.jd.com/product/%s.html"%prt_code print(pc_url,m_url) driver.get(pc_url) time.sleep(3) pc_page_content=driver.page_source if pc_img_info in pc_page_content: insert_data(prt_code,"pc") driver.get(m_url) time.sleep(3) m_page_content = driver.page_source if m_img_info in m_page_content: insert_data(prt_code, "mobile") if m_img_info2 in m_page_content: insert_data(prt_code, "mobile") <file_sep>/JD后台/VC后台/调整商品名称以及类型属性-2018年8月1日.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) data=self.get_lists() for i in range (len(data)): sku_id = data[i][0] sku_name = data[i][1] sku_type = data[i][2] print(sku_id, sku_name, sku_type) driver.find_element_by_id('wareId').clear() driver.find_element_by_id('wareId').send_keys(sku_id) self.s(1,2) driver.find_element_by_css_selector('.btn.btn-primary').click() self.s(2,3) nowhandle = driver.current_window_handle # 在这里得到当前窗口句柄 btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_wareId']/div/button[@class='btn btn-default']" driver.find_element_by_xpath(btn_down_path).click() self.s(5, 6) # 需要获取新弹开的窗口 allhandles = driver.window_handles # 获取所有窗口句柄 for handle in allhandles: # 在所有窗口中查找弹出窗口 if handle != nowhandle: driver.close() driver.switch_to.window(handle) current_url = driver.current_url print(current_url) if "https://vcp.jd.com/sub_item/item/initItemListPage" in current_url: self.update_caigou_price(sku_id,'reviewing') else: driver.get(current_url) content = driver.page_source # print(content) self.s(3, 4) driver.find_element_by_id('cid3Submit').click() self.s(2, 4) driver.find_element_by_id('custmerName').clear() driver.find_element_by_id('custmerName').send_keys(sku_name) self.s(1, 2) driver.find_element_by_id('auditedSubmit').click() self.s(1, 2) xinghao2 = sku_type driver.find_elements_by_class_name("combo-arrow")[4].click() if xinghao2 == "BV": xinghao2_xpath = "//div[@value='632979' ]" driver.find_element_by_xpath(xinghao2_xpath).click() elif xinghao2 == "BVR": xinghao2_xpath = "//div[@value='632984' ]" driver.find_element_by_xpath(xinghao2_xpath).click() elif xinghao2 == "YJV": xinghao2_xpath = "//div[@value='698971' ]" driver.find_element_by_xpath(xinghao2_xpath).click() elif xinghao2 == "YJY": xinghao2_xpath = "//div[@value='632988' ]" driver.find_element_by_xpath(xinghao2_xpath).click() driver.find_element_by_id('createApply').click() self.s(1, 2) self.update_status(sku_id,1) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) def get_lists(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select sku_id,sku_name,sku_type from changed_name where status=0" #print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(self,sku_id,status): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update changed_name set status='%d' where sku_id='%s' " %(status,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url) <file_sep>/找电缆EXCEL处理2.0新版/对新增的数据生成excel.py #将新增的数据,从zhaodianlan_data的状态为2的数据,转换成excel import pymysql import xlwt def get_excel_name_from_zhaodianlan_data(): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select excel_name from zhaodianlan_data where status=2 group by excel_name" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_data_from_zhaodianlan_data(excel_name): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,excel_name,sheet_name,type_specification,lev_zr,price from zhaodianlan_data where status=2 and excel_name='%s'" %excel_name try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_data_from_zhaodianlan_type_detail(table_id): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select 结构,材质,芯数,国标,型号,电压,规格,类别,阻燃,价格 from zhaodianlan_type_detail where table_id='%s' " %table_id try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_type_detail-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #从数据表中获取所有的恶excel_name data_excel_name=get_excel_name_from_zhaodianlan_data() for m in range (len(data_excel_name)): excel_name=data_excel_name[m][0] print(excel_name) data=get_data_from_zhaodianlan_data(excel_name) wbk = xlwt.Workbook() sheet1 = wbk.add_sheet('sheet 1') sheet1.write(0, 0, "类目") sheet1.write(0, 1, "型号") sheet1.write(0, 2, "规格") sheet1.write(0, 3, "电压") sheet1.write(0, 4, "厂商") sheet1.write(0, 5, "品牌") sheet1.write(0, 6, "省") sheet1.write(0, 7, "市") sheet1.write(0, 8, "价格(元/单位)") sheet1.write(0, 9, "商品有效期") sheet1.write(0, 10, "是否上架") sheet1.write(0, 11, "交货期(天)") sheet1.write(0, 12, "权重值") sheet1.write(0, 13, "参与均价计算") sheet1.write(0, 14, "属性") sheet1.write(0, 15, "库存") sheet1.write(0, 16, "生产年份") new_path = "D:\BI\找电缆\已处理\\" + excel_name.replace("xlsx", "xls") wbk.save(new_path) x_num = 1 for i in range (len(data)): table_id=data[i][0] #excel_name = data[i][1] #sheet_name = data[i][2] price = data[i][5] #拿着table_Id去型号明细查询 data2 = get_data_from_zhaodianlan_type_detail(table_id) #print(data2) jiegou=data2[0][0] caizhi=data2[0][1] xinshu=data2[0][2] guobiao=data2[0][3] type=data2[0][4] dianya = data2[0][5] guige = data2[0][6] leibie = data2[0][7] #leibie暂时不加载 leibie="" zuran = data2[0][8] cate_name="电力电缆" if zuran=="PT": type_name=type else: type_name=zuran+"_"+type if guige.endswith("*1.0"): guige=guige.replace("*1.0","*1") print(guige) factory="远东电缆" brand_name="远东" providence="江苏省" city="无锡市" useful_date="300.0" is_sale="是" day="15.0" average_calc="150.0" attribute="是" stock="定制" productive_year="" sheet1.write(i+1, 0, cate_name) sheet1.write(i+1, 1, type_name) sheet1.write(i+1, 2, guige) sheet1.write(i+1, 3, dianya) sheet1.write(i+1, 4, factory) sheet1.write(i+1, 5, brand_name) sheet1.write(i+1, 6, providence) sheet1.write(i+1, 7, city) sheet1.write(i+1, 8, price) sheet1.write(i+1, 9, useful_date) sheet1.write(i+1, 10, is_sale) sheet1.write(i+1, 11, day) sheet1.write(i+1, 12, average_calc) sheet1.write(i+1, 13, attribute) sheet1.write(i+1, 14, stock) sheet1.write(i+1, 15, productive_year) new_path = "D:\BI\找电缆\待新增\\" + excel_name.replace("xlsx", "xls") wbk.save(new_path)<file_sep>/untitled/Selenium/dq123/dq123商品信息2.0-Y.py #实现功能 #1. 列表数据搜集,翻页,导入excel,MAX页码获取,数组合并 import random import re import time import pyautogui import bs4 import xlrd import pymysql from selenium import webdriver #需要修改save_excel模块的存储结构 def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) def add_columns(): driver.find_element_by_css_selector('.fl.add-good.J_continueAdd').click() time.sleep(0.5) def insert_data(prt_name): #name1=str(prt_name[0]).replace("],","").replace("']","").replace("['","") #print(name1) #driver.find_element_by_css_selector(".no-text.center.J_goodsNo").send_keys(name1) #time.sleep(0.5) for i in range (len(prt_name)-1): name=str(prt_name[i]).replace("],","").replace("']","").replace("['","") print(name) pyautogui.press('enter') driver.find_elements_by_css_selector(".no-text.center.J_goodsNo")[i].send_keys(name) time.sleep(3) def get_data(): time.sleep(4) prt_name1=driver.get_elements_by_xpath("//li[@class='d']/span[@class='a']") prt_name2=driver.get_elements_by_xpath("//li[@class='d']/span[@class='b']") kucun=driver.get_elements_by_xpath("//li[@class='e center line-52']") price=driver.get_elements_by_xpath("//div[@class='price-active fl bline-52']/span[@class='price']") market_price=driver.get_elements_by_xpath("//li[@class='g center line-52']") for i in range(len(prt_name1)): insert_data1(prt_name1[i], prt_name2[i], kucun[i], price[i], market_price[i]) def insert_data1(prt_name1,prt_name2,kucun,price,market_price): db = pymysql.connect("localhost", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into gongpinhui_quickorder (prt_name1,prt_name2,kucun,price,market_price)"\ "values('%s','%s','%s','%s','%s')"\ %(prt_name1,prt_name2,kucun,price,market_price) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def print_xls(): data=xlrd.open_workbook(r"D:\BI\data4selenium.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 PRT_NAME=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss PRT_NAME.append(ss) return PRT_NAME #正泰 http://www.vipmro.net/search?brandId=105 if __name__ == '__main__': prt_name = [] #数组存放 prt_name=print_xls() #print(prt_name) driver = webdriver.Firefox() driver.get("http://www.vipmro.net/quickorder") time.sleep(3) uid='18861779873' pwd='<PASSWORD>' driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) cnt=len(prt_name) #行数 for_times=int((cnt-5)/5+1) for i in range(for_times): add_columns() insert_data(prt_name) <file_sep>/待自动化运行脚本/tmall上显卡价格/表内显卡数据筛选.py import pymysql def get_gtx_dictionary(): db = pymysql.connect("localhost", "root", "123456", "tmall_price_changes") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select gtx_type,gtx_memory from gtx_dictionary " #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def check_data(gtx_type,gtx_memory): solution="%"+gtx_type+"%"+gtx_memory+"%" db = pymysql.connect("localhost", "root", "123456", "tmall_price_changes") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select raw_title,view_price from GTX where raw_title like '%s' " %solution #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #按照型号整理 gtx_dictionary=get_gtx_dictionary() for y in range(len(gtx_dictionary)): gtx_type=gtx_dictionary[y][0] gtx_memory = gtx_dictionary[y][1] #print(gtx_type,gtx_memory) gtx_info=check_data(gtx_type,gtx_memory) price_list = [] for m in range (len(gtx_info)): prt_title=gtx_info[m][0] prt_price=gtx_info[m][1] #print(prt_title,prt_price) price_list.append(prt_price) #print(price_list,str(len(price_list))) #对prt_list中的数据进行求平均值 sum=0 for a in price_list: sum=sum+a if len(price_list)==0: pass else: print(gtx_type,gtx_memory,str(round(sum/len(price_list),2))) <file_sep>/MMBAO/企查查数据筛选/分管数据拆分多个excel.py import os import pymysql import xlwt def find_company_info(pianqu_leader,pianqu_name): db = pymysql.connect("localhost", "root", "123456", "tianyancha") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select * from company_main_info where 分管领导='%s' and 片区名称='%s' " %(pianqu_leader,pianqu_name) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def find_pianqu(): db = pymysql.connect("localhost", "root", "123456", "tianyancha") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 片区领导,片区名称 from leader_province group by 片区领导,片区名称" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def create_sheet(wbk,sheet_name): sheet1 = wbk.add_sheet(sheet_name) #样式 col1 = sheet1.col(0) # 获取第0列 col1.width = 100 * 22 # 设置第0列的宽为380,高为20 col2 = sheet1.col(1) # 获取第0列 col2.width = 100 * 22 # 设置第0列的宽为380,高为20 col3 = sheet1.col(2) # 获取第0列 col3.width = 100 * 22 # 设置第0列的宽为380,高为20 col4 = sheet1.col(3) # 获取第0列 col4.width = 100 * 22 # 设置第0列的宽为380,高为20 col5 = sheet1.col(4) # 获取第0列 col5.width = 100 * 22 # 设置第0列的宽为380,高为20 col6 = sheet1.col(5) # 获取第0列 col6.width = 100 * 22 # 设置第0列的宽为380,高为20 col7 = sheet1.col(6) # 获取第0列 col7.width = 260 * 22 # 设置第0列的宽为380,高为20 col8 = sheet1.col(7) # 获取第0列 col8.width = 190 * 22 # 设置第0列的宽为380,高为20 col9 = sheet1.col(8) # 获取第0列 col9.width = 160 * 22 # 设置第0列的宽为380,高为20 col10 = sheet1.col(9) # 获取第0列 col10.width = 160 * 22 # 设置第0列的宽为380,高为20 col11 = sheet1.col(10) # 获取第0列 col11.width = 117 * 22 # 设置第0列的宽为380,高为20 col12 = sheet1.col(11) # 获取第0列 col12.width = 179 * 22 # 设置第0列的宽为380,高为20 col13 = sheet1.col(12) # 获取第0列 col13.width = 154 * 22 # 设置第0列的宽为380,高为20 col14 = sheet1.col(13) # 获取第0列 col14.width = 122 * 22 # 设置第0列的宽为380,高为20 style = xlwt.XFStyle() # 创建样式 borders = xlwt.Borders() borders.left = 1 borders.right = 1 borders.top = 1 borders.bottom = 1 borders.bottom_colour = 0x3A style = xlwt.XFStyle() style.borders = borders style.font.bold=True style2 = xlwt.XFStyle() style2.borders = borders sheet1.write(0, 0, "序号",style) sheet1.write(0, 1, "分管领导",style) sheet1.write(0, 2, "片区名称",style) sheet1.write(0, 3, "类型",style) sheet1.write(0, 4, "省",style) sheet1.write(0, 5, "市",style) sheet1.write(0, 6, "企业名称",style) sheet1.write(0, 7, "统一社会信用代码",style) sheet1.write(0, 8, "法定代表人",style) sheet1.write(0, 9, "成立日期",style) sheet1.write(0, 10, "注册资本",style) sheet1.write(0, 11, "地址",style) sheet1.write(0, 12, "邮箱",style) sheet1.write(0, 13, "电话号码",style) sheet1.write(0, 14, "经营范围",style) return sheet1,style2 def general_excel(data,excel_name): wbk = xlwt.Workbook() sheet1,style2=create_sheet(wbk,'公司信息') save_all_data(sheet1,data,style2) #new_path需要修正 new_path = excel_name wbk.save(new_path) def save_all_data(sheet_name,data,style2): for i in range (len(data)): for j in range (15): if j==0: sheet_name.write(i + 1, j, i+1,style2) else: sheet_name.write(i + 1, j, data[i][j],style2) #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath if __name__=="__main__": pianqu_data=find_pianqu() for a in range (len(pianqu_data)): pianqu_leader=pianqu_data[a][0] pianqu_name=pianqu_data[a][1] dic_path= "./"+pianqu_leader+"/"+pianqu_name+"片区" excel_name= "./"+pianqu_leader+"/"+pianqu_name+"片区/"+str(pianqu_name)+"片区公司信息.xls" createFileWithFileName(dic_path, excel_name) print("片区领导",pianqu_leader,"片区名称",pianqu_name,dic_path) company_data=find_company_info(pianqu_leader,pianqu_name) for i in range (len(company_data)): xuhao=company_data[i][0] fenguan_leader=company_data[i][1] pianqu_name=company_data[i][2] type=company_data[i][3] province=company_data[i][4] city=company_data[i][5] company_name=company_data[i][6] code=company_data[i][7] fading_leader=company_data[i][8] birth_date=company_data[i][9] money=company_data[i][10] address=company_data[i][11] email=company_data[i][12] phone=company_data[i][13] content=company_data[i][14] #判断 general_excel(company_data,excel_name) <file_sep>/untitled/Selenium/dq123/dq123商品信息2.0.py #1.0 版本,完成基本的数据获取/导入MYSQL操作 #1.1版本,需要加入翻页功能,设定20页数据即可(用于多主机分布获取) #2.0版本, # a. #try: #except TimeoutException: # return search() # b. 模块化,减少代码冗余, # c. # d. # e. # f. import datetime import pymysql import time import re from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait def insert_mysql(id,prt_name,price,company,cate1,cate2): db = pymysql.connect("localhost", "root", "<PASSWORD>", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_info" \ " (PRT_ID,PRT_NAME,PRICE,COMPANY_NAME,CAT1,CAT2)" \ " values('%s','%s','%s','%s','%s','%s')" \ % (id,prt_name,price,company,cate1,cate2) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def click_cate(num,category1,category2): list = driver.find_element_by_id("classlibiao") if num==0:#如果是第一次执行,那么需要打开cate1 list.find_element_by_link_text(category1).click() print("一级类目:" + category1) time.sleep(5) if category2=="NULL": time.sleep(5) print("无二级类目") else: list.find_element_by_link_text(category2).click() print("二级类目:" + category2) time.sleep(5) def page_num(orginal_page): if orginal_page>10: num = int((orginal_page - 10) / 4 + 1) print("循环" + str(num) + "次") for page in range(num): m = 10 + 4 * page driver.find_element_by_xpath("//div[@id='pagesdiv']/a[@p='" + str(m) + "']").click() time.sleep(15) try: driver.find_element_by_xpath("//div[@id='pagesdiv']/a[@p='" + str(orginal_page) + "']").click() except: print("当前可能就是" + str(orginal_page)) time.sleep(5) def table_info(catgory2): list_1 = driver.find_element_by_xpath("//table[@class='yjtbs']/tbody[@id='part_list']") tr = list_1.find_elements_by_tag_name("tr") detail=[] tr_num=len(tr) i=1 while 1==1: print("当前页共"+str(tr_num)+"条数据") if tr_num == 0: time.sleep(5) else: break i=i+1 if i==100: break for i in range(len(tr)): #time.sleep(4) colunm = tr[i].find_elements_by_tag_name("td") # print(len(colunm)) # 获取序号、商品名、价格、制造商 td1 = colunm[0].text td2 = colunm[1].text td3 = colunm[2].text td4 = colunm[3].text print(td1 + "//" + td2 + "//" + td3 + "//" + td4) # insert_mysql(td1, td2, td3, td4, category1, catgory2) # print("此条记录已导入") return tr_num # 跳转到下一页 if __name__=="__main__": #定义函数 #当前页面的数据条数 category1="高压成套设备" category2 = [ "聚优柜" ] orginal_page=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ##这里使用PhantomJS,并配置了一些参数 driver = webdriver.Firefox() ##窗口的大小,不设置的话,默认太小,会有问题 #driver.set_window_size(1400, 900) #载入url,点击列表选型 driver.get("http://www.dq123.com/price/index.php") #wait = WebDriverWait(driver, 10) time.sleep(8) driver.find_element_by_id("showhidediv1").click() for i in range(len(category2)): time.sleep(5) # 1. 选择对应的产品目录 #点击到二级类目下的列表 catgory2=category2[i] page=orginal_page[i] click_cate(i,category1,catgory2) time.sleep(5) #1. 获取整个产品目录,然后进行遍历,一个脚本循环20次,防止异常 #先调整起始页数 page_num(page) for a in range(1000): tr_num=table_info(catgory2) time.sleep(10) if tr_num==50: print("翻页,当前" + str(a + 1 + page) + "页") driver.find_element_by_xpath("//div[@id='pagesdiv']/a[@title='下一页']").click() time.sleep(20) else: print("此项类目结束") break <file_sep>/地址拆分/地址拆分-2018年1月4日.py import pymysql def get_providence(): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select pname from tmp2 group by pname" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_city(): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select cname from tmp2 group by cname" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_district(): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select dname from tmp2 group by dname" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_data_from_address(type,pname): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,address from address_data_jd where company_name like '%"+pname+"%' and "+type+" is null" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_providence(pname): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update address_data_jd set providence='"+pname+"' where company_name like '%"+pname+"%'" try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_city(cname): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update address_data_jd set city='"+cname+"' where company_name like '%"+cname+"%'" try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_district(dname): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update address_data_jd set district='"+dname+"' where company_name like '%"+dname+"%' " try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #将address保存到数据表,使用省进行轰炸,把结果更新到数据表,然后再用市轰炸 #取出所有的省份 data_pname=get_providence() for i in range (len(data_pname)): original_pname=data_pname[i][0] pname=original_pname.replace("省","").replace("市","").replace("自治区","").replace("回族","").replace("壮族","").replace("维吾尔","") print(pname) update_providence(pname) data_cname=get_city() for i in range (len(data_cname)): original_cname=data_cname[i][0] cname=original_cname.replace("省","").replace("市","") print(cname) update_city(cname) data_dname=get_district() for i in range (len(data_dname)): original_dname=data_dname[i][0] if original_dname is None: continue else: dname=original_dname.replace("新区","").replace("市","") print(dname) update_district(dname) <file_sep>/untitled/Selenium/天气预报.py import requests import json #定义一个函数 避免代码重写多次。 def gettemp(week,d_or_n,date): wendu=data['result']['weather'][week]['info'][d_or_n][date] #对字典进行拆分 return int(wendu) def getft(t): ft=t*1.8+32 return float(str(ft)[0:4]) cities=['宜兴','无锡'] #这里可以指定想要遍历的城市 url='http://api.avatardata.cn/Weather/Query?key=<KEY>&cityname=' #用于和cities里的城市进行字符串拼接 low=0 high=2 for city in cities: r = requests.get(url+city) # 最基本的GET请求 #print(r.status_code) 获取返回状态200是成功 #print(r.text) 打印解码后的返回数据 data=json.loads(r.text) #返回的json数据被转换为字典类型 #print(type(data)) data 的数据类型是字典 所以可以按照字典操作(字典里的列表就按列表操作) print(city,'近五天天气预报:') for i in range(5): week='周'+str(data['result']['weather'][i]['week']) #对字典类型进行逐个拆分 如列表 元组等。 daylow=gettemp(i,'day',low) dlf=getft(daylow) dayhigh=gettemp(i,'day',high) dhf=getft(dayhigh) nightlow=gettemp(i,'night',low) nlf=getft(nightlow) nighthigh=gettemp(i,'night',high) nhf=getft(nighthigh) print(week,'白天气温:',daylow,'~',dayhigh,'摄氏度','晚上气温:',nightlow,'~',nighthigh,'摄氏度') print(' ','白天气温:',dlf,'~',dhf,'华氏度','晚上气温:',nlf,'~',nhf,'华氏度') print('\n')<file_sep>/untitled/代理/抓取快代理IP-1.0.py import urllib.request from bs4 import BeautifulSoup import pymysql def get_ip(html): # print(html) soup = BeautifulSoup(html,'lxml') ip=soup.findAll('td',{'data-title':'IP'}) port = soup.findAll('td', {'data-title': 'PORT'}) for i in range(len(ip)): ip_address=ip[i].text+":"+port[i].text print(ip_address) save_data(ip_address) def clear_data(): db = pymysql.connect("localhost", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="delete from proxy_info" # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() db.close() def save_data(ip_address): db = pymysql.connect("localhost", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into proxy_info" \ " (ip_address)" \ " values('%s')" \ % (ip_address) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def main(): url="http://www.kuaidaili.com/free/" head={} head['User-Agent']='Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0' req=urllib.request.Request(url,None,head) response=urllib.request.urlopen(req) html=response.read().decode('utf-8') print(html) clear_data() get_ip(html) if __name__=="__main__": main()<file_sep>/加密服务/login.js /** * Created by Administrator on 2017/07/11. */ /* * login * 2016-3-16 * sunxiaowen * */ (function($,pubFuc){ var url=pubFuc.url(), urls=pubFuc.urls(); var api={ "loginApi":url+"/user/saaspcLogin", "loginOut":url+"/user/saasLoginOut/", "loginKey":url+"/user/loginRequest" }; var dom={ "J_userName":".J_userName", "J_psw":".J_psw", "J_loginIn":".J_loginIn", "J_error":".J_error", "J_vcode":".J_vcode", "J_codeHtml":".J_codeHtml", "J_login":".J_login", "J_img":".J_img", "J_a":".J_a", "J_layout":".J_layout", "J_isLogin":".J_isLogin" }; var login=(function(){ return{ init:function(){ this.loginInDo(); }, loginInDo:function(){ var _this_=this; $(dom.J_loginIn).on("click",function(){ _this_.loginIn(); //_this_.dcFunction(); }); $(dom.J_loginIn).removeAttr("disabled"); }, loginIn:function(){ var _this_=this, userName=$(dom.J_userName).val(), psw=$(dom.J_psw).val(), vCode=$(dom.J_vcode).val(), key1, key2, data={}; $(dom.J_loginIn).prop("disabled","disabled").val("登录中。。。").addClass("a"); pubFuc.load(api.loginKey,null,"POST",function(s){ if(s.code==0){ key1=s.data.mm; key2=s.data.ee; setMaxDigits(130); var tt= new RSAKeyPair(key2,"",key1); userName=encryptedString(tt,userName); psw=encryptedString(tt,psw); data.loginName=userName; data.password=psw; pubFuc.load(api.loginApi,data,"POST",function(s){ if(s.code==0){ ///*供1 零2*/ if(s.data.dealerType==1){ location.href=urls+"/seller/orderList"; }else{ pubFuc.cookie({ "cookieName":"cartNum", "cookieValue":s.data.cartNum, }); var pUrl=location.href.split("backURL=")[1]; if(pUrl){ location.href=urls+pUrl; }else{ location.href=urls; } } }else{ pubFuc.openWindow(s.msg,320,120); $(dom.J_codeHtml).remove(); var tHtml= '<li class="J_codeHtml">'+ '<input type="text" class="login-code m-top5 J_vcode">'+ '<img src="'+urls+'/page/loginCaptcha.jsp" class="login-code-img m-left10 m-top5 cursor J_img">'+ '<a href="javascript:;" class="login-code-a m-left10 m-top5 p-top5 J_a">看不清楚</a>'+ '</li>'; $(dom.J_loginIn).parent().before(tHtml); $(dom.J_loginIn).removeAttr("disabled").val("登录").removeClass("a"); } },function(e){ console.log(e); }); } },function(e){ console.log(e); }); }, reloadCode:function(){ var date = new Date(); $(dom.J_img).attr("src",urls+ "/page/loginCaptcha.jsp?id=" + date.getMilliseconds()); } }; })(); $(function(){ login.init(); }); })(jQuery,pubFuc||{});<file_sep>/找电缆EXCEL处理2.0新版/布电线/数据表匹配查询.py #将几张数据表的数据进行逻辑性处理 import pymysql import time import xlwt def get_excel_name_from_zhaodianlan_data(): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select excel_name from zhaodianlan_data where status=0 and excel_name like '%中高压电缆%' group by excel_name" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_data_from_zhaodianlan_data(excel_name): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,excel_name,sheet_name,type_specification,lev_zr,price from zhaodianlan_data where status=0 and excel_name='%s'" %excel_name try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_data_from_zhaodianlan_type_detail(table_id): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select 结构,材质,芯数,国标,型号,电压,规格,类别,阻燃,价格 from zhaodianlan_type_detail where table_id='%s' and is_useful=1 " %table_id try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_type_detail-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_data_from_zhaodianlan_template(jiegou,caizhi,xinshu,type,dianya,guige,leibie,zuran): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor if guige.endswith("*1.0"): guige2=guige.replace("*1.0","*1") else: guige2=guige if zuran=="": type_solution=" and type_name like '"+type+"' " else: type_solution=" and type_name like '%"+type+"' " cursor = db.cursor() sql = "select excel_name,cate_name,type_name,factory,brand_name,providence,city,useful_date,"\ "is_sale,day,average_calc,attribute,stock,productive_year,table_id "\ "from zhaodianlan_template"\ " where excel_name like '%"+jiegou+"%' and excel_name like '%"+caizhi+"%' "\ " and excel_name like '%"+xinshu+"%' "\ " and type_name like'"+type+"' and (specification='"+guige+"' or specification='"+guige2+"') and voltage='"+dianya+"' "+type_solution print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_status_from_zhaodianlan_data(table_id,status): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update zhaodianlan_data set status='%d' where table_id='%s' " %(status,table_id) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_status_from_zhaodianlan_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_status_from_zhaodianlan_template(table_id,status): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update zhaodianlan_template set status='%d' where table_id='%s' " %(status,table_id) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_status_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #从zhaodianlan_data中读取一条数据 data_excel_name=get_excel_name_from_zhaodianlan_data() for m in range (len(data_excel_name)): excel_name=data_excel_name[m][0] print(excel_name) data=get_data_from_zhaodianlan_data(excel_name) wbk = xlwt.Workbook() sheet1 = wbk.add_sheet('sheet 1') sheet1.write(0, 0, "类目") sheet1.write(0, 1, "型号") sheet1.write(0, 2, "规格") sheet1.write(0, 3, "电压") sheet1.write(0, 4, "厂商") sheet1.write(0, 5, "品牌") sheet1.write(0, 6, "省") sheet1.write(0, 7, "市") sheet1.write(0, 8, "价格(元/单位)") sheet1.write(0, 9, "商品有效期") sheet1.write(0, 10, "是否上架") sheet1.write(0, 11, "交货期(天)") sheet1.write(0, 12, "权重值") sheet1.write(0, 13, "参与均价计算") sheet1.write(0, 14, "属性") sheet1.write(0, 15, "库存") sheet1.write(0, 16, "生产年份") new_path = "D:\BI\找电缆\已匹配\\" + excel_name.replace("xlsx", "xls") wbk.save(new_path) x_num = 1 for i in range(len(data)): table_id=data[i][0] excel_name=data[i][1] sheet_name=data[i][2] type_specification=data[i][3] lev_zr=data[i][4] price=data[i][5] #print(table_id,excel_name,sheet_name,type_specification,lev_zr,price) #将源数据,带入到zhaodianlan_type_detail中查询 data2=get_data_from_zhaodianlan_type_detail(table_id) #print(data2) if len(data2)==1: jiegou=data2[0][0] caizhi=data2[0][1] xinshu=data2[0][2] guobiao=data2[0][3] type=data2[0][4] dianya = data2[0][5] guige = data2[0][6] leibie = data2[0][7] #leibie暂时不加载 leibie="" zuran = data2[0][8] #如果是普通,那么直接省略,如果是ZR的, if zuran=="PT": zuran="" jiage = data2[0][9] data3=get_data_from_zhaodianlan_template(jiegou,caizhi,xinshu,type,dianya,guige,leibie,zuran) print("返回%s条结果"%str(len(data3))) print(data3) if len(data3)==0: #如果数据集为0,那么就说明是要新增的 #print("需要新增") #对于新增的数据,那么处理的方法应该是调整zhaodianlan_data中的状态为2 status=2 update_status_from_zhaodianlan_data(table_id,status) elif len(data3)==1: template_table_id = data3[0][14] print(template_table_id) if guige.endswith("*1.0"): guige = guige.replace("*1.0", "*1") print(str(len(data3[0])),str(x_num)) #结果为1,说明完全匹配上了结果,则将数据整理入excel中存放,参照走之前写的脚本 sheet1.write(x_num, 0, data3[0][1]) sheet1.write(x_num, 1, data3[0][2]) sheet1.write(x_num, 2, guige) sheet1.write(x_num, 3, dianya) sheet1.write(x_num, 4, data3[0][3]) sheet1.write(x_num, 5, data3[0][4]) sheet1.write(x_num, 6, data3[0][5]) sheet1.write(x_num, 7, data3[0][6]) sheet1.write(x_num, 8, price) sheet1.write(x_num, 9, data3[0][7]) sheet1.write(x_num, 10, data3[0][8]) sheet1.write(x_num, 11, data3[0][9]) sheet1.write(x_num, 12, data3[0][10]) sheet1.write(x_num, 13, data3[0][11]) sheet1.write(x_num, 14, data3[0][12]) sheet1.write(x_num, 15, data3[0][13]) x_num+=1 status=1 update_status_from_zhaodianlan_template(template_table_id, status) else: #print("多条数据,检查并选择") #正常情况下,应该不会存在做这种,如果存在,那么估计就是说数据异常了 status = 2 update_status_from_zhaodianlan_data(table_id, status) new_path = "D:\BI\找电缆\已匹配\\" + excel_name.replace("xlsx", "xls") wbk.save(new_path) else: status = 2 update_status_from_zhaodianlan_data(table_id, status) <file_sep>/多线程/test2.py import requests from bs4 import BeautifulSoup #-----------------------------------------------------post请求ajax if __name__=="__main__": #print(type(response)) url = 'http://www.de-ele.com/ShoppingHandler.aspx' header={} header['Accept']='*/*' header['Accept-Encoding']='gzip, deflate' header['Accept-Language']='zh-CN,zh;q=0.8' header['Connection']='keep-alive' header['Content-Length']='6' header['Content-Type']='application/x-www-form-urlencoded' header['Host']='www.de-ele.com' #header['Origin']='(这个地方我删掉了,大家根据自己需要访问的来写)' header['Referer']='http://www.de-ele.com/2276.htm' header['User-Agent']='Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0' header['X-Requested']='XMLHttpRequest' data = {} data['action'] = 'UnUpsellingSku' data['productId'] = '2276' data['AttributeId'] = '65' data['ValueId'] = '387' data['sourceId'] = '0' r=requests.post(url,data=data,headers=header) htmlcontent=r.content.decode('utf-8') print(htmlcontent) #s1=BeautifulSoup(htmlcontent,'lxml').find_all('div',class_ ='brief') #for s in s1: # print(s.div.contents[0]) #-------------------------------post请求ajax`<file_sep>/工品汇/正泰.NET/工品汇2.1-详情内容.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver from selenium.common.exceptions import NoSuchElementException def s(a,b): t=random.randint(a,b) time.sleep(t) def company_info(): company_name="正泰" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() s(3,5) def get_url_status(): #company_name=company_info() db = pymysql.connect("localhost","root","123456","vipmro_chint",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select prt_id,prt_url from vipmro_net_data where status=0 order by table_id " try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(prt_id): db = pymysql.connect("localhost","root","123456","vipmro_chint",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_net_data set status=1 where prt_id='%s' " \ % (prt_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) cursor.close() db.close() def get_package_data(prt_id): divs=driver.find_elements_by_xpath("//div[@class='product-main-r-cont p-top5 J_productCont']/span") try: package=divs[3].text except IndexError as e: package='' print(package) update_package(package,prt_id) def update_package(package,prt_id): db = pymysql.connect("localhost","root","123456","vipmro_chint",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_net_data set package='%s' where prt_id='%s' " % (package,prt_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) cursor.close() db.close() def get_attrs_info(prt_id): attr_names=[] attr_values=[] tr_names=driver.find_elements_by_xpath("//table[@class='J_introduceList']/tbody/tr/td[@class='introduce-list-box-l']") tr_values=driver.find_elements_by_xpath("//table[@class='J_introduceList']/tbody/tr/td[@class='introduce-list-box-r']") print(str(len(tr_names)),str(len(tr_values))) for i in range (len(tr_names)): attr_name=tr_names[i].text attr_value=tr_values[i].get_attribute('innerHTML') print(attr_name,attr_value) attr_num=i+1 insert_attributes(prt_id, attr_name, attr_value, attr_num) def insert_attributes(prt_id,attr_name,attr_value,attr_num): db = pymysql.connect("localhost","root","123456","vipmro_chint",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into vipmro_net_attribute (sku_id,attribute_name,attribute_value,attribute_num) values('%s','%s','%s','%s') " % (prt_id,attr_name,attr_value,attr_num) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) cursor.close() db.close() def get_content(prt_id): prt_content=driver.find_element_by_xpath("//div[@class='product-detail-body center p-top20 p-bottom20 J_productBody']").get_attribute('innerHTML') prt_content='<div class="product-detail-body center p-top20 p-bottom20 J_productBody">'+prt_content+'</div>' insert_content(prt_id, prt_content) def insert_content(prt_id,prt_desc): db = pymysql.connect("localhost","root","123456","vipmro_chint",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into vipmro_net_desc (prt_id,prt_desc) values('%s','%s') " % (prt_id,prt_desc) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) cursor.close() db.close() def get_prt_img(prt_id): prt_imgs=driver.find_elements_by_xpath("//ul[@class='J_smallImage smallImage']/li/img") print("共%s张主图"%str(len(prt_imgs))) for i in range (len(prt_imgs)): img_url=prt_imgs[i].get_attribute('src') img_name=prt_id+str(i+1) print(img_name,img_url) img_num=i+1 insert_imgs(prt_id, img_name, img_url, img_num, "prt_img") def insert_imgs(prt_id,img_name,original_url,img_num,img_type): db = pymysql.connect("localhost","root","123456","vipmro_chint",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into vipmro_net_img_info (prt_id,img_name,original_url,img_num,img_type) values('%s','%s','%s','%s','%s') " % (prt_id,img_name,original_url,img_num,img_type) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) cursor.close() db.close() if __name__=="__main__": browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() url = "http://www.vipmro.net/login" driver.get(url) s(3, 5) uid='18861779873' pwd='<PASSWORD>6' login_url(uid,pwd) #完成登录 #点击一下搜索按钮,使页面正确加载url #driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() driver.get("http://www.vipmro.net/search?keyword=%25E6%2596%25BD%25E8%2580%2590%25E5%25BE%25B7") s(3, 5) driver.find_element_by_css_selector(".index-button.cursor.ft14.J_searchListTop").click() s(3, 5) data = get_url_status() for i in range (len(data)): prt_id=data[i][0] prt_url=data[i][1] #url=str(url_t).replace("(('","").replace("',),)","") print(prt_id,prt_url) #url=u'http://www.vipmro.net/search?keyword=%25E5%25BE%25B7%25E5%258A%259B%25E8%25A5%25BF&categoryId=50101811' driver.get(prt_url) s(4, 6) #简单描述下在详情页需要获取的数据 #包装数,在商品属性里面 #商品主图 #详情内容 #销售属性 #先处理包装数量的获取 #get_package_data(prt_id) #处理销售属性 #get_attrs_info(prt_id) #详情内容 #get_content(prt_id) #商品主图 get_prt_img(prt_id) update_status_to_run_log(prt_id) <file_sep>/JD后台/图片上传-商品主图上传/商品主图上传V0726.py #第一版,只是完成了整个流程的调试,第二版,需要增加参数,循环等 import pymysql import time import random import logging import win32gui import win32con import pyperclip from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.select import Select logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #判断是否登陆成功 name = input("Go?") print(name) #通过url,找到需要修改图片的商品 sku_id='7952991' init_img_url="https://vcp.jd.com/sub_item/itemPic/initEditItemPicInfo?wareId=%s&saleState=1&isProEdit=true"%sku_id driver.get(init_img_url) self.s(2,3) del_imgs=driver.find_elements_by_class_name("delete-img") for x in range(len(del_imgs)-1): driver.find_element_by_class_name("delete-img").click() self.s(1,2) #删除完当前的图片后,使用win32gui去上传图片 driver.find_element_by_id("img-plus-id").click() self.s(1,2) #获取句柄 # win32gui dialog = win32gui.FindWindow('#32770', u'打开') # 对话框 ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮Button win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, 'D:\\bv(r)_imgs\\主图2-裸线BVR-黄(20180725).jpg') # 往输入框输入绝对地址 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) # 按button while 1==1: try: driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() break except Exception as e: print("waitting") self.s(2, 4) #上传完成第一张主图后,还有后面的四张,按照数据表吧,先调通整个流程 driver.find_element_by_id("img-plus-id").click() self.s(1,2) # win32gui dialog = win32gui.FindWindow('#32770', u'打开') # 对话框 ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮Button win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None,'"主图2-裸线-红(20180725).jpg" "主图1-裸线-黄(20180725).jpg" "主图2-裸线BVR-绿(20180725).jpg" "主图2-裸线BVR-双(20180725).jpg"' ) # 往输入框输入绝对地址 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) # 按button self.s(10,13) while 1==1: try: driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() break except Exception as e: print("waitting") self.s(2, 4) driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() self.s(1, 2) #切换到透明图 driver.find_elements_by_xpath("//ul[@class='tabs']/li")[1].click() self.s(1,2) try: driver.find_element_by_xpath("//div[@class='img-bar-div-lucency']/img[@class='delete-img']").click() except Exception as e: print(e) self.s(1, 2) # 删除完当前的图片后,使用win32gui去上传图片 driver.find_element_by_id("img-plus-id-lucency").click() self.s(1, 2) #chrome://settings/content/flash # 获取句柄 # win32gui dialog = win32gui.FindWindow('#32770', u'打开') # 对话框 ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None) Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None) # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄 button = win32gui.FindWindowEx(dialog, 0, 'Button', None) # 确定按钮Button win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, 'D:\\bv(r)_imgs\\裸线-红(20180725).png') # 往输入框输入绝对地址 win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) # 按button self.s(8, 10) driver.find_element_by_xpath("//div[@id='system_alert']/div/button").click() #到以上,已经完成整个商品的图片上传 #提交任务 driver.find_element_by_id("mySubmitLucency").click() #凤鸣 def update_status(self,table_id): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update upload_prt_basic_info set status=1 where table_id='%s'" %table_id print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_upload_data(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select * from upload_prt_basic_info where status=0 and 一级分类='工业品' order by table_id" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/日常工作/西门子开关详情内容url更新.py import cx_Oracle import pandas as pd import time import pymysql def find_prt_data(): if current_version == "test": db = cx_Oracle.connect('mmbao2_bi/<EMAIL>:21252/mmbao2b2c') else: db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@192.168.127.12:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT ID,prt_title,series FROM mmbao2.t_prt_entity"\ " WHERE shop_id='1781287' AND is_use=1 AND is_sale=1 AND is_delete=0 "\ " AND series IN ('品宜白系列','远景金系列','远景白系列','灵致白系列','远景银系列','灵致金系列')" print(sql) cursor.execute(sql) data = cursor.fetchall() return data def find_pc_content(prt_id): if current_version == "test": db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.mmbao.com:21252/mmbao2b2c') else: db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@192.168.127.12:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT pc_content FROM mmbao2.t_prt_entity WHERE id='%s'" % prt_id #print(sql) cursor.execute(sql) pc_content=[] for row in cursor: pc_content.append(row[0].read()) #print(row[0].read()) #print(pc_content) return pc_content def insert_data(prt_id,prt_title,series,pc_content,content_table): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into mmbao_prt_pc_content values('%s','%s','%s','%s','%s')" %(prt_id,prt_title,series,pc_content,content_table) # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('-------get_mysql_data--------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": current_version='proc' original_prt_data=find_prt_data() #print(original_prt_data) for i in range (len(original_prt_data)): prt_id=original_prt_data[i][0] prt_title = original_prt_data[i][1] series = original_prt_data[i][2] print(prt_id) #重新导数据表寻找对应的pc_content pc_content=find_pc_content(prt_id) content_table=pc_content[0].split('</table>')[0]+'</table>' insert_data(prt_id,prt_title,series,pc_content[0],content_table) time.sleep(0.2) <file_sep>/MMBAO筛选所有的搜索词/筛选所有的搜索词.py import urllib.parse import pymysql from urllib import request from bs4 import BeautifulSoup def get_keywords(): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") cursor = db.cursor() sql = "select keyword from MMBAO_KEYWORDS where status=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() # 获取html函数,参数:url def getHtml(url): req = request.Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/47.0") response = request.urlopen(req) html = response.read().decode('utf-8') # print(html) return html def find_data(html): soup=BeautifulSoup(html,'html.parser') prt_text=soup.find('div',attrs={'class':'mt crumbs clearfix'}).find('div',attrs={'class':'fl'}).find_all('span')[1].text prt_cnt=prt_text[prt_text.rindex("商品")+2:prt_text.rindex("个")] return prt_text,prt_cnt def update_status(key_word,prt_cnt): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") cursor = db.cursor() sql = "update MMBAO_KEYWORDS set status=1,cnt='%s' where status=0 and keyword='%s'" %(prt_cnt,key_word) print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": for i in range (100000): data=get_keywords() key_word=data[0][0] keywords=urllib.parse.quote(key_word) search_url = u"http://search.mmbao.com/?keywords="+keywords+"&searchSource=1" html=getHtml(search_url) #print(html) prt_text, prt_cnt=find_data(html) update_status(key_word,prt_cnt)<file_sep>/MMBAO.COM遍历URL筛选404链接-1.1/获取URL返回状态-V2.1-多进程版.py import pymysql import requests import time from multiprocessing import Pool def get_url(solution): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select href_current from url_code where status=0 " + solution #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_url-------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status(href_current): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="update url_code set status=1 where href_current='%s'" %href_current #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_status-------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def get_code(url): try: r = requests.get(url) return r.status_code except requests.exceptions.ConnectTimeout: NETWORK_STATUS = False code='ConnectTimeout' return code except requests.exceptions.ConnectionError: code='ConnectionError' return code except requests.exceptions.InvalidURL: code='InvalidURL' return code def update_code(url,code): db = pymysql.connect("localhost", "root", "123456", "tmp", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql = "update url_code set code='%s' where href_current='%s' " % (code,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def task(name): #print("start the %s process"%name) if name==0: solution=" and table_id<=35000 limit 1 " elif name==1: solution=" and table_id>35000 and table_id<=70000 limit 1 " elif name==2: solution=" and table_id>70000 and table_id<=105000 limit 1 " elif name==3: solution=" and table_id>105000 and table_id<=140000 limit 1 " data=get_url(solution) href=data[0][0] print(href) update_status(href) if "mmbao" in href: if "jpg" not in href: if "png" not in href: if ";" not in href: code=get_code(href) #print("%s:%s"%(href,code)) update_code(href, code) else: update_code(href, ";") else: update_code(href, "PNG") else: update_code(href, "jpg") else: update_code(href, "NONE_MMBAO") def get_cnt(): db = pymysql.connect("localhost","root","123456","tmp",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select count(href_current) as cnt from url_code where status=0" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() if __name__=="__main__": keywords=["jpg",'png',";"] data=get_cnt() cnt=data[0][0] print(cnt) for x in range (int(cnt)): start = time.time() p=Pool() for i in range(4): p.apply_async(func=task,args=(i,)) p.close() p.join() end=time.time() #print(end - start) <file_sep>/dianlan.cn/获取各线缆型号对应的重量.py import pymysql import time from selenium import webdriver def insert_into_detail_lists(detail_name,detail_href,spu_name,brand_name,publisher): db = pymysql.connect("localhost", "root", "123456", "dianlan_cn") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into detail_lists (detail_name,detail_href,spu_name,brand_name,publisher) values('%s','%s','%s','%s','%s') " %(detail_name,detail_href,spu_name,brand_name,publisher) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": url="http://www.dianlan.cn/lzj/zhanshi.html" browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #加载主页面,等待输入型号名称进行查询 keywords=['YH','ZC-KVVP' ] print(str(len(keywords))) for x in range (len(keywords)): print(keywords[x]) driver.find_element_by_id('smodelCode').clear() driver.find_element_by_id('smodelCode').send_keys(keywords[x]) time.sleep(1) driver.find_element_by_xpath("//input[@class='btn_ss']").click() #页面刷新,获取对应的每个列表展示的名称对应的url time.sleep(30) links=driver.find_elements_by_xpath("//ul[@id='list_tab']/li/a") print("current pages have %s links" %(str(len(links)))) names = driver.find_elements_by_xpath("//ul[@id='list_tab']/li/a/div/span[@id='sublen']") print("current pages have %s names" % (str(len(names)))) spu_names = driver.find_elements_by_xpath("//ul[@id='list_tab']/li/a/div/span[@id='modelNamelen']") brand_names = driver.find_elements_by_xpath("//ul[@id='list_tab']/li/a/div/span[@id='brandlen']") publishers=driver.find_elements_by_xpath("//ul[@id='list_tab']/li/a/div[@class='cr_industry cr_bscon']") for i in range (len(links)): detail_href=links[i].get_attribute('href') detail_name=names[i].text spu_name=spu_names[i].get_attribute('title') brand_name=brand_names[i].text publisher=publishers[i].text print(detail_name,detail_href,spu_name,brand_name,publisher) insert_into_detail_lists(detail_name,detail_href,spu_name,brand_name,publisher)<file_sep>/untitled/Selenium/工品汇/伊顿电气-20170831/图片下载.py import os import urllib.request import pymysql import sys import shutil #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(product_id,img_url, img_name): if (len(img_url) != 0): fileName = img_name file_path=u"D:\\BI\\Upload\\IMG\\"+product_id try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) except: print("这图我没法下载") #复制图片 def copy_Img(prt_id_exist,prt_id,img_name): #暂时不加异常捕捉机制,试运行 src="D:\\BI\\Upload\\IMG\\"+prt_id_exist+"\\"+img_name dst="D:\\BI\\Upload\\IMG\\"+prt_id+"\\"+img_name print("waiting for "+src+" =>=>=>=>=>=> "+dst) file_path = u"D:\\BI\\Upload\\IMG\\" + prt_id createFileWithFileName(file_path, img_name) shutil.copyfile(src,dst) print("复制成功") def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,original_url from prt_img_info where state=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def is_existed(img_name,url): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_id,img_name,original_url from prt_img_info where state=1 and img_name='%s' and original_url='%s' limit 1" %(img_name,url) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_state(prt_id,url,state,is_repeat,file_path): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update prt_img_info set state='%d',is_repeat='%d',img_path='%s' where prt_id='%s' and original_url='%s'" %(state,is_repeat,file_path,prt_id,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #从数据表获取prt_id,img_url,img_name for i in range (5600): data=get_prt_data() prt_id=data[0][0] img_name=data[0][1] url=data[0][2] print(prt_id,img_name,url) #判断是否已经存在相同的图片,进行复制,而不是重新下载 data=is_existed(img_name,url) if len(data)==0: print("不存在相同的耶") getAndSaveImg(prt_id, url, img_name) state=1 is_repeat=0 update_state(prt_id,url,state,is_repeat,"") else: prt_id_exist=data[0][0] print("已存在相同的数据prt_id=%s"%prt_id_exist) copy_Img(prt_id_exist,prt_id,img_name) #返回状态更新,以及path更新 state=1 is_repeat=1 update_state(prt_id,url,state,is_repeat,"") print("-------------------------------------") #返回path路径,更新到数据表字段 <file_sep>/MMBAO/对SKU进行属性的获取补充/part1.py import pymysql import time def get_category_data(): db = pymysql.connect("localhost","root","123456","mmbao_data",charset="utf8" ) cursor = db.cursor() sql="select lev3_cat_id,attr_name from category_attribute_link where status=0 limit 1" try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_sku_data(lev3_category_id): db = pymysql.connect("localhost","root","123456","mmbao_data",charset="utf8" ) cursor = db.cursor() sql="select table_id,lev3_cat_id,prt_id,sku_id,sku_title,attr_name,attr_val from sku_attribute_link where lev3_cat_id='%s' " %lev3_category_id try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def filter_data(table_id,lev3_cat_id,prt_id,sku_id,sku_title,attr_name,attr_val): pass def update_status(lev3_category_id,attribute_name): db = pymysql.connect("localhost","root","123456","mmbao_data",charset="utf8" ) cursor = db.cursor() sql="update category_attribute_link set status=1 where lev3_cat_id='%s' and attr_name='%s' " %(lev3_category_id,attribute_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": for x in range (16): category_data=get_category_data() lev3_category_id=category_data[0][0] attribute_name=category_data[0][1] print(lev3_category_id,attribute_name) data=get_sku_data(lev3_category_id) for i in range (len(data)): table_id=data[i][0] lev3_cat_id = data[i][1] prt_id = data[i][2] sku_id = data[i][3] sku_title = data[i][4] attr_name = data[i][5] attr_val = data[i][6] print(table_id,lev3_cat_id,prt_id,sku_id,sku_title,attr_name,attr_val) #筛选 filter_data(table_id,lev3_cat_id,prt_id,sku_id,sku_title,attr_name,attr_val) update_status(lev3_category_id,attribute_name) print('-----------------------') time.sleep(10)<file_sep>/地址拆分/热点图制作-test.py import pymysql import time from chinese_province_city_area_mapper.transformer import CPCATransformer from chinese_province_city_area_mapper import drawers def find_data_from_address(): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,country,province,city,district from search_keywords_address " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #将address保存到数据表,使用省进行轰炸,把结果更新到数据表,然后再用市轰炸 #取出所有地址 location_str = [] data=find_data_from_address() cpca = CPCATransformer() for i in range (len(data)): table_id=data[i][0] country=data[i][1] province = data[i][2] city = data[i][3] district = data[i][4] address=country+province+city+district location_str.append(address) df,is_multiple = cpca.transform(location_str) # df为上一段代码输出的df drawers.draw_locations(df, "df.html") <file_sep>/MMBAO/对搜索词返回商品标题结果集-2017年11月29日/main_scripts.py #从excel中获取100个搜索词 #将搜索词带入到网站的搜索框 #返回列表中的前10个产品 #将结果集写入数据表 import pymysql import xlrd import urllib.request from selenium import webdriver from bs4 import BeautifulSoup def get_excel_data(file_name): data = xlrd.open_workbook(file_name) # 打开excel sheetName = data.sheet_names()[0] table = data.sheets()[0] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 data_lists = [] print(sheetName) for i in range(1, nrows): ss = table.row_values(i) # 获取一行的所有值,每一列的值以列表项存在 # print ss data_lists.append(ss) return data_lists def get_lists_data(html): soup=BeautifulSoup(html,'html.parser') lists=soup.find_all('div',attrs={'class':'goods_box'}) if __name__=="__main__": browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/Administrator/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() file_name=r"D:\BI\买卖宝\搜索词返回结果集.xlsx" data=get_excel_data(file_name) for i in range (len(data)): search_keyword=data[i][0] url=r"http://search.mmbao.com/?keywords="+search_keyword+"&searchSource=1" print(url) driver.get(url) html = driver.page_source get_lists_data(html)<file_sep>/untitled/代理/公用快代理函数.py import urllib.request import pymysql import random from bs4 import BeautifulSoup def get_data(): try: conn = pymysql.connect("localhost", "root", "<PASSWORD>", "test01") cursor = conn.cursor() #count获取的是满足查询条件的数量 count=cursor.execute('select ip_address from proxy_info') ## 或者使用fetchmany(),打印表中的多少数据 ##info = cursor.fetchmany(count) #for循环count次,使用fetchone()将游标中的值遍历 for i in range (int(count)): list=cursor.fetchone() list=str(list).replace("('","").replace("',)","") ip_list.append(list) #print(list) conn.close() except: return get_data() def check_ip(): try: url="http://www.whatismyip.com.tw" #将参数随机化,从数据表获取 rand_1=random.randint(1,len(ip_list)) ip_address=ip_list[rand_1] proxy_support=urllib.request.ProxyHandler({'http':ip_address}) opener=urllib.request.build_opener(proxy_support) opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0')] urllib.request.install_opener(opener) response=urllib.request.urlopen(url) html=response.read().decode('utf-8') #print(html) soup = BeautifulSoup(html,'lxml') ip_name=soup.find('h1') ip_address=soup.find('h2') print(str(ip_name.text)+":"+str(ip_address.text)) print('尝试访问DQ123') except: print('异常-check_ip()') return check_ip() if __name__=="__main__": ip_list=[] get_data() print(ip_list) check_ip() <file_sep>/JD后台/销售区域黑名单/增加销售区域黑名单.py import pymysql import time import random import logging from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.select import Select logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 #option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #判断是否登陆成功 name = input("Go?") print(name) init_url="https://vcp.jd.com/sub_dropship/salesAreaBlacklist/initListPage" #sku_id='7952991' sku_data=self.get_sku_id() for i in range(len(sku_data)): driver.get(init_url) sku_id = sku_data[i][0] driver.find_element_by_id('sku').clear() driver.find_element_by_id('sku').send_keys(sku_id) driver.find_element_by_id('btnQuery').click() self.s(2,3) status=0 #查看有没有返回相关的饿记录 try: tr_lists=driver.find_elements_by_xpath("//table[@id='58remote2']/tbody/tr") print(len(tr_lists)) if len(tr_lists)>1: if len(tr_lists)==12: print("已完成配置11项,现删减") driver.find_element_by_id("jqg_58remote2_8").click() driver.find_element_by_id("jqg_58remote2_10").click() driver.find_element_by_id("jqg_58remote2_11").click() driver.find_element_by_id("jqg_58remote2_28").click() driver.find_element_by_id("jqg_58remote2_29").click() driver.find_element_by_id("jqg_58remote2_30").click() driver.find_element_by_id("jqg_58remote2_31").click() driver.find_elements_by_class_name(("ui-pg-div"))[-1].click() self.s(1, 1) driver.find_elements_by_xpath("//div[@id='system_confirm']/div[@class='pui-dialog-buttonpane ui-widget-content ui-helper-clearfix']/button")[0].click() self.s(1,2) status=1 else: print("已配置,但异常") try: driver.find_element_by_id("jqg_58remote2_8").click() driver.find_element_by_id("jqg_58remote2_10").click() driver.find_element_by_id("jqg_58remote2_11").click() driver.find_element_by_id("jqg_58remote2_28").click() driver.find_element_by_id("jqg_58remote2_29").click() driver.find_element_by_id("jqg_58remote2_30").click() driver.find_element_by_id("jqg_58remote2_31").click() driver.find_elements_by_class_name(("ui-pg-div"))[-1].click() self.s(1, 1) driver.find_elements_by_xpath( "//div[@id='system_confirm']/div[@class='pui-dialog-buttonpane ui-widget-content ui-helper-clearfix']/button")[ 0].click() self.s(1, 2) status = 1 except: status = 3 pass except Exception as e: print(e) if status==0: #进行配置 driver.find_elements_by_xpath("//div[@class='ui-pg-div']")[0].click() try: driver.find_element_by_xpath("//div[@id='system_alert']/div[@class='pui-dialog-buttonpane ui-widget-content ui-helper-clearfix']/button").click() print("可能需要配置厂直") status=4 except Exception as e: print(e) pass if status == 0: self.s(2,3) #查找对应的id,jinxingcclick driver.find_element_by_id("jqg_58remote2Win_26").click() driver.find_element_by_id("jqg_58remote2Win_32").click() driver.find_element_by_id("jqg_58remote2Win_84").click() driver.find_element_by_id("jqg_58remote2Win_52993").click() self.s(1,2) driver.find_elements_by_xpath("//div[@class='ui-pg-div']")[2].click() self.s(1, 1) driver.find_elements_by_xpath("//div[@id='system_confirm']/div[@class='pui-dialog-buttonpane ui-widget-content ui-helper-clearfix']/button")[0].click() status=1 self.s(2, 3) self.upload_status(sku_id,status) def get_sku_id(self): db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select sku_id from 销售区域黑名单 where status=0 " #print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def upload_status(self,sku_id,status): db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update 销售区域黑名单 set status='%d' where sku_id='%s' " %(status,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('----------upload_status-----Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/Scrapy/dq123/dq123/pipelines.py # -*- coding: utf-8 -*- import os import urllib class Dq123Pipeline(object): def process_item(self, item, spider): return item <file_sep>/untitled/Selenium/dq123/dq123数据获取-20170831/伊顿电气-类目获取.py from urllib import request from bs4 import BeautifulSoup import re import pymysql def getHtml(url): req = request.Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/47.0") response = request.urlopen(req) html = response.read().decode('utf-8') # print(html) return html def insert_cates(cate1_name,cate2_name,cate3_name,cate4_name,cate5_name): db = pymysql.connect("localhost","root","123456","yidun",charset="utf8" ) cursor = db.cursor() sql="insert into category_info (cate1_name,cate2_name,cate3_name,cate4_name,cate5_name) values('%s','%s','%s','%s','%s')" %(cate1_name,cate2_name,cate3_name,cate4_name,cate5_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() #嵌套循环,不好分出函数 def find_data(html): soup=BeautifulSoup(html,"lxml") li_cate1s=soup.findAll("li",attrs={'class':"level0"}) for li_cate1 in li_cate1s: #print(li_cate1) #一级类目获取 cate1_name=li_cate1.find('a',attrs={'class':'level0'}) cate1_name=cate1_name.get('title') print(cate1_name) cate2_name, cate3_name, cate4_name, cate5_name="","","","" insert_cates(cate1_name,cate2_name,cate3_name,cate4_name,cate5_name) #二级类目获取 li_cate2s=li_cate1.findAll('li',attrs={'class':'level1'}) for li_cate2 in li_cate2s: #print(li_cate2) # 一级类目获取 cate2_name = li_cate2.find('a', attrs={'class': 'level1'}) cate2_name = cate2_name.get('title') print(cate1_name,cate2_name) cate3_name, cate4_name, cate5_name = "", "", "" insert_cates(cate1_name, cate2_name, cate3_name, cate4_name, cate5_name) # 二级类目获取 li_cate3s = li_cate2.findAll('li', attrs={'class': 'level2'}) #print(len(li_cate3s)) for li_cate3 in li_cate3s: cate3_name = li_cate3.find('a', attrs={'class': 'level2'}) cate3_name = cate3_name.get('title') print(cate1_name, cate2_name, cate3_name) cate4_name, cate5_name = "", "" insert_cates(cate1_name, cate2_name, cate3_name, cate4_name, cate5_name) # 二级类目获取 li_cate4s = li_cate3.findAll('li', attrs={'class': 'level3'}) #print(len(li_cate4s)) for li_cate4 in li_cate4s: cate4_name = li_cate4.find('a', attrs={'class': 'level3'}) cate4_name = cate4_name.get('title') print(cate1_name, cate2_name, cate3_name, cate4_name) cate5_name = "" insert_cates(cate1_name, cate2_name, cate3_name, cate4_name, cate5_name) # 二级类目获取 li_cate5s = li_cate4.findAll('li', attrs={'class': 'level4'}) #print(len(li_cate5s)) for li_cate5 in li_cate5s: cate5_name = li_cate5.find('a', attrs={'class': 'level3'}) cate5_name = cate5_name.get('title') print(cate1_name, cate2_name, cate3_name, cate4_name, cate5_name) insert_cates(cate1_name, cate2_name, cate3_name, cate4_name, cate5_name) if __name__=="__main__": url="file:///D:/BI/dq123厂家及类目获取/伊顿电气.html" html=getHtml(url) #print(html) find_data(html) print("---------------完成类目的获取与存储,请不要删除-file:///D:/BI/dq123厂家及类目获取/伊顿电气.html-该文件--------------------")<file_sep>/JD后台/VC后台/测试下拉框.py # coding=utf-8 from selenium import webdriver import os, time from selenium.webdriver.support.ui import Select from selenium.webdriver.support.select import Select <<<<<<< HEAD browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 ======= browser = "Chrome" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/Administrator/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 >>>>>>> origin/master driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() <<<<<<< HEAD file_path = "file:///C:/Users/CC-SERVER/Desktop/zx.html" ======= file_path = "file:///C:/Users/Administrator/Desktop/zx.html" >>>>>>> origin/master print(file_path) driver.get(file_path) time.sleep(1) # 先定位到下拉框 #m = driver.find_element_by_xpath("//*[@id='ShippingMethod']") # 再点击下拉框下的选项 #m.find_element_by_xpath("//*[@id='ShippingMethod']/option[3]").click() #driver.find_element_by_xpath("//select[@id='ShippingMethod']/option[@value='10.69']").click() <<<<<<< HEAD Select(driver.find_element_by_id("ShippingMethod")).select_by_value("10.69") driver.find_element_by_id("ShippingMethod").click() time.sleep(1) driver.find_element_by_xpath("//select[@id='ShippingMethod']/option[@value='10.69']").click() s=driver.find_element_by_xpath("//select[@id='ShippingMethod']/option[@value='10.69']").text print(s) ======= Select(driver.find_element_by_id("s1")).select_by_visible_text("bb") #driver.find_element_by_id("s1").click() #time.sleep(1) #driver.find_element_by_xpath("//select[@id='ShippingMethod']/option[@value='10.69']").click() #s=driver.find_element_by_xpath("//select[@id='ShippingMethod']/option[@value='10.69']").text #print(s) >>>>>>> origin/master <file_sep>/untitled/Selenium/天眼查2-当异常由日志导入.py import xlsxwriter def save_excel(fin_result2,fin_result3,fin_result4): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\test1.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result2)): tmp.write(i, 1, fin_result2[i]) tmp.write(i, 2, fin_result3[i]) tmp.write(i, 3, fin_result4[i]) if __name__ == '__main__': leader = ['曾义宏', '齐运增', '刘永辉', '孔德山', '张明', '肖峰(HSIAO KENNETH FENG)', '蒋亚军', '罗涛', '未找到', '张小芳', '孙昌银', '葛立英', '葛立英', '侯锦龙', '李丽娟', '未找到', '崔旭明', '林梅生'] phone = ['0551-64205959', '03728491143', '13311363225', '15810391480', '0551-62880273', '0519-82797909', '13861138659', '0519-82058700', '未找到', '0511-86611163', '0550-7723806', '未公开', '15920727342', '13702744816', '13802634648', '未找到', '34863221', '13538737728'] address = ['合肥市瑶海工业园站北路8号', '滑县白道口镇白道口东', '北京市昌平区百善镇狮子营村东', '北京市房山区石楼镇坨头村西坨头桥向北30米', '合肥市高新区创新大道1858号', '金坛区薛埠镇茅山大道888号', '金坛市儒林镇园区北路18号', '常州市钟楼区飞龙西路69号', '未找到', '丹阳市皇塘镇蒋墅迎宾西路70号', '安徽省天长市经济开发区', ' 地址: 佛山市南海区狮山镇沙头村红沙高新技术开发区惠国路东', '佛山市南海区狮山镇沙头村红沙高新技术开发区惠国路东', '佛山市南海区官窑大榄开发区', '佛山市南海区里水镇和桂工业园A区A-2栋', '未找到', '广州市番禺区大龙街沙涌村长沙路17号(厂房)', '广州市增城朱村街朱村大道中49号(厂房A3)'] save_excel(address,leader,phone) <file_sep>/TMALL/列表页数据获取/列表页销量评价获取-胜华电缆.py import pymysql from bs4 import BeautifulSoup from selenium import webdriver import time import re def get_useful_data(html): soup=BeautifulSoup(html,'html.parser') prt_divs=soup.find_all('dl',attrs={'class':re.compile('item ')}) print("current page have %s records"%str(len(prt_divs))) for prt_div in prt_divs: prt_price=prt_div.find('div',attrs={'class':'cprice-area'}).text print("prt_price",prt_price) prt_title = prt_div.find('dd', attrs={'class': 'detail'}).find('a',attrs={'class':'item-name J_TGoldData'}).text print("prt_title", prt_title) prt_url = prt_div.find('dd', attrs={'class': 'detail'}).find('a',attrs={'class':'item-name J_TGoldData'}).get('href') print("prt_url", prt_url) #//detail.tmall.com/item.htm?id=524785657239&skuId=3573590028479&areaId=320200&user_id=923873351&cat_id=50067923&is_b=1&rn=a36346c54fc20f2a4d2dbed860331aa9 prt_id=prt_url.split("id=")[1].split('&rn')[0] print("prt_id",prt_id) prt_shop = "" #print("prt_shop", prt_shop) prt_sales = prt_div.find('div', attrs={'class': 'sale-area'}).find('span',attrs={'class':'sale-num'}).text prt_evaluations = prt_div.find('dd', attrs={'class': 'rates'}).find('span').text print("prt_sales,prt_evaluations", prt_sales,prt_evaluations) insert_prt_lists_data(prt_id, prt_url, prt_title, prt_price, prt_shop, prt_sales, prt_evaluations) def insert_prt_lists_data(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations): prt_title=prt_title.replace("\n","") prt_shop=prt_shop.replace("\n","") db = pymysql.connect("localhost", "root", "123456", "tmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_lists_info (prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) values('%s','%s','%s','%s','%s','%s','%s')" \ %(prt_id,prt_url,prt_title,prt_price,prt_shop,prt_sales,prt_evaluations) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def next_page(num): driver.find_element_by_class_name('ui-page-s-next').click() time.sleep(3) try: page_num=driver.find_element_by_class_name("ui-page-s-len").text print(page_num) page_num=page_num.split("/")[0] current_page=num+2 if current_page==page_num: print("success") except: temp = input("tmp") #在处理next_page时,应该会有两种跳转的结果,一种结果是返回登录页面,另一种是网警验证码页面,只能做等待处理 if __name__=="__main__": url="https://xinxindg.tmall.com/search.htm?spm=a1z10.3-b.w5002-13361519040.1.2af531a3RE3j2y&search=y" #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) temp = input("tmp") #将html带入到函数进行分析 for i in range(100): html = driver.page_source get_useful_data(html) next_page(i) <file_sep>/漫画大业/动漫之家/download_imgs.py import pymysql import requests import re import time import os import urllib.request import logging local_time=time.strftime("%Y-%m-%d %H%M",time.localtime(time.time())) filename = str.format('./logs/download_imgs_log_%s.txt'%local_time) logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s',filename=filename) #,filename=filename logger=logging.getLogger(__name__) from bs4 import BeautifulSoup class download_imgs(): def main(self): transformed_scripts=self.get_transformed_scripts() logger.info("%s records need to exec"%str(len(transformed_scripts))) for i in range (len(transformed_scripts)): table_id=transformed_scripts[i][0] chapter_title=transformed_scripts[i][1] transformed_script=transformed_scripts[i][2] comic_name=transformed_scripts[i][3] logger.info(str(table_id)+"#"+transformed_script) original_paths=transformed_script.split(",") for x in range (len(original_paths)): original_path=original_paths[x] #print(original_path) img_url="https://images.dmzj.com/"+original_path.replace('"','') logger.info(img_url) #经过尝试,请求的时候要带上来源,不然会报403错误 #content=self.get_imgs(table_id,img_url) status=self.getAndSaveImg(table_id,chapter_title,img_url,comic_name) #time.sleep(100) self.update_status(table_id,status) def get_transformed_scripts(self): db = pymysql.connect("localhost", "root", "123456", "comic") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select a.table_id,chapter_title,transformed_scripts,comic_name from comic_original_scripts a "\ "left join comic_introduction b on a.url=b.url "\ "where status=1 " logger.info(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() logger.info('------scripts_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def update_status(self,table_id,status): db = pymysql.connect("localhost", "root", "123456", "comic") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update comic_original_scripts set status='%d' where table_id='%s' " %(status,table_id) logger.info(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() logger.info('------scripts_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def get_imgs(self,table_id,url): headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0", "Accept-Language":"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer":"https://manhua.dmzj.com", "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } s=requests.get(url,headers=headers) content=s.content.decode('utf-8') #print(content) return content def createFileWithFileName(self,localPathParam, fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) logger.info(localPathParam + ' 创建成功') totalPath = localPathParam + '\\' + fileName if not os.path.exists(totalPath): file = open(totalPath, 'a+') file.close() return totalPath # 保存图片 def getAndSaveImg(self,table_id,chapter_title,img_url,comic_name): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer": "https://manhua.dmzj.com", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } if (len(img_url) != 0): img_name = img_url.split('/')[-1] img_name=urllib.request.unquote(img_name) logger.info(img_name) file_path = u"D:\\BI\\COMIC\\DMZJ\\" +comic_name+"\\"+ chapter_title fileName = file_path+"\\"+img_name self.createFileWithFileName(file_path, img_name) try: response = requests.get(img_url,headers=headers) #print(response.content) with open(fileName, 'wb') as f: f.write(response.content) f.flush() status = 2 except Exception as e: logger.info('当前图片无法下载 %s' %e) status=3 return status if __name__=="__main__": download_imgs=download_imgs() download_imgs.main()<file_sep>/python监控Windows进程/kill_py_process.py import os kill_process=os.popen('taskkill /f /t /im main_scripts.exe').read() title = "D:/logs.txt" with open(title, "a") as f: f.write('\n') f.write(kill_process) <file_sep>/untitled/Selenium/天眼查/天眼查2.0.py #1. 用于将所有需要的数据都写成函数进行分类划分,达到自由组合的目的 #引用 import xlrd import re import time import pymysql from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By def print_xls(): data=xlrd.open_workbook(r"D:\BI\Tianyancha\公司目录_input.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 Company_Name=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss Company_Name.append(ss) return Company_Name #列表页的数据 def list_info(): try: #检查url是否加载完成 lists=wait1.until(EC.presence_of_element_located((By.CLASS_NAME,"search_right_item"))) #列表模块 # 包括:法定代表人、注册资本、注册时间、地址 #company_info1 = driver.find_element_by_class_name("search_right_item") # 公司名称 name = lists.find_element_by_class_name("ng-binding").text detail_sum.append(name) print("公司名称:" + name) address=lists.find_element_by_css_selector(".search_base.col-xs-2.search_repadding2.text-right.c3.position-rel.ng-binding") # 地址 tmp=address.text province=tmp.split('\n') detail_sum.append(province[0]) print("地址:"+province[0]) # 列表页二级 company_info2 = lists.find_element_by_class_name("search_row_new") company_info2 = company_info2.find_elements_by_tag_name("span") # 法定代表人 legal_person = company_info2[0].text detail_sum.append(legal_person) print("法定代表人:" + legal_person) # 注册资本 fund = company_info2[1].text detail_sum.append(fund) print("注册资本:" + fund) # 注册时间 register_date = company_info2[2].text detail_sum.append(register_date) print("注册时间:" + register_date) except TimeoutException: return list_info() #公司详情页的数据 def detail_info(): try: co_info1 = wait2.until(EC.presence_of_element_located((By.CLASS_NAME,"company_header_width"))) tmp_1 = co_info1.find_elements_by_css_selector(".in-block.vertical-top.overflow-width.mr20") #电话 tmp_2 = tmp_1[0].find_elements_by_tag_name("span") phone = tmp_2[0].text + tmp_2[1].text phone=phone.replace("电话:","") detail_sum.append(phone) print("电话:"+phone) #公司网址 try: tmp_3=tmp_1[1].find_element_by_css_selector(".c9.ng-binding.ng-scope") company_url = tmp_3.text except: tmp_3 = tmp_1[1].find_elements_by_tag_name("span") company_url = tmp_3[0].text + tmp_3[1].text company_url = company_url.replace("网址:", "") detail_sum.append(company_url) print("网址:" + company_url) tmp_4=co_info1.find_elements_by_xpath("//div[@class='in-block vertical-top']") #公司邮箱 tmp_5=tmp_4[0].find_elements_by_tag_name("span") email=tmp_5[0].text+tmp_5[1].text email=email.replace("邮箱:","") detail_sum.append(email) print("邮箱:"+email) #公司地址 tmp_6 = tmp_4[1].find_elements_by_tag_name("span") address = tmp_6[0].text + tmp_6[1].text address=address.replace("地址:","") detail_sum.append(address) print("地址:"+address) ###################table详细内容###################### title=[] value=[] co_info2=wait2.until(EC.presence_of_element_located((By.CSS_SELECTOR,".row.b-c-white.company-content.base2017"))) info_list=co_info2.find_elements_by_class_name("basic-td") for i in range(len(info_list)): #tmp_title=info_list[i].text #title.append(tmp_title) tmp_value=info_list[i].find_element_by_tag_name("span").text value.append(tmp_value) #print(tmp_value) try: detail_sum.append(value[0]) print("工商注册号:"+value[0]) except: detail_sum.append("NULL") try: detail_sum.append(value[1]) print("组织机构代码:" + value[1]) except: detail_sum.append("NULL") try: detail_sum.append(value[2]) print("统一信用代码:" + value[2]) except: detail_sum.append("NULL") try: detail_sum.append(value[3]) print("企业类型:" + value[3]) except: detail_sum.append("NULL") try: detail_sum.append(value[4]) print("行业:" + value[4]) except: detail_sum.append("NULL") try: detail_sum.append(value[5]) print("营业期限:" + value[5]) except: detail_sum.append("NULL") try: detail_sum.append(value[6]) print("核准日期:" + value[6]) except: detail_sum.append("NULL") try: detail_sum.append(value[7]) print("登记机关:" + value[7]) except: detail_sum.append("NULL") try: detail_sum.append(value[8]) print("注册地址:" + value[8]) except: detail_sum.append("NULL") try: detail_sum.append(value[9]) print("经营范围:" + value[9]) except: detail_sum.append("NULL") except TimeoutException: return detail_info() def insert_mysql(detail_sum): db = pymysql.connect("localhost", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") COMPANY_NAME4EXCEL = detail_sum[0] COMPANY_NAME = detail_sum[1] PROVINCE = detail_sum[2] LEGAL = detail_sum[3] FUND = detail_sum[4] RELEASE_DATE = detail_sum[5] PHONE = detail_sum[6] COMPANY_URL = detail_sum[7] EMAIL = detail_sum[8] ADDRESS = detail_sum[9] REGISTER_CODE = detail_sum[10] ORGANIZATION_CODE = detail_sum[11] CREDIT_CODE = detail_sum[12] COMPANY_TYPE = detail_sum[13] INDUSTRY = detail_sum[14] MANAGE_DATE = detail_sum[15] AUDIT_DATE = detail_sum[16] AUDIT_ORGANIZATION = detail_sum[17] REGISTER_ADDRESS = detail_sum[18] BUSINESS_SCOPE = detail_sum[19] sql = "insert into TYC_DETAIL" \ " (COMPANY_NAME4EXCEL,COMPANY_NAME,PROVINCE,LEGAL,FUND,RELEASE_DATE,PHONE,COMPANY_URL,EMAIL,ADDRESS,REGISTER_CODE,ORGANIZATION_CODE,CREDIT_CODE,COMPANY_TYPE,INDUSTRY,MANAGE_DATE,AUDIT_DATE,AUDIT_ORGANIZATION,REGISTER_ADDRESS,BUSINESS_SCOPE)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (COMPANY_NAME4EXCEL,COMPANY_NAME,PROVINCE,LEGAL,FUND,RELEASE_DATE,PHONE,COMPANY_URL,EMAIL,ADDRESS,REGISTER_CODE,ORGANIZATION_CODE,CREDIT_CODE,COMPANY_TYPE,INDUSTRY,MANAGE_DATE,AUDIT_DATE,AUDIT_ORGANIZATION,REGISTER_ADDRESS,BUSINESS_SCOPE) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() if __name__=="__main__": #打开网站 driver=webdriver.Firefox() #driver.set_window_size(1400, 900) wait1 = WebDriverWait(driver, 1) #输入模块,公司名称 company_list=print_xls() #company_list=["核聚信息科技","中软国际"] for i in range(len(company_list)): detail_sum=[] company_name=str(company_list[i]) company_name=company_name.replace("['","").replace("']","") detail_sum.append(company_name) print(company_name) #载入url driver.get("http://www.tianyancha.com/search?key="+str(company_name)+"") #time.sleep(5) #两个模块, #判断是否能够找到对应的公司,如果true,则插入null的记录,否则执行正常的流程 try: wait1.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".f18.deepsearch.mt10.text-center.point"))) for y in range(19): detail_sum.append("NULL") except: # 1. 列表页中的数据获取 list_info() #点击跳转到公司详情页 time.sleep(0.5) company_info1 = driver.find_element_by_class_name("search_right_item") company_info1.find_element_by_class_name("ng-binding").click() wait2 = WebDriverWait(driver, 1) #time.sleep(1) #切换窗口,在页面跳转后,driver所对应的url并不是当前,而是列表页 handles = driver.window_handles #print(handles) driver.switch_to.window(handles[1]) # 2. 详情页的数据获取 detail_info() #insert into mysql insert_mysql(detail_sum) driver.close() #切换窗口,在页面跳转后,driver所对应的url并不是当前,而是列表页 handles = driver.window_handles #print(handles) driver.switch_to.window(handles[0]) print("#######################################################################") <file_sep>/漫画大业/动漫之家/dmzjV18.05.14.py import pymysql import requests import re import time import logging local_time=time.strftime("%Y-%m-%d %H%M",time.localtime(time.time())) filename = str.format('./logs/dmzj_log_%s.txt'%local_time) logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s',filename=filename) logger=logging.getLogger(__name__) from bs4 import BeautifulSoup class comic_dmzj(): def main(self): url="https://manhua.dmzj.com/tianjiangzhiwu" logger.info(url) content=self.get_content(url) #分析、提取数据 self.find_comic_introduction(content,url) chapter_titles, chapter_hrefs=self.find_comic_data(content) self.get_img_content(url,chapter_titles,chapter_hrefs) def get_content(self,url): headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0", "Accept-Language":"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer":"https://manhua.dmzj.com", "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } s=requests.get(url,headers=headers) content=s.content.decode('utf-8') #print(content) return content #漫画的描述,作者,连载日期等 def find_comic_introduction(self,content,url): # comic_attributes str_g_current_id = re.compile(r'g_current_id = ".*"') g_current_id = str_g_current_id.findall(content) g_current_id=g_current_id[0].split('"')[1] str_g_authors_py = re.compile(r'g_authors_py = ".*"') g_authors_py = str_g_authors_py.findall(content) g_authors_py = g_authors_py[0].split('"')[1] str_g_types_py = re.compile(r'g_types_py = ".*"') g_types_py = str_g_types_py.findall(content) g_types_py = g_types_py[0].split('"')[1] str_g_comic_name = re.compile(r'g_comic_name = ".*"') g_comic_name = str_g_comic_name.findall(content) g_comic_name = g_comic_name[0].split('"')[1] str_g_comic_url = re.compile(r'g_comic_url = ".*"') g_comic_url = str_g_comic_url.findall(content) g_comic_url = g_comic_url[0].split('"')[1] str_g_comic_id = re.compile(r'g_comic_id = ".*"') g_comic_id = str_g_comic_id.findall(content) g_comic_id = g_comic_id[0].split('"')[1] str_g_comic_code = re.compile(r'g_comic_code = ".*"') g_comic_code = str_g_comic_code.findall(content) g_comic_code = g_comic_code[0].split('"')[1] str_g_last_update = re.compile(r'g_last_update = ".*"') g_last_update = str_g_last_update.findall(content) g_last_update = g_last_update[0].split('"')[1] str_g_last_chapter_id = re.compile(r'g_last_chapter_id = ".*"') g_last_chapter_id = str_g_last_chapter_id.findall(content) g_last_chapter_id = g_last_chapter_id[0].split('"')[1] self.insert_comic_introduction(url,g_current_id, g_authors_py, g_types_py, g_comic_name, g_comic_url, g_comic_id, g_comic_code,g_last_update, g_last_chapter_id) #print(g_current_id,g_authors_py, g_types_py, g_comic_name, g_comic_url, g_comic_id, g_comic_code,g_last_update, g_last_chapter_id) println=g_current_id+"##"+g_authors_py+"##"+g_types_py+"##"+g_comic_name+"##"+g_comic_url+"##"+g_comic_id+"##"+g_comic_code+"##"+g_last_update+"##"+g_last_chapter_id logger.info(println) def find_comic_data(self,content): soup=BeautifulSoup(content,'html.parser') cartoon_online_border=soup.find('div',attrs={'class':'cartoon_online_border'}).find_all('li') logger.info("current page have %s records"%str(len(cartoon_online_border))) chapter_titles=[] chapter_hrefs=[] for i in range(len(cartoon_online_border)): chapter_info=cartoon_online_border[i].find('a') chapter_title=chapter_info.get("title") chapter_href=chapter_info.get("href") chapter_href="https://manhua.dmzj.com"+chapter_href logger.info(chapter_title+"##"+chapter_href) chapter_titles.append(chapter_title) chapter_hrefs.append(chapter_href) return chapter_titles,chapter_hrefs def get_img_content(self,url,chapter_titles,chapter_hrefs): for i in range (len(chapter_hrefs)): chapter_title=chapter_titles[i] chapter_href=chapter_hrefs[i] detail_content=self.get_content(chapter_href) self.get_imgs(url,detail_content,chapter_title,chapter_href) def get_imgs(self,url,detail_content,chapter_title,chapter_href): soup=BeautifulSoup(detail_content,'html.parser') #print(detail_content) str_img_script=re.compile(r'eval\(function.*{}\)\)') img_script = str_img_script.findall(detail_content) logger.info(img_script[0]) img_script=str(img_script[0]).replace("'","@").replace('"','$').replace('/','#').replace('\\','&') logger.info(img_script) self.insert_imgs_data(url,chapter_title,chapter_href,img_script) def insert_comic_introduction(self,url,g_current_id, g_authors_py, g_types_py, g_comic_name, g_comic_url, g_comic_id, g_comic_code,g_last_update, g_last_chapter_id): db = pymysql.connect("localhost", "root", "123456", "comic") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into comic_introduction (url,author,type,comic_name,comic_url,comic_id,comic_code,last_update,last_chapter_id) values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ %(url, g_authors_py, g_types_py, g_comic_name, g_comic_url, g_comic_id, g_comic_code,g_last_update, g_last_chapter_id) logger.info(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() logger.info('------insert_comic_introduction---------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_imgs_data(self,url,chapter_title,chapter_href,img_script): db = pymysql.connect("localhost", "root", "123456", "comic") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into comic_original_scripts (url,chapter_title,chapter_href,original_img_scripts) values('%s','%s','%s','%s') "%(url,chapter_title,chapter_href,img_script) logger.info(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() logger.info('------insert_imgs_data---------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": dmzj=comic_dmzj() dmzj.main() <file_sep>/MMBAO/筛选无效url地址/筛选无效url-mmb.py #大概分为 #1.从excel中读取数据get_data_from_excel #2. 读取数据,组成lists #3. 遍历lists的数据,通过selenium进行页面数据获取 #4. 筛选返回的结果,暂定为3种情况,a.404页面<注意是页面,state=200,需要找xpath>, b.搜索结果为空的压面, c.正常的结果 #5. 将返回的结果存入数据表,供后续的筛检 import time import xlrd import pymysql from selenium import webdriver #从excel中获取url的列表数据 def get_data_from_excel(): data=xlrd.open_workbook(r"D:\BI\关键词筛选\百度关键词url.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 url_lists=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss url_lists.append(ss) return url_lists def insert_data(url,info,state): db = pymysql.connect("localhost", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into MMB_URL_FILTER(url,info,state)"\ "values('%s','%s','%s')"\ %(url,info,state) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() #将lst[i]的数据放入函数进行数据获取 def get_url_data(url): driver.get(url) #获取到页面后,有两个if需要进行筛选,或者是try,except try: error_404=driver.find_element_by_xpath("//div[@class='erbg']/div[@class='ercont']/img") err_msg=error_404.get_attribute('alt') print(err_msg) insert_data(url,err_msg,0) except: try: error_null=driver.find_element_by_xpath("//div[@class='all clearfix pb30']/div[@class='w1']/div[@class='s1']") error_null=error_null.text.split("\n") err_msg=error_null[0] print(error_null[0]) insert_data(url, err_msg, 0) except: try: error_o=driver.find_element_by_xpath("//div[@class='good_list clearfix']/div/span").text if error_o=="没有您搜索的商品哦,重新搜索下吧~": print(error_o) insert_data(url, "", 2) else: print("url正常") insert_data(url, "", 1) except: print("url正常") insert_data(url, "", 1) #print(driver.page_source) if __name__=="__main__": driver=webdriver.PhantomJS() url_lists=get_data_from_excel() for i in range(len(url_lists)): url_list=str(url_lists[i]).replace("['","").replace("']","") print("当前url->"+url_list) get_url_data(url_list) print("####################################") <file_sep>/地址拆分/热点图制作.py import pymysql import time from chinese_province_city_area_mapper.transformer import CPCATransformer from chinese_province_city_area_mapper import drawers def find_data_from_address(): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,address from address_data_jd" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_data(table_id,provience,city,district): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update address_data_jd set providence='%s',city='%s',district='%s' where table_id='%s' " %(provience,city,district,table_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #将address保存到数据表,使用省进行轰炸,把结果更新到数据表,然后再用市轰炸 #取出所有地址 location_str = [] data=find_data_from_address() cpca = CPCATransformer() for i in range (len(data)): table_id=data[i][0] address=data[i][1] location_str.append(address) df,is_multiple = cpca.transform(location_str) # df为上一段代码输出的df drawers.draw_locations(df, "df.html") <file_sep>/untitled/Selenium/众业达/众业达2.0/zydmall-V2.0.py #首先, 数据获取的方式,通过商品详情的url直接跳转到详情,获取其中的相关内容 #http://www.zydmall.com/detail/product_14321.html #数据源分为4块 #1. 类目,包括一级二级三级(四级)类目 #2. 商品信息,价格,名称等 #3. img_url,发现有些商品的图片N多,多疑如果单纯添加字段,很容易崩掉,所以要另起新表 #4. 属性名称/属性值,因为不同类型商品的属性count不同,所以名称和属性值分开存放 from selenium import webdriver import time #获取类目名称 def get_category(product_id,prt_name): cate_list=driver.find_elements_by_xpath("//div[@class='page_posit']/a") cate_1=cate_list[1].text cate_2=cate_list[2].text cate_3 = cate_list[3].text print("#"+str(len(cate_list)-1)+"层类目:"+cate_1+"//"+cate_2+"//"+cate_3) insert_category(product_id,prt_name,cate_1,cate_2,cate_3) def insert_category(product_id,prt_name,cate_1,cate_2,cate_3): pass #获取商品主要信息,如价格,品牌等 def get_prt_info(product_id, prt_name): prt_model=driver.find_element_by_xpath("//div[@class='pro_desc clearfix mt20']/p[@class='wp100'][1]/span").text prt_order_id=driver.find_element_by_xpath("//div[@class='pro_desc clearfix mt20']/p[@class='wp100'][2]/span").text print("产品型号:"+prt_model+",订货号:"+prt_order_id) discount_price=driver.find_element_by_css_selector(".f30.ceb6161.fw.t-count").text print("折扣价"+discount_price) face_price = driver.find_element_by_css_selector(".f30.ceb6161.fw.t-count").text print("面价" + face_price) brand_name=driver.find_element_by_xpath("//p[@class='row2']/span[@class='mr10']/a").text print("品牌:" + brand_name) series=driver.find_element_by_xpath("//div[@class='pro_price clearfix']/p[4]/span").text print("系列:" + series) insert_prt_info(product_id, prt_name, prt_model, prt_order_id, discount_price,face_price,brand_name,series) def insert_prt_info(product_id, prt_name, prt_model, prt_order_id, discount_price,face_price,brand_name,series): pass #img_url获取 def get_img_info(): img_path=driver.find_elements_by_xpath("//ul[@id='thumblist']/li/a/img") print("共"+str(len(img_path))+"张图片") for i in range (len(img_path)): img_url_big=img_path[i].get_attribute("big") print(img_url_big) img_num=str(i+1) img_name=img_url_big[5:100]####################################################### original_url=img_url_big insert_img_info(product_id, prt_name,img_num,img_name,img_path,original_url) def insert_img_info(product_id, prt_name,img_num,img_name,img_path,original_url): pass #获取属性名称,属性值 def get_attributes(): #获取属性名称 attr_name_list=driver.find_elements_by_xpath("//div[@class='pro_desc clearfix']/p/b") print("共"+str(len(attr_name_list))+"条属性") for i in range (len(attr_name_list)): attr_name_t=attr_name_list[i].text attr_name=attr_name_t.replace(":","") print("属性名称:"+attr_name) #获取属性值 attr_value_list = driver.find_elements_by_xpath("//div[@class='pro_desc clearfix']/p/span") #print(len(attr_value_list)) for j in range(len(attr_value_list)): attr_value_t = attr_value_list[j].text attr_value = attr_value_t.replace(":", "") print("属性值:"+attr_value) if __name__=="__main__": driver = webdriver.Firefox() #driver.set_page_load_timeout(2) for i in range (14325,90000): id=i product_id="product_"+str(id) while True: try: driver.get("http://www.zydmall.com/detail/"+product_id+".html") print(">>"+product_id+"页面加载完成<<") break except: #print("商品未找到") pass try: prt_name = driver.find_element_by_css_selector(".c333.fw.f20.h20").text print("商品名称:"+prt_name) except: print("商品不存在或者已经下架") print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") continue #获取类目 get_category(product_id,prt_name) #time.sleep(0.5) #获取商品主要信息 get_prt_info(product_id, prt_name) #time.sleep(0.5) #获取图片信息 get_img_info(product_id, prt_name) #获取属性属性值 get_attributes(product_id, prt_name) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") #time.sleep(2) <file_sep>/untitled/Requests/MMBAO-DELIXI数据关联.py import pymysql import time def get_cnt(): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select count(table_id) as cnt from mmbao_data_delixi where status=0" try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) cnt=str(cnt).replace("((", "").replace(",),)", "") return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def get_data(): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_title from mmbao_data_delixi where status=0 limit 1" try: execute = cursor.execute(sql) prt_title = cursor.fetchmany(execute) prt_title=str(prt_title).replace("(('", "").replace("',),)", "") return prt_title except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def find_data(prt_title): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select prt_name from tmp_prt where prt_name like '%"+prt_title+"%' " try: execute = cursor.execute(sql) prt_name = cursor.fetchmany(execute) return prt_name except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_data(prt_title,state): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update mmbao_data_delixi set status='"+str(state)+"' where prt_title='"+prt_title+"' and status=0" try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def insert_fliter_data(prt_title,prt_name): db = pymysql.connect("localhost", "root", "123456", "de-ele", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into tmp_name_link (prt_title,prt_name)values('%s','%s')" %(prt_title,prt_name) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() if __name__=="__main__": cnt=get_cnt() print(cnt) for i in range(int(cnt)): prt_title=get_data() print("prt_title",prt_title) prt_name=find_data(prt_title) print("prt_name",prt_name) print(len(prt_name)) if len(prt_name)==0: state=4 else: state=1 for x in range(len(prt_name)): name=str(prt_name[x]).replace("('","").replace("',)","") print(prt_name[x][0]) insert_fliter_data(prt_title,prt_name[x][0]) update_data(prt_title,state) <file_sep>/企查查/数据查询-企查查V1.py import requests from selenium import webdriver import time import random #http://www.qichacha.com/search?key=%E8%AE%BE%E8%AE%A1%E9%99%A2 def s(a,b): x=random.randint(a,b) time.sleep(x) if __name__=="__main__": url="http://www.qichacha.com/user_login" browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) time.sleep(20) keywords="水电" driver.find_element_by_id('searchkey').send_keys(keywords) driver.find_element_by_id('V3_Search_bt').click() s(5,7) #http://www.qichacha.com/search?key=%E6%88%BF%E5%9C%B0%E4%BA%A7 # #sortField:0 # &p:2& <file_sep>/untitled/Selenium/MMBAO/买卖宝价格审核筛选脚本/买卖宝价格审核筛选脚本.py #1. 将后台筛选出的数据先放到数据表中 #2. 执行脚本,脚本输入:list,包含型号和规格的数组。输出:insert into new_table select....where type=@type and 规格=@规格 import xlrd import pymysql #用于获取excel中的两列,型号+规格 def print_xls(): data=xlrd.open_workbook(r"D:\BI\买卖宝\type and format.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 lists=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss lists.append(ss) return lists def get_data(type,format): db = pymysql.connect("192.168.180.159", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="INSERT INTO MMB_PRT_INFO_FILTER(TYPE,FORMAT,PRT_INFO_ID,PRT_ID,PRT_NAME,SHOP_ID,COMPANY_NAME,ATTRIBUTE_NAME,ATTRIBUTE,MODULE,SALE_PRICE,PRICE,RATE,CHANNEL,CAT_1,CAT_2,CAT_3)"\ " select '"+type+"','"+format+"',ID,PRT_ID,PRT_NAME,SHOP_ID,COMPANY_NAME,ATTRIBUTE_NAME,ATTRIBUTE,MODULE,SALE_PRICE,PRICE,RATE,CHANNEL,CAT_1,CAT_2,CAT_3 from MMB_PRT_INFO"\ " WHERE PRT_NAME LIKE '%"+str(type+format)+"%'" #print(sql) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() if __name__=="__main__": #从excel中获取数据,存入list,返回值list lists=print_xls() #print(lists) #根据如参筛选数据 for i in range(len(lists)): tmp_list=lists[i] tmp_list=str(tmp_list).split(",") type=tmp_list[0].replace("[","").replace("'","").replace(" ","") format = tmp_list[1].replace("]", "").replace("'", "").replace(" ","") #print(type+" "+format) get_data(type,format)<file_sep>/TMALL/罗格朗/legrand-获取天猫列表数据.py import pymysql from selenium import webdriver import time from bs4 import BeautifulSoup def get_prt_lists(): db = pymysql.connect("localhost", "root", "123456", "legrand", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,url from legrand_tmall_series_info where status=0 " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_html(prt_id,prt_url): driver.get(prt_url) #等待页面相应完成 html=driver.page_source time.sleep(5) return html def find_useful_info(html): soup=BeautifulSoup(html,'html.parser') data=soup.find_all('div',attrs={'class':'left1900'})[6] print(data) hrefs=data.find_all('area') print(len(hrefs)) for i in range (len(hrefs)): url=hrefs[i].get('href') time.sleep(0.5) print(url) status=1 return status if __name__=="__main__": #从数据表获取数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() data = get_prt_lists() for i in range(len(data)): # status=1 prt_id = data[i][0] prt_url = data[i][1] print(prt_id, prt_url) # 打开url,对数据进行一系列的分析抓取 html = get_html(prt_id, prt_url) # 把html的内容通过bs4进行检查 status = find_useful_info(html) time.sleep(100) # 处理完成后更新状态 <file_sep>/untitled/Selenium/工品汇/伊顿电气-20170831/图片筛选-给予美工.py import os import urllib.request import pymysql import sys import shutil #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath #保存图片 def getAndSaveImg(product_id,img_url, img_name): if (len(img_url) != 0): fileName = img_name file_path=u"D:\\BI\\Upload\\IMG\\"+product_id try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) except: print("这图我没法下载") def get_prt_data(): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_id,img_name,original_url from img_fliter where status=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() #复制图片 def copy_Img(prt_id,img_name): #暂时不加异常捕捉机制,试运行 src="D:\\BI\\Upload\\IMG\\"+prt_id+"\\"+img_name dst="D:\\BI\\Modify\\IMG\\"+prt_id+"\\"+img_name print("waiting for "+src+" =>=>=>=>=>=> "+dst) file_path = u"D:\\BI\\Modify\\IMG\\" + prt_id createFileWithFileName(file_path, img_name) shutil.copyfile(src,dst) print("复制成功") def update_state(prt_id,url,status): db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="update img_fliter set status='%d' where prt_id='%s' and original_url='%s'" %(status,prt_id,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": for i in range (232): data=get_prt_data() prt_id=data[0][0] img_name=data[0][1] url=data[0][2] print(prt_id,img_name,url) copy_Img(prt_id,img_name) status=1 update_state(prt_id,url,status)<file_sep>/untitled/Requests/2VEX网站登录.py import requests from bs4 import BeautifulSoup url="http://www.v2ex.com/signin" UA="Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.13 Safari/537.36" header = { "User-Agent" : UA, "Referer": "http://www.v2ex.com/signin" } v2ex_session = requests.Session() f = v2ex_session.get(url, headers=header) soup = BeautifulSoup(f.content, "html.parser") uid=soup.find('input',attrs={'type':'text','class':'sl'}) userid=uid.get('name') print(userid) pwd=soup.find('input',attrs={'type':'<PASSWORD>','class':'sl'}) password=<PASSWORD>('<PASSWORD>') print(password) once = soup.find('input', {'name': 'once'})['value'] print(once) postData = {userid: 'mlg2434s', password: '<PASSWORD>', 'once': once, 'next': '/' } v2ex_session.post(url, data=postData, headers=header) f = v2ex_session.get('http://www.v2ex.com/settings', headers=header) print(f.content.decode()) #根据html的对比,发现登录成功啦<file_sep>/漫画大业/动漫之家/sojson.js解析.py import pymysql import time import pyperclip import logging local_time=time.strftime("%Y-%m-%d %H%M",time.localtime(time.time())) filename = str.format('./logs/dmzj_sojson_log_%s.txt'%local_time) logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') #,filename=filename logger=logging.getLogger(__name__) from selenium import webdriver class sojson(): def main(self): # 从数据表获取数据 sojson_url="https://www.sojson.com/jsjiemi.html" browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(sojson_url) time.sleep(1) scripts_data=self.scripts_data() for i in range (len(scripts_data)): table_id=scripts_data[i][0] original_script=scripts_data[i][1] #logger.info(original_script) original_script=original_script.replace("@","'").replace("#","/").replace("&","\\").replace("$",'"') logger.info(original_script) time.sleep(5) driver.find_element_by_id('source').clear() time.sleep(5) driver.find_element_by_id('source').send_keys(original_script) time.sleep(5) driver.find_element_by_xpath("//div[@class='layui-row pt5']/button[@exe='decode']").click() time.sleep(30) driver.find_elements_by_xpath("//button[@class='layui-btn layui-btn-primary']")[0].click() time.sleep(2) script = pyperclip.paste() logger.info(script) try: driver.find_elements_by_xpath("//li[@lay-id='copyFile']")[0].click() time.sleep(2) transformed_scripts=script.split("[")[1].split("]")[0] logger.info(transformed_scripts) status=1 except Exception as e: logger.info(e) transformed_scripts="" status = 0 self.update_transformed_scripts(table_id,transformed_scripts,status) def scripts_data(self): db = pymysql.connect("localhost", "root", "123456", "comic") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select table_id,original_img_scripts from comic_original_scripts where status=0" logger.info(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() logger.info('------scripts_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def update_transformed_scripts(self,table_id,transformed_scripts,status): db = pymysql.connect("localhost", "root", "123456", "comic") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update comic_original_scripts set transformed_scripts='%s',status='%d' where table_id='%s' " %(transformed_scripts,status,table_id) logger.info(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('------update_transformed_scripts---------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": sojson=sojson() sojson.main() <file_sep>/SIMON商城/图片下载.py import pymysql import os import urllib.request def get_prt_imgs_from_table(): db = pymysql.connect("localhost", "root", "123456", "simon_shop") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select table_id,prt_id,img_name,img_path from simon_prt_imgs " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def getAndSaveImg(product_id,img_url, img_name,img_type): if (len(img_url) != 0): fileName = img_name file_path=u"D:\\BI\\SIMON\\upload\\prt\\"+img_type+"\\"+prt_id try: urllib.request.urlretrieve(img_url, createFileWithFileName(file_path, fileName)) status=1 except: print("这图我没法下载",img_url) status=2 #保存图片 def createFileWithFileName(localPathParam,fileName): isExists = os.path.exists(localPathParam) if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(localPathParam) print(localPathParam + ' 创建成功') totalPath=localPathParam+'\\'+fileName if not os.path.exists(totalPath): file=open(totalPath,'a+') file.close() return totalPath if __name__=="__main__": #从数据库获取整体的数据 data=get_prt_imgs_from_table() for i in range(len(data)): #print(data[i]) table_id=data[i][0] prt_id=data[i][1] img_name=data[i][2] original_url=data[i][3] img_type="spu_img" #print(original_url[0:2]) try: if original_url[0:2]=="//": original_url="https:"+original_url #print(original_url) #检查图片名称,如果是gif格式的,直接修改状态跳过 #print(img_name.split(".")[1]) #img_name = prt_id + "_" + img_name getAndSaveImg(prt_id, original_url, img_name, img_type) #img_path = "/upload/prt/" + img_type + "/" + img_name # print(img_path) #update_status(table_id, status, img_path) except IndexError as e: print(e) status = 3 # status=3,gif图片,跳过下载 #img_path = "" #update_status(table_id, status, img_path) <file_sep>/untitled/Selenium/抓取dq123厂家列表.py import time import json from selenium import webdriver import xlsxwriter def save_excel(fin_result1): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'D:\BI\dq123厂家及类目获取\test1.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result1)): tmp.write(i, 1, fin_result1[i]) if __name__=="__main__": driver = webdriver.Firefox() driver.get('http://www.dq123.com/price/index.php') time.sleep(5) cate=driver.find_elements_by_xpath("//li[@class='level1']/a") for i in range(len(cate)): list=cate[i].get_attribute('title') print(list) save_excel(list) <file_sep>/待自动化运行脚本/zydmall_数据监控/zydmall面价获取-合并版本.py import datetime import hashlib import requests from multiprocessing import Pool import time from bs4 import BeautifulSoup import pymysql def get_brand_name(): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select brand_name from brand_list group by brand_name" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_brand_info(brand_name): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select brand_name,page_num,total_num,md5,control_date from brand_list where brand_name='%s' order by control_date" %brand_name try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_d_value(brand_name,d_value,control_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update brand_list set d_value='%s' where brand_name='%s' and control_date='%s' " % (d_value,brand_name,control_date) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() class spu_detail(): def get_pid(self,url, good_id): s = requests.get(url) content = s.content.decode('utf-8') # print(content) # 根据分析ajax请求,需要两个参数,一个goods_id,一个pid # goods_id直接可以从url中获取,pid则需要正则分析源码 soup = BeautifulSoup(content, 'html.parser') time = 1 try: pid = soup.find('input', attrs={'id': 'J-basketNum'}).get('data-id') except AttributeError as e: time += 1 print(e) if time > 3: exit() pid = '' else: return self.get_pid(url, good_id) return pid def get_json_data(self,url): s = requests.get(url) content = s.content.decode('utf-8') # print(content) # full_content="<html><head></head><body><table>"+content+"</table></body></html>" content = content.replace("<div>", "").replace("</div>", "") # print(content) return content def insert_prt_data(self,prt_id, good_id, po_number, prt_url, prt_type, face_price, discount_price, weight, unit,creation_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_data (prt_id,good_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit,creation_date)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % ( prt_id, good_id, po_number, prt_url, prt_type, face_price, discount_price, weight, unit, creation_date) # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_prt_data-------Error------Message--------:' + str(err)) cursor.close() db.close() def get_content(self,html, good_id, num): # 里面分为两块,一块是图片的获取,另一块是整个content的获取,包括修改图片路径 # 1.内容html数据 soup = BeautifulSoup(html, 'html.parser') original_content = soup.find('div', attrs={'class': 'tab_contain'}) # 还需要replace掉所有的图片路径 imgs = original_content.find_all('img') print("当前详情内容里面一共有%s张图片" % str(len(imgs))) if len(imgs) == 0: self.update_good_id_status(good_id, 2) # num=0 for img in imgs: num += 1 # 图片的属性,需要名称,url img_title = img.get('title') if img_title == None: img_title = img.get('alt') if img_title == None: img_title = img.get('name') img_title = str(img_title).replace(".jpg", "") original_img_url = img.get('src') try: img_url = original_img_url[0:original_img_url.rindex("?")] except: img_url = original_img_url img_name = img_url[img_url.rindex('/') + 1:100] img_path = "/upload/prt/zyd/" + good_id + "/" + img_name # print(num, img_title, img_name, img_path, img_url) img_no = num img_type = "content" # 对content数据进行replace original_content = str(original_content).replace(original_img_url, img_path) # print(original_content) # print("++++++++++++++++") def get_good_id(self,solution): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select good_id from goods_lists_info where status=1 and is_executed=0 " + solution + " limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_good_id_status(self,good_id, status): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update goods_lists_info set is_executed='%d' where status=1 and good_id='%s' " % (status, good_id) # print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_good_cnt(self): db = pymysql.connect("localhost", "root", "<PASSWORD>", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select count(good_id) as cnt from goods_lists_info where status=1 and is_executed=0 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def main(self,id, creation_date): # 获取good_id if id == 0: solution = "order by table_id" else: solution = "order by table_id desc" goods_data = self.get_good_id(solution) good_id = goods_data[0][0] print("loading the %s ......" % good_id) # 尝试requests请求页面的返回结果 # good_id=str(3752) url = "https://www.zydmall.com/detail/good_" + good_id + ".html" pid = self.get_pid(url, good_id) print(pid) ajax_url = "https://www.zydmall.com/ashx/detail_products.ashx?goods_id=" + good_id + "&pid=" + pid print(ajax_url) content = self.get_json_data(ajax_url) # 分析html数据 soup = BeautifulSoup(content, 'html.parser') trs = soup.find_all('tr', attrs={'class': 'pro_list'}) print("共%s条SKU数据" % str(len(trs))) for tr in trs: # print(tr) # tr=str(tr).replace("<div>","").replace("</div>","") tds = tr.find_all('td') po_number = tds[0].find('a').text prt_url = tds[0].find('a').get('href') prt_id = prt_url.split('/')[-1].split('.')[0].split('_')[-1] prt_type = tds[1].find('p').text face_price = tds[2].text discount_price = tds[3].text weight = tds[7].text unit = tds[8].text # print(prt_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit) # ---------------------保存商品基础属性---------------------------------------------- self.insert_prt_data(prt_id, good_id, po_number, prt_url, prt_type, face_price, discount_price, weight, unit, creation_date) self.update_good_id_status(good_id, 1) print("------------------------------ ") def update_prt_data_status(self): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_data set status=0 " try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------update_prt_data_status-------Error------Message--------:' + str(err)) cursor.close() db.close() def get_url_md5(self,content): m2 = hashlib.md5() m2.update(content.encode('gbk')) md5 = m2.hexdigest() print(md5) return md5 def get_current_date(self): now = datetime.datetime.now() md = str(now.year) + "-" + str(now.month) + "-" + str(now.day) + " " + str(now.hour) + ":" + str(now.minute) return md class brand_info(): def get_brand_info(self): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select brand_name,brand_url from brand_list where status=1 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def filed_history(self,table_name): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update "+table_name+" set status=0 " try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_current_date(self): now = datetime.datetime.now() md = str(now.year)+"-"+str(now.month)+"-"+str(now.day)+" "+str(now.hour)+":"+str(now.minute) return md def find_basic_list(self,ajax_url): #根据brand_url获取当前页面的html数据 content=self.get_content(ajax_url) soup = BeautifulSoup(content, 'html.parser') page_value=soup.find('input',attrs={'class':'action-pagedata'}).get('value') page_total=page_value.split('pagetotal:')[-1].split('}')[0] total=page_value.split('{total:')[-1].split(',')[0] print("total:%s,page_total:%s"%(total,page_total)) return content,total,page_total def find_list_data(self,ajax_url,current_date): content=self.get_content(ajax_url) soup = BeautifulSoup(content, 'html.parser') items = soup.find_all('div', attrs={'class': 'item'}) print("current page have %s records" % (str(len(items)))) for i in range(len(items)): spu_title = items[i].find('a', attrs={'class': 'title'}).text spu_href = items[i].find('a', attrs={'class': 'title'}).get('href') spu_id = spu_href.split("_")[-1].split(".")[0] spu_price = items[i].find('span').text spu_cnt = items[i].find('i', attrs={'class': 'fl'}).text spu_brand = items[i].find('i', attrs={'class': 'fr'}).text list_img = items[i].find('a', attrs={'class': 'pic'}).find('img') original_pic = list_img.get('src').replace(" ", "") # 图片名称 pic_name = original_pic[original_pic.rindex('/') + 1:100] # 图片原始url original_pic_url = original_pic # 更新后的图片路径 self.insert_goods_lists(spu_id, spu_href, original_pic_url, pic_name, "", spu_title, spu_price, spu_cnt, spu_brand,current_date) def insert_goods_lists(self,good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand,current_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into goods_lists_info(good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand,creation_date)" \ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (good_id,good_url,original_pic_url,pic_name,pic_path,title,good_price,cnt,brand,current_date) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def get_content(self,url): s = requests.get(url, headers=headers) content = s.content.decode('utf=8') #print(content) return content def insert_current_brand_data(self,brand_name,brand_url,page_num,total_num,status,md5,control_date): db = pymysql.connect("localhost", "root", "123456", "zydmall_control") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into brand_list(brand_name,brand_url,page_num,total_num,status,md5,control_date)" \ "values('%s','%s','%d','%d','%d','%s','%s')" \ % (brand_name,brand_url,int(page_num),int(total_num),status,md5,control_date) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def get_url_md5(self,content): m2 = hashlib.md5() m2.update(content.encode('gbk')) md5=m2.hexdigest() print(md5) return md5 if __name__=="__main__": brand=brand_info() brand_data=brand.get_brand_info() #取出brand_data后,将数据表的数据置为历史,状态变为0,然后重新插入一组数据 brand.filed_history('brand_list') brand.filed_history('goods_lists_info') #循环插入新的待处理brand_list for i in range (len(brand_data)): brand_name=brand_data[i][0] brand_url=brand_data[i][1] #在以上的两个字段中,还需要其他的,所以还是一次性处理后再insert headers = { "Host": "www.zydmall.com", "Accept": "text/html, */*; q=0.01", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer": brand_url, "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" } #获取ajax——url brand_id=brand_url.split("_")[-1].split(".")[0] print(brand_id) ajax_url="https://www.zydmall.com/ashx/brand_product_list.ashx?br="+str(brand_id) #page_num需要提前获取 #page_num,total_num, content,total,page_total=brand.find_basic_list(ajax_url) basic_ajax = ajax_url #current_date current_date=brand.get_current_date() for page in range (int(page_total)): current_page=page+1 if current_page==1: pass else: ajax_url=basic_ajax+"&page="+str(current_page) print(ajax_url) brand.find_list_data(ajax_url,current_date) #md5 md5=brand.get_url_md5(content) #o代表历史记录,1代表新增的有效数据 status=1 brand.insert_current_brand_data(brand_name,brand_url,page_total,total,status,md5,current_date) #PART2 brand_names=get_brand_name() for ii in range (len(brand_names)): brand_name=brand_names[ii][0] brand_info=get_brand_info(brand_name) #print(brand_info) original_total_num=brand_info[0][2] for xx in range (len(brand_info)): page_num=brand_info[xx][1] total_num = brand_info[xx][2] control_date=brand_info[xx][4] d_value=int(total_num)-int(original_total_num) print(d_value) update_d_value(brand_name,d_value,control_date) #PART3 spu_detail=spu_detail() creation_date=spu_detail.get_current_date() is_only_price=1 spu_detail.update_prt_data_status() cnt_data=spu_detail.get_good_cnt() cnt=cnt_data[0][0] for_times=round(int(cnt)/2,0)+1 for xxx in range (int(for_times)): start = time.time() p = Pool() for iii in range(2): p.apply_async(func=spu_detail.main, args=(iii,creation_date)) p.close() p.join() end = time.time() <file_sep>/API调用/练习/历史上的今天.py #python3.5 from urllib import request, parse import json import datetime now=datetime.datetime.now() today_is='today is '+str(now) print(today_is) md=now.strftime('%m')+now.strftime('%d') showapi_appid="61534" #替换此值 showapi_sign="feb4bf41ec<KEY>" #替换此值 url="http://route.showapi.com/119-42" send_data = parse.urlencode([ ('showapi_appid', showapi_appid) ,('showapi_sign', showapi_sign) ,('date', md) ]) req = request.Request(url) try: response = request.urlopen(req, data=send_data.encode('utf-8'), timeout = 10) # 10秒超时反馈 except Exception as e: print(e) result = response.read().decode('utf-8') result_json = json.loads(result) #print ('result_json data is:', result_json) #对result_json的结果进行筛选 txt_path = "C:/Users/CC-SERVER/Desktop/本日大事件.txt" with open(txt_path, "w") as f: f.write(today_is) f.write('\n') year_items=result_json['showapi_res_body']['list'] for i in range (len(year_items)): year=year_items[i]['year'] title=year_items[i]['title'] print(year,title) with open(txt_path, "a") as f: f.write(year) f.write(" ") f.write(title) f.write('\n') <file_sep>/untitled/mysql数据读取.py import pymysql # 库名:python;表名:students conn = pymysql.connect("192.168.180.147", "root", "<PASSWORD>", "test01") cursor = conn.cursor() count = cursor.execute('select mail from students') mail_list = [] # 获取所有结果 results = cursor.fetchall() result = list(results) for r in result: # print 'mail:%s ' % r mail_list.append(('<span style="color:#ff0000;">%s' )) print(mail_list) # 游标归零,默认mode='relative' cursor.scroll(0, mode='absolute') count = cursor.execute('select name from students') name_list = [] results = cursor.fetchall() result = list(results) for r in result: # print '%s' % r # print type('%s' % r) name_list.append(('%s' % r)) # for i in range(6): # print name_list[i] conn.close()<file_sep>/dianlan.cn/获取详情内的重量信息.py import pymysql import time from selenium import webdriver def get_data(): db = pymysql.connect("localhost", "root", "123456", "dianlan_cn") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select table_id,detail_href from detail_lists where status=0"# try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_weight(table_id,guige,baodai_guige,houdu,weight): db = pymysql.connect("localhost", "root", "123456", "dianlan_cn") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into weight_info (link_id,guige,baodai_guige,houdu,weight) values('%s','%s','%s','%s','%s') "%(table_id,guige,baodai_guige,houdu,weight) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(table_id): db = pymysql.connect("localhost", "root", "123456", "dianlan_cn") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update detail_lists set status=1 where table_id='%s' " %table_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() data=get_data() for i in range (len(data)): table_id=data[i][0] detail_url=data[i][1] driver.get(detail_url) time.sleep(3) tab_controls=driver.find_elements_by_xpath("//div[@class='tab-item-menu']/ul[@class='tab-menu']/li") for x in range (len(tab_controls)): tmp_tab_name=tab_controls[x].text if "结构尺寸" in tmp_tab_name: driver.find_elements_by_xpath("//div[@class='tab-item-menu']/ul[@class='tab-menu']/li")[x].click() time.sleep(5) trs=driver.find_elements_by_xpath("//table[@id='tableTitleIda_T0042']/tbody/tr") print("current pages have %s links" % (str(len(trs)))) for y in range(1,len(trs)): guige_path="//table[@id='tableTitleIda_T0042']/tbody/tr["+str(y+1)+"]/td" #tmp=driver.find_elements_by_xpath("//table[@id='tableTitleIda_T0042']/tbody/tr[1]/th") #print(len(tmp)) guige=driver.find_elements_by_xpath(guige_path)[1] baodai_guige=driver.find_elements_by_xpath(guige_path)[5] houdu = driver.find_elements_by_xpath(guige_path)[6] weight = driver.find_elements_by_xpath(guige_path)[-1] print(guige.text,baodai_guige.text,houdu.text,weight.text) insert_weight(table_id,guige.text,baodai_guige.text,houdu.text,weight.text) update_status(table_id) <file_sep>/对MMBAO搜索词Jieba分词/将分好的词挨个进行引导分类.py #对所有的搜索词,通过分好的词汇,进行分类 import pymysql import time def get_keyword(): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select keyword,module from channel_keyword where status=0 order by table_id limit 1 " try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def get_result(keyword): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select table_id,keyword,source from search_keywords_data where keyword like '%"+keyword+"%' and channel is null" try: execute=cursor.execute(sql) data=cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_channel(keyword,module): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="update search_keywords_data set main_key='"+keyword+"',channel='"+module+"' where keyword like '%"+keyword+"%'" try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status(keyword): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="update channel_keyword set status=1 where keyword = '%s'"%(keyword) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() if __name__=="__main__": for i in range (688): try: data=get_keyword() keyword=data[0][0] module=data[0][1] print("keyword:%s module:%s"%(keyword,module)) #将关键词放到另一张进行检索,得出结果集 data=get_result(keyword) update_channel(keyword,module) try: print("共%s条查询结果"%(str(len(data)))) for i in range(len(data)): table_id = data[i][0] keyword = data[i][1] source = data[i][2] #print(table_id, "/", keyword, "/", source) except: print(data) update_status(keyword) time.sleep(1) except IndexError: print("列表索引结束")<file_sep>/JD后台/shop后台关联店内类目/商家后台-商品关系管理.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() #option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 option.add_argument('--user-data-dir=C:\\Users\\CC-SERVER\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) driver.get('https://ware.shop.jd.com/wareClassify/wareClassify_getWareByCondition.action') self.s(3, 4) data=self.get_lists() for i in range (len(data)): sku_id = data[i][0] print(sku_id) #sku_id="5915121" ''' driver.find_element_by_id('wareId').clear() driver.find_element_by_id('wareId').send_keys(sku_id) self.s(1,2) #点击查询 driver.find_element_by_id("search").click() self.s(2,3) check_id="selectWare_"+sku_id driver.find_element_by_id(check_id).click() driver.find_element_by_id("top_bt_category_batch").click() self.s(1,1) #print(driver.page_source) #通过id,勾选对应的数据 ''' used_data = self.find_used_cate(sku_id) config_post_url="https://ware.shop.jd.com/wareClassify/wareClassify_updateShopCategory.action?updateWareIds=%s,&shopCategoryIds="%sku_id for x in range (len(used_data)): cat_id=used_data[x][3] print(cat_id) if x==len(used_data)-1: config_post_url = config_post_url + cat_id else: config_post_url = config_post_url + cat_id + "," print(config_post_url) driver.get(config_post_url) #driver.find_element_by_id(cat_id).click() self.s(1,1) #调用一下回车键,因为弹出的确认窗口获取不到 status=1 self.update_status(sku_id,status) def get_lists(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select sku_id from 商品关系管理 group by sku_id " #print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def find_used_cate(self,sku_id): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select a.sku_id,a.sku_name,a.category_name,b.cat_id from 商品关系管理 a left join 商品关系字典表 b on a.category_name=b.cat_name and a.vc_shop=b.vc_shop where sku_id='%s' " %(sku_id) #print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('-------insert_to_img_zone--------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(self,sku_id,status): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update 商品关系管理 set status='%d' where sku_id='%s' " %(status,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.shop.jd.com/login/index.action" main.init(url) <file_sep>/找电缆EXCEL处理/处理已导入的模板数据.py # 打开一个excel import xlrd import os import time import pymysql import xlwt def find_data_from_table(where_solution): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,full_text,price from zhaodianlan_price_update "+where_solution print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_type_detail(excel_name,full_type_name): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select gb,structure,material,lev_zr,type from type_name_detail where excel_name='%s' and full_type_name='%s'" %(excel_name,full_type_name) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_status(id): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update zhaodianlan_price_update set status=1 where table_id='%s'" %id try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() # 从excel中获取url的列表数据 def get_data_from_excel(path): # excel_name=r"D:\BI\找电缆\2017年12月红本出厂价《产品价格目录》\1712出厂价/201712 架空线出厂价-国标.xls" print(path) excel_name=path[path.rindex("/")+1:1000] #print(excel_name) data=xlrd.open_workbook(path) #打开excel sheetName = data.sheet_names()[0] # print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[0] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] # print(sheetName) #上一条数据的型号 last_type="" wbk = xlwt.Workbook() sheet1 = wbk.add_sheet('sheet 1') sheet1.write(0, 0, "类目") sheet1.write(0, 1, "型号") sheet1.write(0, 2, "规格") sheet1.write(0, 3, "电压") sheet1.write(0, 4, "厂商") sheet1.write(0, 5, "品牌") sheet1.write(0, 6, "省") sheet1.write(0, 7, "市") sheet1.write(0, 8, "价格(元/单位)") sheet1.write(0, 9, "商品有效期") sheet1.write(0, 10, "是否上架") sheet1.write(0, 11, "交货期(天)") sheet1.write(0, 12, "权重值") sheet1.write(0, 13, "参与均价计算") sheet1.write(0, 14, "属性") sheet1.write(0, 15, "库存") sheet1.write(0, 16, "生产年份") new_path = "D:\BI\找电缆\已处理\\"+excel_name.replace("xlsx","xls") wbk.save(new_path) try: # 经过检验,数据的结构相同 # 类目、型号、规格、电压、价格 for i in range(1, nrows): ss = table.row_values(i) # 获取一行的所有值,每一列的值以列表项存在 # print(len(ss)) cate_name = ss[0] full_type_name = ss[1] specification = ss[2] voltage = ss[3] factory = ss[4] brand_name = ss[5] providence = ss[6] city = ss[7] price = ss[8] useful_date = ss[9] is_sale = ss[10] day = ss[11] average_calc = ss[12] attribute = ss[13] stock = ss[14] print(excel_name, full_type_name) # 通过这两个条件,从数据表中筛选出型号的拆分结果 data = find_type_detail(excel_name, full_type_name) if len(data) == 1: gb = data[0][0] structure = data[0][1] material = data[0][2] lev_zr = data[0][3] type = data[0][4] if specification.endswith('*1'): specification+=".0" print("specification",specification) print("细化型号内容:", "<", gb, "><", structure, "><", material, "><", lev_zr, "><", type, "><", specification, "><", voltage, "><", price, ">") else: print("error") break # 拿着细化的型号,以及其他属性,去数据表查找对应的12月份数据 # time.sleep(100) where_solution = "where full_text like '%" + type + "-%' and full_text like '%-" + specification + "%' and full_text like '%" + voltage + "%'" where_solution += " and full_text like '%" + gb + "%' and full_text like '%" + structure + "%' and full_text like '%" + material + "%' and full_text like '%" + lev_zr + "%'" data2 = find_data_from_table(where_solution) print("查询结果有%s条" % str(len(data2))) if len(data2) == 1: print("查询结果一条,属于正常范畴") id=data2[0][0] new_price = data2[0][2] print("new_price", new_price) update_status(id) elif len(data2) == 0: new_price="" else: print("选择序号,对应哪条结果") for j in range(len(data2)): id = data2[j][0] full_text = data2[j][1] price = data2[j][2] print(id, full_text, price) table_id = input("《针对返回结果,对相同型号,请输入想要添加的检索条件》\n") where_table_id = "where table_id=" + table_id data_with_table_id = find_data_from_table(where_table_id) new_price = data_with_table_id[0][2] print("new_price", new_price) update_status(table_id) #time.sleep(5) print("######################################") # time.sleep(100) # 将数据写到新的excel中 sheet1.write(i, 0, ss[0]) sheet1.write(i, 1, ss[1]) sheet1.write(i, 2, ss[2]) sheet1.write(i, 3, ss[3]) sheet1.write(i, 4, ss[4]) sheet1.write(i, 5, ss[5]) sheet1.write(i, 6, ss[6]) sheet1.write(i, 7, ss[7]) sheet1.write(i, 8, new_price) sheet1.write(i, 9, ss[9]) sheet1.write(i, 10, ss[10]) sheet1.write(i, 11, ss[11]) sheet1.write(i, 12, ss[12]) sheet1.write(i, 13, ss[13]) sheet1.write(i, 14, ss[14]) sheet1.write(i, 15, ss[15]) sheet1.write(i, 16, ss[16]) new_path = "D:\BI\找电缆\已处理\\" + excel_name.replace("xlsx", "xls") wbk.save(new_path) except IndexError as e: print(e) #读取所有文件夹中的xls文件 def read_xls(path, type2): #遍历路径文件夹 for file in os.walk(path): for each_list in file[2]: file_path=file[0]+"/"+each_list #os.walk()函数返回三个参数:路径,子文件夹,路径下的文件,利用字符串拼接file[0]和file[2]得到文件的路径 name.append(file_path) if __name__ == "__main__": xpath = r"D:\BI\找电缆\待处理" xtype = "xls" name = [] read_xls(xpath, xtype) print("%s个文件"%str(len(name))) for i in range (len(name)): excel_name = name[i] get_data_from_excel(excel_name) time.sleep(10) <file_sep>/MMBAO/根据SKU_ID和图片url拼接prt_desc.py import pymysql import xlwt def get_data_from_mysql(): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select b.spu_id from sku_img_link a left join spu_sku_link b on a.sku_id=b.sku_id group by b.spu_id" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('-------get_data_from_mysql--------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_imgs(spu_id): db = pymysql.connect("localhost", "root", "<PASSWORD>", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select b.spu_id,a.img_url from sku_img_link a left join spu_sku_link b on a.sku_id=b.sku_id where b.spu_id='%s' group by b.spu_id,a.img_url " %spu_id try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('-------get_data_from_mysql--------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": wbk = xlwt.Workbook() sheet1 = wbk.add_sheet('sheet 1') data=get_data_from_mysql() for i in range (len(data)): spu_id=data[i][0] spu_img_data=get_imgs(spu_id) desc_data= "<div><p>" for x in range (len(spu_img_data)): img_url=spu_img_data[x][1] #拼接prt_desc链接 desc_part2="<img src='"+img_url+"' style='width:600px'>" desc_data+=desc_part2 for y in range(len(spu_img_data)): if 'a01' in img_url: sku_first_img=img_url break desc_data+='</p></div>' print(desc_data) sheet1.write(i, 0, spu_id) sheet1.write(i, 1, desc_data) #sheet1.write(i,2,sku_first_img) #update_status(prt_id) wbk.save('html.xls') <file_sep>/untitled/Selenium/PhantomJS&Firefox/PhantomJS.py from untitled.Selenium import webdriver driver=webdriver.PhantomJS() driver.get("http://www.tianyancha.com/search?key=%<KEY>&checkFrom=searchBox") url=driver.find_elements_by_xpath("//div[@class='col-xs-10 search_repadding2 f18']/a") for i in range(len(url)): print(url[i].text) <file_sep>/untitled/Selenium/test2-fanye.py # -*- coding: utf-8 -*- import time from untitled.Selenium import webdriver if __name__ == "__main__": driver = webdriver.Firefox() #driver.maximize_window() driver.get('http://www.baidu.com') driver.implicitly_wait(5) driver.find_element_by_id('kw').send_keys('selenium') driver.find_element_by_id('su').click() page = driver.find_element_by_id('page') pages = page.find_elements_by_tag_name('a') js = 'document.documentElement.scrollTop=10000' total = str(len(pages)) print('total page is %s' %total) has_pre_page = False page_num = 0 for i in range (0,len(pages)): driver.find_element_by_xpath("//div[@id='page']/a[contains(text(),'下一页')]" ).click() # selenium的xpath用法,找到包含“下一页”的a标签去点击 time.sleep(2) # 睡2秒让网页加载完再去读它的html代码 <file_sep>/untitled/Selenium/test3.py #coding=utf-8 from untitled.Selenium import webdriver driver = webdriver.PhantomJS() driver.get("http://search.mmbao.com/0_0_0.html?enc=utf-8&model_a=BVR&spec_a=10/") print (driver.page_source) driver.quit()<file_sep>/JD后台/VC后台/正阳门-商品重新提交.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": option = webdriver.ChromeOptions() # option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 #option.add_argument( '--user-data-dir=C:\\Users\\coco.chen\\AppData\\Local\\Google\\Chrome\\User Data') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=option) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) prt_data=self.get_sku_id() for i in range (len(prt_data)): sku_id=prt_data[i][0] new_sku_name=prt_data[i][1] print(sku_id,new_sku_name) driver.find_element_by_id('wareId').clear() driver.find_element_by_id('wareId').send_keys(sku_id) self.s(1,2) driver.find_element_by_css_selector('.btn.btn-primary').click() self.s(2,3) nowhandle = driver.current_window_handle # 在这里得到当前窗口句柄 btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_wareId']/div/button[@class='btn btn-default dropdown-toggle']" driver.find_element_by_xpath(btn_down_path).click() self.s(1,1) driver.find_elements_by_xpath("//ul[@class='dropdown-menu']/li/a")[0].click() self.s(5, 6) # 需要获取新弹开的窗口 allhandles = driver.window_handles # 获取所有窗口句柄 for handle in allhandles: # 在所有窗口中查找弹出窗口 if handle != nowhandle: driver.close() driver.switch_to.window(handle) current_url = driver.current_url print(current_url) if "https://vcp.jd.com/sub_item/item/initItemListPage" in current_url: self.update_caigou_price(sku_id,'reviewing') else: driver.get(current_url) content = driver.page_source # print(content) self.s(3, 4) driver.find_element_by_id('cid3Submit').click() self.s(2, 4) driver.find_element_by_id('auditedSubmit').click() self.s(2, 4) yanse = "黑色" driver.find_elements_by_class_name("combo-arrow")[1].click() if yanse == "红色": yanse_xpath = "//div[@value='703187' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "黄色": yanse_xpath = "//div[@value='703188' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "蓝色": yanse_xpath = "//div[@value='703189' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "绿色": yanse_xpath = "//div[@value='703190' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "双色": yanse_xpath = "//div[@value='703193' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "黑色": yanse_xpath = "//div[@value='703192' ]" driver.find_element_by_xpath(yanse_xpath).click() elif yanse == "白色": yanse_xpath = "//div[@value='703191' ]" driver.find_element_by_xpath(yanse_xpath).click() driver.find_element_by_id('createApply').click() self.s(1, 2) driver.get('https://vcp.jd.com/sub_item/item/initItemListPage') self.s(3, 4) def get_sku_id(self): db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select sku_id,new_sku_name from sku_name_change where status is null " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_caigou_price(self,sku_id,state): db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update sku_name_change set status='%s' where sku_id ='%s'" %(state,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/untitled/Selenium/test7 from 4.py #coding=utf-8 import xlsxwriter from untitled.Selenium import webdriver def save_excel(fin_result, file_name): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\%s.xlsx' % file_name) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') row_num = len(fin_result) for i in range(0, row_num): #print('##############') fin_a=fin_result[i] #从50*2的二维数组中,遍历i后获取的每个一维数组 for j in range(0, len(fin_a)): fin_b = fin_result[i][j] #print(fin_b) for k in fin_b: #print(k) tmp.write(i, j, k) tmp.write(i, 0, fin_result[i][0]) #tmp.write(i,j,fin_a[j]) #for j in range (0,2): # tmp.write(i,j,fin_a[j]) def max_page(): x=1 driver = webdriver.PhantomJS() driver.get("http://www.vipmro.net/facePrice") link=driver.find_elements_by_link_text("iC60L MA") for i in range(0,len(link)): link[i].click() #print (driver.current_url) source=driver.page_source print(source) driver.quit() <file_sep>/企查查/查询公司信息-2018年7月12日.py import pymysql from selenium import webdriver from bs4 import BeautifulSoup def insert_company_data(company_name,leader,registered_capital,founding_date,phone,email,address,hangye): db = pymysql.connect("localhost", "root", "123456", "company_data") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into company_info_sxd (company_name,leader,registered_capital,founding_date,phone,email,address,hangye) values('%s','%s','%s','%s','%s','%s','%s','%s')" %(company_name,leader,registered_capital,founding_date,phone,email,address,hangye) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_company_name(): db = pymysql.connect("localhost", "root", "123456", "company_data") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select * from company_name where status=0" try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_status(table_id): db = pymysql.connect("localhost", "root", "123456", "company_data") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update company_name set status=1 where table_id='%s' and status=0" %(table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": browser = "Chrome" if browser == "Chrome": driver = webdriver.Chrome() else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() login_url='https://www.qichacha.com/user_login' driver.get(login_url) name = input("Go?") print(name) #完成登录 search_front_url = "https://www.qichacha.com/search?key=" company_data=get_company_name() for i in range (len(company_data)): table_id=company_data[i][0] search_name=company_data[i][1] #search_name="%E5%A4%A9%E6%B4%A5%E5%8D%8E%E5%85%B4%E9%87%91%E5%8A%9B%E7%94%B5%E5%8A%9B%E8%AE%BE%E5%A4%87%E5%AE%89%E8%A3%85%E8%82%A1%E4%BB%BD%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8" #search_name="天津华兴" search_url=search_front_url+search_name driver.get(search_url) #直接查找搜索结果中的数据 content=driver.page_source soup=BeautifulSoup(content,'html.parser') lists=soup.find_all('') try: lists_trs=soup.find('table',attrs={'class':'m_srchList'}).find('tbody').find_all('tr') state=1 except AttributeError as e: state=0 if state==1: print(len(lists_trs)) for x in range (len(lists_trs)): company_name = lists_trs[x].find('a', attrs={'class': 'ma_h1'}).text print(company_name) try: leader=lists_trs[x].find_all('a',attrs={'class':'text-primary'})[0].text except IndexError as e : leader=lists_trs[x].find_all('p',attrs={'class':'m-t-xs'})[0].text.replace(" ","").replace("\n","") print(leader) #original_data registered_capital="" founding_date="" phone="" email="" address="" hangye="" m_l_lists=lists_trs[x].find_all('span',attrs={'class':'m-l'}) for y in range (len(m_l_lists)): name=m_l_lists[y].text.replace(" ","").replace("\n","") if "注册资本" in name: registered_capital=name if "成立时间" in name: founding_date = name if "电话" in name: phone = name if "所属行业" in name: hangye = name m_t_xs_lists=lists_trs[x].find_all('p',attrs={'class':'m-t-xs'}) for z in range (len(m_t_xs_lists)): xs_name=m_t_xs_lists[z].text.replace(" ","").replace("\n","") if "邮箱" in xs_name: email=xs_name if "地址" in xs_name: address=xs_name leader.replace(registered_capital,"").replace(founding_date,"") email=email.replace(phone,"").replace("更多号码","") print(registered_capital,founding_date,phone,email,address) insert_company_data(company_name,leader,registered_capital,founding_date,phone,email,address,hangye) update_status(table_id) ''' lists_company_name=driver.find_elements_by_xpath("//tr/td[1]/a[@class='ma_h1']") print(len(lists_company_name)) for x in range (len(lists_company_name)): print(lists_company_name[x].text) lists_leader=driver.find_elements_by_xpath("//tr/td[1]/p[@class='m-t-xs'][0]/a[@class='text-primary']") print(len(lists_leader)) ''' <file_sep>/untitled/代理/test.py #代理使用 import urllib import urllib.request from urllib.request import urlopen proxy_handler=urllib.request.ProxyHandler({'http':'172.16.58.3'}) opener=urllib.request.build_opener(proxy_handler) urllib.request.install_opener(opener) page=urlopen('http://ip.chinaz.com/getip.aspx') print(page.read().decode('utf-8')) <file_sep>/MMBAO/搜索词产品数量打分/获取后台数据库的搜索结果集数量.py import cx_Oracle import xlrd import time import pymysql def get_data_from_excel(): data=xlrd.open_workbook(r"D:\BI\MMBAO搜索词分类\第一期-12月\搜索词评分表.xlsx") #打开excel sheetName = data.sheet_names()[1] table=data.sheets()[1] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 url_lists=[] print(sheetName) for i in range(1,nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss url_lists.append(ss) return url_lists def check_data_in_oracle(para1,para2,para3,para4): #将这些值带入到oracle数据表中查看 db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@192.168.127.12:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT COUNT(*) AS cnt FROM ("\ " SELECT sku_title||' '||a.po_number||' '||prt_title||' '||series||' '||lev1_cat_name||' '||lev2_cat_name||' '||lev3_cat_name||' '||d.brand_name_cn||' '||e.s_shop_name AS prt_info"\ " FROM mmbao2.t_prt_sku a"\ " LEFT JOIN mmbao2.t_prt_entity b"\ " ON a.prt_id=b.id"\ " LEFT JOIN mmbao2.v_prt_catgory_level3 c"\ " ON b.catgory_id=c.lev3_cat_id"\ " LEFT JOIN mmbao2.t_shop_brand d"\ " ON b.brand_id=d.id"\ " LEFT JOIN mmbao2.t_shop_supplier e"\ " ON b.shop_id=e.supplier_id"\ " WHERE b.is_delete=0 AND b.is_sale=1 AND b.is_use=1"\ " ) a"\ " WHERE "+para1+para2+para3+para4 # and create_date>to_date('%s','yy/MM/dd') # 因为还得分为新增和更新 #print(sql) #print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def update_status(table_id,cnt): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update search_keywords_content set oracle_count='%s' where table_id='%s'" %(cnt,table_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": data=get_data_from_excel() for i in range (len(data)): table_id=data[i][0] search_keywords=data[i][1] jieba1 = data[i][2] jieba2 = data[i][3] jieba3 = data[i][4] jieba4 = data[i][5] print(jieba1,jieba2,jieba3,jieba4) if jieba1!="": para1="upper(prt_info) like upper('%"+jieba1+"%') " else: para1=" " if jieba2!="": para2="and upper(prt_info) like upper('%"+jieba2+"%') " else: para2=" " if jieba3!="": para3="and upper(prt_info) like upper('%"+jieba3+"%') " else: para3=" " if jieba4!="": para4="and upper(prt_info) like upper('%"+jieba4+"%') " else: para4=" " data2=check_data_in_oracle(para1,para2,para3,para4) cnt=data2[0][0] print(cnt) update_status(table_id,cnt) time.sleep(0.1)<file_sep>/工品汇/伊顿电气-20170831/属性名称、属性值匹配.py import cx_Oracle as oracle import os os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' def oraclesql(cursor): fp = open(r'/home/oracle/scripts/tablespace.sql') fp_sql = fp.read() cursor.execute(fp_sql) data = cursor.fetchall() return data if __name__ == '__main__': ipaddr = "192.168.223.138" username = "system" password = "<PASSWORD>" oracle_port = "1521" oracle_service = "oracle.test" try: db = oracle.connect(username + "/" + password + "@" + ipaddr + ":" + oracle_port + "/" + oracle_service) # 将异常捕捉,然后e就是抛异常的具体内容 except Exception as e: print(e) else: cursor = db.cursor() data = oraclesql(cursor) for i in data: print(i) cursor.close() db.close()<file_sep>/OA_FEGROUP/test.py import base64 me = base64.b64encode("mink".encode(encoding='utf-8')) print(me)<file_sep>/地址拆分/地址拆分-2018年7月4日.py import pymysql import time from chinese_province_city_area_mapper.transformer import CPCATransformer from chinese_province_city_area_mapper import drawers def find_data_from_address(): db = pymysql.connect("localhost", "root", "123456", "qichacha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select company_name,address from company_info_qichacha where scope_of_operation like '%太阳能%' or scope_of_operation like '%二轮车%' " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_data(company_name,address,provience,city,district): db = pymysql.connect("localhost", "root", "123456", "qichacha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into address_link (company_name,address,provience,city,district) values('%s','%s','%s','%s','%s')" %(company_name,address,provience,city,district) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #将address保存到数据表,使用省进行轰炸,把结果更新到数据表,然后再用市轰炸 #取出所有地址 data=find_data_from_address() for i in range (len(data)): location_str = [] company_name=data[i][0] address=data[i][1] location_str.append(address) cpca = CPCATransformer() df,is_multiple = cpca.transform(location_str) # df为上一段代码输出的df drawers.draw_locations(df, "df.html") district=df.ix[0][0] city=df.ix[0][1] provience=df.ix[0][2] print(provience,city,district) update_data(company_name,address,provience,city,district) <file_sep>/untitled/Selenium/dq123/dq123数据获取-20170831/test.py from selenium import webdriver browser = webdriver.Firefox() # 打开浏览器 browser.set_page_load_timeout(10) #10秒 while True: try: browser.get('http://www.baidu.com') break except: pass<file_sep>/ZYDMALL/zydmall_德力西/型号匹配.py import pymysql import cx_Oracle def get_common_attr2(lev3_cat_id, attr_val_value): # db = cx_Oracle.connect('mmbao2_bi/<EMAIL>:21252/mmbao2b2c') db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@172.16.58.3:7018/mmbao2b2c') # print(db.version) cursor = db.cursor() sql = "SELECT attr_id,attr_name,attr_val_id,attr_val_value FROM mmbao2.v_prt_catgory_attr_val"\ " WHERE lev3_cat_id='%s' AND attr_val_value='%s'" %(lev3_cat_id,attr_val_value) # print(sql) cursor.execute(sql) data = cursor.fetchall() cursor.close() db.close() return data def get_data_from_sku_table(): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select a.SKU_ID,a.SKU标题,b.三级类目ID from insert_sku_table a"\ " left join insert_spu_table b on a.对应SPU_ID=b.spu_id where b.spu_id not like '2017%'" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_sku_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def insert_sale_attr_table(id,sku_id,attr_id,attr_name,attr_val_id,attr_value,order_num): db = pymysql.connect("localhost", "root", "<PASSWORD>", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into insert_sale_attr_table (id,对应SKU_ID,销售属性ID,销售属性名称,销售属性值ID,销售属性值,销售属性顺序_数字) " \ "values('%s','%s','%s','%s','%s','%s','%s')" % ( id, sku_id, attr_id, attr_name, attr_val_id, attr_value, order_num) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": data=get_data_from_sku_table() for i in range (len(data)): sku_id=data[i][0] sku_title=data[i][1] cate3_id=data[i][2] sku_type=sku_title[sku_title.rindex(";")+1:100] data2=get_common_attr2(cate3_id,sku_type) #print(sku_id, sku_type, cate3_id,str(len(data2))) id=sku_id+"0000" 销售属性ID=data2[0][0] 销售属性名称=data2[0][1] 销售属性值ID=data2[0][2] 销售属性值=data2[0][3] 销售属性顺序_数字="1" insert_sale_attr_table(id,sku_id,销售属性ID,销售属性名称,销售属性值ID,销售属性值,销售属性顺序_数字) print(str(i+1)) <file_sep>/API调用/练习/工商信息查询.py import urllib, sys from urllib import parse import urllib.request company_name="远东买卖宝网络科技有限公司" company_name=parse.quote(company_name) host = 'http://qianzhan1.market.alicloudapi.com' path = '/CommerceAccurate' method = 'GET' appcode = '34953821e8b943d39f160992c56d7f6e' querys = 'comName='+company_name bodys = {} url = host + path + '?' + querys request = urllib.request.Request(url) request.add_header('Authorization', 'APPCODE ' + appcode) response = urllib.request.urlopen(request) content = response.read().decode('utf-8') if (content): print(content)<file_sep>/待自动化运行脚本/tmall上显卡价格/获取tmall上显卡价格.py import pymysql import requests import re import json from selenium import webdriver def get_content(url): s = requests.get(url) content = s.content.decode('utf-8') print(content) regex = 'g_page_config = (.+)' items = re.findall(regex, content) items = items.pop().strip() items = items[0:-1] items = json.loads(items) #print(items) items = items['mods']['itemlist']['data']['auctions'] for item in items: if 'item_loc' in item: item_loc = item['item_loc'] else: item_loc = u" " if 'nick' in item: nick = item['nick'] else: nick = u" " if 'raw_title' in item: raw_title = item['raw_title'] else: raw_title = u" " if 'view_sales' in item: view_sales = item['view_sales'] else: view_sales = u" " if 'view_price' in item: view_price = item['view_price'] else: view_price = u" " if 'comment_url' in item: comment_url = item['comment_url'] else: comment_url = u" " comment_url = 'https:' + comment_url #print("{0}——{1}——{2}——{3}——{4}——{5}".format(item_loc, nick, raw_title, view_sales, view_price, comment_url)) #print(item_loc + ',' + nick + ',' + raw_title + ',' + view_sales + ',' + view_price + ',' + comment_url + u"\n") #清理raw_title里面无效的描述信息 #将数据每个字段存到数据表中 if "二手" not in raw_title: if "笔记本" not in raw_title: raw_title = filter_raw_title(raw_title) insert_original_lists(item_loc, nick, raw_title, view_sales, view_price, comment_url) def filter_raw_title(raw_title): #全部转大写 raw_title=raw_title.upper() #拼接非超等词 for key1 in keywords_1: for key2 in kewords_2: search_key=key1+key2 #print(search_key) raw_title=raw_title.split(search_key)[0] #print(raw_title) return raw_title def insert_original_lists(item_loc,nick,raw_title,view_sales,view_price,comment_url): view_price=float(view_price) db = pymysql.connect("localhost", "root", "123456", "tmall_price_changes") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into GTX_ORIGINAL_DATA (item_loc,nick,raw_title,view_sales,view_price,comment_url) values('%s','%s','%s','%s','%d','%s')" %(item_loc,nick,raw_title,view_sales,view_price,comment_url) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_gtx_lists(item_loc,nick,raw_title,view_sales,view_price,comment_url): view_price=float(view_price) db = pymysql.connect("localhost", "root", "123456", "tmall_price_changes") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into GTX (item_loc,nick,raw_title,view_sales,view_price,comment_url) values('%s','%s','%s','%s','%d','%s')" %(item_loc,nick,raw_title,view_sales,view_price,comment_url) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_list(): db = pymysql.connect("localhost", "root", "123456", "tmall_price_changes") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select item_loc,raw_title,view_price,comment_url from GTX_ORIGINAL_DATA group by item_loc,raw_title,view_price,comment_url" #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_gtx_dictionary(): db = pymysql.connect("localhost", "root", "123456", "tmall_price_changes") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select gtx_type,gtx_memory from gtx_dictionary " #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": keywords_1=["非","超","秒","追","战","吊打","代替","完胜","拼","挑"] kewords_2=[""] kewords_3=["笔记本","二手"] #打开对应的tmall查询显卡的链接 xianka=["GTX1050","GTX1060","GTX1070","GTX1080","GTX1065","显卡"] #xianka=["电线电缆"] for i in range(len(xianka)): gtx_url_normal="https://s.taobao.com/search?q="+xianka[i]+"&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20180228&ie=utf8&cps=yes&ppath=413%3A1001889" get_content(gtx_url_normal) gtx_url_xiaoliang=gtx_url_normal+"&sort=sale-desc" get_content(gtx_url_xiaoliang) gtx_url_renqi = gtx_url_normal + "&sort=renqi-desc" get_content(gtx_url_renqi) #处理table数据 data=get_list() for x in range (len(data)): item_loc=data[x][0] raw_title=data[x][1] view_price=data[x][2] comment_url=data[x][3] #print(item_loc,raw_title,view_price,comment_url) insert_gtx_lists(item_loc, "", raw_title,"", view_price, comment_url) #按照型号整理 gtx_dictionary=get_gtx_dictionary() for y in range(len(gtx_dictionary)): gtx_type=gtx_dictionary[y][0] gtx_memory = gtx_dictionary[y][1] #print(gtx_type,gtx_memory) <file_sep>/untitled/Selenium/selenium爬取淘宝美食页数据.py #encoding:utf8 import re from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup #from config import * #import pymongo #client=pymongo.MongoClient(MONGODB_URL) #db=client[MONGODB_DB] ##这里使用PhantomJS,并配置了一些参数 browser=webdriver.PhantomJS() ##窗口的大小,不设置的话,默认太小,会有问题 browser.set_window_size(1400,900) wait=WebDriverWait(browser, 10) def search(): print('正在搜索') ##容易出现超时的错误 try: ##等待这两个模块都加载好 browser.get("https://www.taobao.com") input = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#q')) ) submit=wait.until( EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_TSearchForm > div.search-button > button')) ) ######这块python2搞得鬼 input.send_keys('\u<PASSWORD>\u<PASSWORD>'.decode("unicode-escape")) #input.send_keys(KEYWORD.decode("unicode-escape")) submit.click() total = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.total')) ) get_product() return total.text except TimeoutException: return search() def next_page(page_number): print('翻页'+str(page_number)) try: input = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.form > input')) ) submit=wait.until( EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit')) ) input.clear() input.send_keys(page_number) submit.click() ##判断是否翻页成功 高亮的是不是输入的值,直接加在后面即可 wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number))) get_product() except TimeoutException: return next_page(page_number) #获取产品信息 def get_product(): products = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .m-itemlist .items')) ) ##拿到网页 html = browser.page_source soup = BeautifulSoup(html,'lxml') items = soup.select('#mainsrp-itemlist .m-itemlist .items .item.J_MouserOnverReq')# print('*************************到此*************') for item in items: img = item.select('.J_ItemPic.img')[0].get('src') price = item.select('.price.g_price.g_price-highlight > strong')[0].get_text() deal = item.select('.deal-cnt')[0].get_text() title= item.select('.row.row-2.title > a ')[0].get_text().strip() #:nth-of-type(3) shop = item.select('.row.row-3.g-clearfix > .shop > a > span:nth-of-type(2)')[0].get_text() location = item.select('.location')[0].get_text() product={ 'img':img, 'price':price, 'deal':deal, 'title':title, 'shop':shop, 'location':location } #打印一下 import json j = json.dumps(product) dict2 = j.decode("unicode-escape") print (dict2) #save_to_mongo(product) def main(): try: total=search() ##搜寻 re正则表达式 s=re.compile('(\d+)') total=int(s.search(total).group(1)) for i in range(2,total+1): next_page(i) except Exception: print('出错') finally: browser.close() if __name__ == '__main__': main()<file_sep>/工品汇/查找德力西商品型号/直接获取详情页的数据-part.py import random import re import time import bs4 import xlrd import pymysql from selenium import webdriver from bs4 import BeautifulSoup def company_info(): company_name="德力西" return company_name def login_url(uid,pwd): driver.find_element_by_css_selector('.login-name.u-b.J_name').send_keys(uid) driver.find_element_by_css_selector('.login-pwd.p-b.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.main-background-color.login-but.cursor.J_button').click() time.sleep(5) def get_main_data(url): J_searchLists=driver.find_elements_by_xpath("//div[@class='J_searchList']/ul") for Searchlist in J_searchLists: img_url=Searchlist.find_element_by_xpath("./li[@class='a']/a/img").get_attribute('src') prt_name=Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").text prt_url =Searchlist.find_element_by_xpath("./li[@class='b lh tl']/a").get_attribute('href') prt_id = prt_url[prt_url.index("product/") + 8:100] prt_type=Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[0].text order = Searchlist.find_elements_by_xpath("./li[@class='b lh tl']/div")[1].text price=Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='a']").text market_price = Searchlist.find_element_by_xpath("./li[@class='e lh tl']/div[@class='search-active']/span[@class='b']").text print(img_url,prt_id,prt_name,prt_url,prt_type,order,price,market_price) insert_data1(prt_id,prt_name,prt_url,prt_type,order,price,market_price,url) def insert_data1(prt_id,prt_name,prt_url,prt_type,order,price,market_price,url): company_name=company_info() db = pymysql.connect("localhost", "root", "123456", "vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into vipmro_data (company_name,prt_id,prt_name,prt_url,prt_type,order_,price,market_price,cate_2_url)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s','%s')"\ %(company_name,prt_id,prt_name,prt_url,prt_type,order,price,market_price,url) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def next_page(j): time.sleep(4) xpath_data="//div[@class='saas-paging J_paging']/a[@class='J_page_turn'][@page-id='"+str(j+2)+"']" print(xpath_data) driver.find_element_by_xpath(xpath_data).click() time.sleep(4) def get_url_status(): company_name=company_info() db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select case when cate_2_url='' then cate_1_url else cate_2_url end as url from vipmro_url where status=0 and company_name='"+company_name+"' order by table_id limit 1 " try: execute=cursor.execute(sql) category_url=cursor.fetchmany(execute) return category_url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_run_log(url): db = pymysql.connect("localhost","root","123456","vipmro",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update vipmro_url set status=1 where cate_2_url='%s' or cate_1_url='%s' " \ % (url,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def find_series_cate(html): soup=BeautifulSoup(html,'html.parser') divs=soup.find('div',attrs={'class':'J_attr'}).find_all('div',attrs={'class':'search-menu-li'}) for div in divs: name=div.find('span',attrs={'class':'a m-top10 weight'}).text series = div.find('span', attrs={'class': 'b p-left10 no-border'}).find_all('a') for a in series: series_url = a.get('href') series_name = a.text print(name, series_name, series_url) def get_lists(): list_divs=driver.find_elements_by_xpath("//div[@class='list-main-box J_list J_car_box']/ul/li") print('当前页一共%s条数据'%str(len(list_divs))) for list_div in list_divs: #列表页小图 list_prt_img=list_div.find_element_by_xpath("./div[@class='list-main-box-img']/a/img") list_prt_img_url=list_prt_img.get_attribute('src') list_prt_img_name=list_prt_img_url[list_prt_img_url.rindex("/")+1:list_prt_img_url.rindex("jpg")+3] print(list_prt_img_name,list_prt_img_url) #SKU_TITLE list_prt_info=list_div.find_element_by_xpath("./div[@class='list-main-box-cont']/a") list_prt_url=list_prt_info.get_attribute('href') list_prt_title = list_prt_info.find_element_by_xpath("./span[@class='title']").text list_prt_type = list_prt_info.find_element_by_xpath("./span[@class='model m-top5']").text list_prt_order = list_prt_info.find_element_by_xpath("./span[@class='model']").text.replace(" ","") list_prt_sale_price = list_prt_info.find_element_by_xpath("./span[@class='price_color m-top5']/font/font[@class='weight ft14']").text prt_id=list_prt_url[list_prt_url.rindex("/"):100] print(prt_id,list_prt_title,list_prt_url,list_prt_type,list_prt_order,list_prt_sale_price) insert_vipmro_delixi_lists(prt_id,list_prt_title,list_prt_url,list_prt_type,list_prt_order) def insert_vipmro_delixi_lists(prt_id,prt_name,prt_url,prt_type,po_number): company_name=company_info() db = pymysql.connect("localhost", "root", "123456", "de-ele") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_order_type_link (prt_id,prt_name,prt_url,prt_type,po_number)"\ "values('%s','%s','%s','%s','%s')"\ %(prt_id,prt_name,prt_url,prt_type,po_number) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def get_detail(prt_id): #商品属性 prt_title=driver.find_element_by_css_selector('.detail-goods-right-head.ft22.J_title').text old_price=driver.find_element_by_css_selector('.b.l.weight.ft12.J_marketPrice').text po_number=driver.find_element_by_css_selector('.J_buyNo.d').text prt_type = driver.find_element_by_css_selector('.J_model.d').text print(prt_title,old_price,po_number,prt_type) insert_prt_info(prt_id,prt_title,old_price,po_number,prt_type) #销售属性 attr_names=driver.find_elements_by_xpath("//table[@class='detail-attrs-right-attrs fl J_attrs']/tbody/tr/td[@align='center']") attr_values = driver.find_elements_by_xpath("//table[@class='detail-attrs-right-attrs fl J_attrs']/tbody/tr/td[@width='37%']") print(str(len(attr_names)),str(len(attr_values))) for i in range(len(attr_names)): num=i+1 print(attr_names[i].text,attr_values[i].text) attr_name=attr_names[i].text attr_value=attr_values[i].text insert_attr_info(prt_id,attr_name,attr_value,num) def insert_prt_info(prt_id,prt_name,old_price,po_number,prt_type): db = pymysql.connect("localhost", "root", "123456", "de-ele") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_order_type_link (prt_id,prt_name,old_price,prt_type,po_number)"\ "values('%s','%s','%s','%s','%s')"\ %(prt_id,prt_name,old_price,prt_type,po_number) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def insert_attr_info(prt_id,attr_name,attr_value,num): db = pymysql.connect("localhost", "root", "123456", "de-ele") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into attributes_info (prt_id,attr_name,attr_value,num)"\ "values('%s','%s','%s','%s')"\ %(prt_id,attr_name,attr_value,num) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() if __name__=="__main__": driver=webdriver.Firefox() urls=['http://www.vipmro.com/product/578321', 'http://www.vipmro.com/product/578312', 'http://www.vipmro.com/product/578331', 'http://www.vipmro.com/product/578333', 'http://www.vipmro.com/product/578334', 'http://www.vipmro.com/product/577340', 'http://www.vipmro.com/product/577304', 'http://www.vipmro.com/product/577453', 'http://www.vipmro.com/product/577463', 'http://www.vipmro.com/product/577473', 'http://www.vipmro.com/product/575168', 'http://www.vipmro.com/product/575157', 'http://www.vipmro.com/product/1145073', 'http://www.vipmro.com/product/1145267', 'http://www.vipmro.com/product/1145530'] for i in range (len(urls)): #url_t=get_url_status() #url=url_t[0][0] url=urls[i] prt_id=url[url.rindex('/')+1:100] print(prt_id,url) driver.get(url) time.sleep(5) html=driver.page_source #获取二级类目后,判断页面上是否有系列这个词 get_detail(prt_id) #update_status_to_run_log(url) time.sleep(4) <file_sep>/suning/苏宁后台/获取详情内容html.py import pymysql import os import urllib.request import sys import requests def get_prt_content_from_table(): db = pymysql.connect("localhost", "root", "123456", "suning") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select table_id,prt_id,prt_title,prt_desc from suning_prt_data" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_prt_content(table_id,content): db = pymysql.connect("localhost", "root", "123456", "suning") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update suning_prt_data set prt_content='%s' where table_id='%s' " %(content,table_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------update_prt_content------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #从数据库获取整体的数据 data=get_prt_content_from_table() for i in range(len(data)): #print(data[i])table_id,prt_id,prt_title,prt_desc table_id=data[i][0] prt_id=data[i][1] prt_title=data[i][2] prt_desc = data[i][3] #如何干掉prt_desc prt_text=prt_desc.split("introduceEdit=")[-1].split('" width')[0] print(prt_text) s=requests.get(prt_text) content = s.content.decode('utf-8') print(content) update_prt_content(table_id,content) <file_sep>/untitled/Selenium/问答论坛关键词/百度知道1.0.py #1. 百度知道 #2. 搜索关键词"",搜索 #https://zhidao.baidu.com/ #sendkeys=> <input class="hdi" id="kw" maxlength="256" tabindex="1" size="46" name="word" value="" autocomplete="off"> #click=> <button alog-action="g-search-anwser" type="submit" id="search-btn" hidefocus="true" tabindex="2" class="btn-global">搜索答案</button> #3. 获取搜索结果页的列表问题标题与url #<div class="list" id="wgt-list" data-log-area="list"> #标题、url、回答数、赞数 #4. 遍历这些url,并且作为第一层问题汇总 #5. 对每一个url的跳转页面,中的“其他类似问题”进行获取标题和url,作为第二层问题的汇总 #6. 对每一个url的跳转页面,中的“其他类似问题”进行获取标题和url,作为第三层问题的汇总 #7. 后面应该就是循环的次数进行限制了,不过问题在于1->6->36->6^3不断增加的 import time from selenium import webdriver if __name__=="__main__": driver=webdriver.PhantomJS() driver.get("https://zhidao.baidu.com") driver.find_element_by_id("kw").send_keys("RVV") driver.find_element_by_id("search-btn").click() time.sleep(2) #url=driver.title #print(url) page=driver.page_source print(page) #搜索结果页,第一页的结果 for i in range(10): list1=driver.find_element_by_id("wgt-list") list2=list1.find_elements_by_class_name("dl") print("当前结果页一共 "+str(len(list2))+" 条记录") for j in range(len(list2)): title_url=list2[j].find_element_by_css_selector(".dt.mb-4.line") title=title_url.find_element_by_tag_name("a").text #url=title_url.find_element_by_tag_name("a").get_attribute("href") print("标题名称:"+title) answer=list2[j].find_element_by_css_selector(".dd.answer").text print("answer") <file_sep>/untitled/Selenium/工品汇/category.py import time import bs4 from Login import login if __name__=='__main__': url='http://www.vipmro.net/search?brandId=105' uid='18861779873' pwd='<PASSWORD>' #完成登录 source=login.login_url(url,uid,pwd) time.sleep(5) page_info = bs4.BeautifulSoup(source, "html.parser") cate_1=page_info.find('span',attrs={'class':'b p-left10 no-border'}).findAll('a') for i in range (0,len(cate_1)): print(cate_1[i]) <file_sep>/JD后台/VC后台/获取前台的京东价V1.2.py import pymysql import time import random from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def init(self,url): #selenium登录 browser = "Chrome" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 driver = webdriver.Chrome() else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() driver.get(url) #等待用户自己登陆 #判断是否登陆成功 name = input("Go?") print(name) prt_data=self.get_sku_id() for i in range (len(prt_data)): sku_id=prt_data[i][0] vc_shop=prt_data[i][1] print(sku_id,vc_shop) #直接通过url获取京东价、市场价 prt_url="https://vcp.jd.com/sub_item/item/preview/init?pid="+sku_id+"&wareId="+sku_id driver.get(prt_url) table_ths=driver.find_elements_by_xpath("//table[@class='basic-table']/tbody/tr/th") table_tds = driver.find_elements_by_xpath("//table[@class='basic-table']/tbody/tr/td") print(str(len(table_ths)),str(len(table_tds))) for i in range (len(table_ths)): th_text=table_ths[i].text td_text=table_tds[i].text #print(th_text,td_text) if "商品型号" in th_text: prt_type=td_text if "商品名称" in th_text: prt_name = td_text if "商品重量" in th_text: prt_weight = td_text if "长" in th_text: length = td_text if "宽" in th_text: width = td_text if "高" in th_text: height = td_text if "市场价" in th_text: market_price = td_text if "京东价" in th_text: jd_price= td_text if vc_shop=="家装": table_guige_names=driver.find_elements_by_xpath("//div[@class='category-table-div']/div/div/table/tbody/tr/th/span") table_guige_values = driver.find_elements_by_xpath("//div[@class='category-table-div']/div/div/table/tbody/tr/td/input") dianya='' gonglv='' for x in range (2): th_text=table_guige_names[x].text td_text=table_guige_values[x].get_attribute('value') print(th_text,td_text) if "额定电压" in th_text: dianya = td_text if "额定功率" in th_text: gonglv = td_text self.update_caigou_price(prt_type, prt_name, prt_weight, length, width, height, market_price, jd_price,dianya, gonglv, sku_id) else: self.update_caigou_price(prt_type, prt_name, prt_weight, length, width, height, market_price, jd_price,'', '', sku_id) #self.s(1, 3) def get_sku_id(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 主商品编号,vc_shop from jd_upgrade_price where 市场价 is null" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_caigou_price(self,prt_type,prt_name,prt_weight,length,width,height,market_price,jd_price,dianya,gonglv,sku_id): db = pymysql.connect("localhost", "root", "1<PASSWORD>", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update jd_upgrade_price set 商品型号='%s',商品名称='%s',商品重量='%s',长='%s',宽='%s',高='%s',市场价='%s',京东价='%s',额定电压='%s',额定功率='%s' where 主商品编号 ='%s'" %(prt_type,prt_name,prt_weight,length,width,height,market_price,jd_price,dianya,gonglv,sku_id) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": main=main() #url="http://www.baidu.com" url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com" main.init(url)<file_sep>/MMBAO.COM遍历URL筛选404链接-1.1/层级遍历(暂未可靠地停止方法)-1.1.py #参数,层级 #使用request进行操作 import urllib.request import requests from bs4 import BeautifulSoup import re import pymysql import time import socket class get_data(): # 获取html函数,参数:url def getHtml(self,url): req = urllib.request.Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/47.0") response = urllib.request.urlopen(req) html = response.read().decode('utf-8') # print(html) return html # 获取所有<a>标签中的href属性 def getHref_1(self,url, html): hrefs = [] url = url[0:url.index("/", 7)] #将url截断,拼href soup = BeautifulSoup(html, 'lxml') a_s = soup.find_all('a') for a in a_s: a_href = a.get('href') if a_href != None: if a_href != '': if 'http' not in a_href: if 'javascript:' not in a_href: href = url + a_href hrefs.append(href) # print(url+a_href) return hrefs def getHref_2(self,html): hrefs = [] hrefs_2 = re.findall('"((http)s?://.*?)"', html) for href in hrefs_2: # print(href[0]) if 'mmbao' in href[0]: hrefs.append(href[0]) return hrefs def insert_data2(floor,href1,hrefs2,codes): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() for i in range(len(hrefs2)): # 使用 execute() 方法执行 SQL 查询 sql="insert into floor_2 " \ " (floor,href_up,href_current,code)" \ " values('%d','%s','%s','%s')" \ % (floor,href1,hrefs2[i],codes[i]) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def insert_data(floor, href1, href2, code): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql = "insert into floor_2 " \ " (floor,href_up,href_current,code)" \ " values('%d','%s','%s','%s')" \ % (floor, href1, href2, code) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def get_status(url): try: r = requests.get(url, allow_redirects = False,timeout=5) return r.status_code except requests.exceptions.ConnectTimeout: NETWORK_STATUS = False code='405' return code def get_url(): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select href_current from floor_2 where status=0 limit 1" try: execute = cursor.execute(sql) url = cursor.fetchmany(execute) url=str(url).replace("(('", "").replace("',),)", "") return url except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def excute_def(floor,url): hrefs=[] hrefs_2=[] codes=[] print(url) data = get_data() html = data.getHtml(url) hrefs = data.getHref_1(url, html) hrefs_2 = data.getHref_2(html) for href in hrefs_2: # print(href) hrefs.append(href) for href in hrefs: code = get_status(href) code = "waiting" #判断是否有.js加持,有的话跳过 if '.js' in href: continue if '.css' in href: continue print(href + " " + str(code)) # codes.append(code) insert_data(floor, url, href, code) # insert_data2(floor,url,hrefs,codes) def get_cnt(floor): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor floor=floor-1 cursor = db.cursor() sql="select count(href_current) as cnt from floor_2 where status=0 and floor='%d'" %(floor) try: execute = cursor.execute(sql) cnt = cursor.fetchmany(execute) cnt=str(cnt).replace("((", "").replace(",),)", "") return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_log(url,status): db = pymysql.connect("localhost","root","123456","mmbao",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update floor_2 set status='%s' where href_current='%s' " %(status,url) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() if __name__=="__main__": floors=4 #其实只有三层,4代表第三层,line151 for i in range (3,floors): floor=i if floor==1: url="http://www.mmbao.com" excute_def(floor, url) else: cnt=get_cnt(floor) print("还有%s要处理"%cnt) for j in range(int(cnt)): url = get_url() try: excute_def(floor, url) status=1 update_status_to_log(url, status) except: status=2 update_status_to_log(url, status) <file_sep>/找电缆EXCEL处理2.0新版/判断当前excel格式.py # 打开一个excel import xlrd import os import pymysql import shutil # 从excel中获取url的列表数据 def get_data_from_excel(path): # excel_name=r"D:\BI\找电缆\2017年12月红本出厂价《产品价格目录》\1712出厂价/201712 架空线出厂价-国标.xls" print(path) excel_name = path[path.rindex("/") + 1:1000] excel_status=1 data=xlrd.open_workbook(path) #打开excel # 遍历所有的sheet # print("当前excel共有%s个SHEET" % str(len(data.sheets()))) for i in range (len(data.sheets())): sheetName = data.sheet_names()[i] #print("##第【%s】个SHEET:%s" % (str(i+1), sheetName)) table = data.sheets()[i] # 打开excel的第几个sheet nrows = table.nrows # 捕获到有效数据的行数 url_lists = [] # print(sheetName) try: first_row = table.row_values(0) msg="" except IndexError as e: msg="error" if msg=="": second_row = table.row_values(1) # print(first_row) len_first_row = len(first_row) if len_first_row == 2: # ['型号规格', '出厂价'] # ['规格型号', '出厂价'] # print(second_row) # second有两种情况 if second_row[0] == "": # ['', '元/KM'] for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] exw_price = ss[1] print(type_specification, exw_price) # full_text=excel_name+","+sheetName+","+type_specification insert_new_details(excel_name, sheetName, type_specification, "", exw_price) else: # ['3*10/3*6', 376.79488600421473] for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] exw_price = ss[1] print(type_specification, exw_price) # full_text = excel_name + "," + sheetName + "," + type_specification insert_new_details(excel_name, sheetName, type_specification, "", exw_price) elif len_first_row == 3: if first_row[1] == "出厂价": # print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] zrc = ss[1] zrb = ss[2] print(type_specification, zrc, zrb) x_type = ["zrc", "zrb"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification+ "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 1]) elif first_row[1] == "普通": # print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] zrc = ss[1] zrb = ss[2] print(type_specification, zrc, zrb) x_type = ["普通", "zrc"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification+ "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 1]) elif len_first_row == 4: if first_row[1] == "出厂价": # print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] zrc = ss[1] zrb = ss[2] zra = ss[3] print(type_specification, zrc, zrb, zra) x_type = ["zrc", "zrb", "zra"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification+ "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 1]) elif first_row[1] == "型号": print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 wuliao_num = ss[0] type = ss[1] specification = ss[2] exw_price = ss[3] if wuliao_num != "物料编码" and type!="" : type_specification=type+"-"+specification print(wuliao_num, type, specification, exw_price) # full_text = excel_name + "," + sheetName + "," + wuliao_num+ "," + type+ "," + specification insert_new_details(excel_name, sheetName, type_specification,wuliao_num, exw_price) pass elif len_first_row == 5: if first_row[1] == "出厂价": # print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb = ss[3] zra = ss[4] if type_specification != "": print(type_specification, pt, zrc, zrb, zra) x_type = ["pt", "zrc", "zrb", "zra"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 1]) elif first_row[1] == "普通": # print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb = ss[3] zra = ss[4] print(type_specification, pt, zrc, zrb, zra) x_type = ["pt", "zrc", "zrb", "zra"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 1]) elif len_first_row == 6: if first_row[1] == "出厂价": # print(second_row) for j in range(1, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] exw_price = ss[1] print(type_specification, exw_price) # full_text = excel_name + "," + sheetName + "," + type_specification insert_new_details(excel_name, sheetName, type_specification, "", exw_price) elif first_row[1] == "": # print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] type2 = ss[1] pt = ss[2] zrc = ss[3] zrb = ss[4] zra = ss[5] print(type_specification, type2, pt, zrc, zrb, zra) x_type = ["pt", "zrc", "zrb", "zra"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 2]) # type2不入 elif len_first_row == 11: # print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb = ss[3] zra = ss[4] essence_pt = ss[5] essence_zc = ss[6] pt_balance = ss[7] essence_balance = ss[8] essence_sale_price = ss[9] zc_balance = ss[10] print(type_specification, pt, zrc, zrb, zra, essence_pt, essence_zc, pt_balance, essence_balance, essence_sale_price, zc_balance) x_type = ["pt", "zrc", "zrb", "zra", "essence_pt", "essence_zc", "pt_balance", "essence_balance", "essence_sale_price", "zc_balance"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 1]) elif len_first_row == 8: # print(second_row) for j in range(2, nrows): ss = table.row_values(j) # 获取一行的所有值,每一列的值以列表项存在 type_specification = ss[0] pt = ss[1] zrc = ss[2] zrb = ss[3] zra = ss[4] essence_pt = ss[5] essence_zc = ss[6] zc_balance = ss[7] print(type_specification, pt, zrc, zrb, zra, essence_pt, essence_zc, zc_balance) x_type = ["pt", "zrc", "zrb", "zra", "essence_pt", "essence_zc", "pt_balance"] for x in range(len(x_type)): # full_text = excel_name + "," + sheetName + "," + type_specification + "," + x_type[x] insert_new_details(excel_name, sheetName, type_specification, x_type[x], ss[x + 1]) # type2不入 else: excel_status=0 else: excel_status = 2 if excel_status==0: target_path = path.replace("201712特殊红本", "通过的红本文件") shutil.move(path, target_path) print("move %s -> %s" % (path, target_path)) elif excel_status==2: # 将获取完成的excel,转移到history文件夹 target_path = path.replace("201712特殊红本", "异常红本文件") shutil.move(path, target_path) print("move %s -> %s" % (path, target_path)) else: target_path = path.replace("201712特殊红本", "通过的红本文件") shutil.move(path, target_path) print("move %s -> %s" % (path, target_path)) #读取所有文件夹中的xls文件 def read_xls(path, type2): #遍历路径文件夹 for file in os.walk(path): for each_list in file[2]: file_path=file[0]+"/"+each_list #os.walk()函数返回三个参数:路径,子文件夹,路径下的文件,利用字符串拼接file[0]和file[2]得到文件的路径 name.append(file_path) #储存结果集 def insert_new_details(excel_name, sheet_name,type_specification,lev_zr,price): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into hongben_1712 (excel_name, sheet_name,type_specification,lev_zr,price) values('%s','%s','%s','%s','%s') "%(excel_name, sheet_name,type_specification,lev_zr,price) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------insert_sale_attr_table-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__ == "__main__": xpath = r"D:\BI\找电缆\201712特殊红本" xtype = "xls" name = [] read_xls(xpath, xtype) print("%s个文件"%str(len(name))) for i in range (len(name)): excel_name = name[i] get_data_from_excel(excel_name) <file_sep>/ZYDMALL/zydmall_德力西/通过脚本处理销售属性(值)的筛选问题.py #把筛选属性值、属性名称放在一起了,所以请注意prt_entity表中的status状态有没有重置 #通过修改主函数中的type参数,达到是筛选属性名称还是属性值的作用 import pymysql import time def get_prt_id(): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi", charset="utf8") cursor = db.cursor() sql = "select prt_id,prt_title,series_name from prt_entity where status=0 limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def update_status(prt_id): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi", charset="utf8") cursor = db.cursor() sql = "update prt_entity set status=1 where prt_id='%s' " %prt_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def filter_attribute_name(prt_id): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi", charset="utf8") cursor = db.cursor() sql = "select b.prt_id as prt_id,a.attribute_name as attribute_name from prt_attribute a left join ( "\ " select prt_id,sku_id from prt_sku"\ " ) b on a.sku_id=b.sku_id"\ " where b.prt_id='%s'"\ " group by b.prt_id,a.attribute_name"\ %prt_id try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def filter_attribute_value(prt_id): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi", charset="utf8") cursor = db.cursor() sql = "select b.prt_id as prt_id,a.attribute_name as attribute_name,a.attribute_value as attribute_value from prt_attribute a left join ( " \ " select prt_id,sku_id from prt_sku" \ " ) b on a.sku_id=b.sku_id" \ " where b.prt_id='%s'" \ " group by b.prt_id,a.attribute_name,a.attribute_value" \ % prt_id try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_attribute_name_data(prt_id,prt_title,series_name,attribute_name): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi", charset="utf8") cursor = db.cursor() sql = "insert into prt_attribute_name_filter (prt_id,prt_title,series_name,attribute_name) values('%s','%s','%s','%s') " %(prt_id,prt_title,series_name,attribute_name) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_attribute_value_data(prt_id, prt_title, series_name, attribute_name,attribute_value): db = pymysql.connect("localhost", "root", "123456", "zydmall_delixi", charset="utf8") cursor = db.cursor() sql = "insert into prt_attribute_value_filter (prt_id,prt_title,series_name,attribute_name,attribute_value) values('%s','%s','%s','%s','%s') " %(prt_id, prt_title, series_name, attribute_name,attribute_value) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": type="属性值" for i in range(303): data=get_prt_id() prt_id=data[0][0] prt_title=data[0][1] series_name=data[0][2] print(prt_id,prt_title,series_name) #拿着prt_id去执行sql脚本,筛选出每个系列,对应的销售属性 if type=="属性名称": datas2=filter_attribute_name(prt_id) else: datas2 = filter_attribute_value(prt_id) print(datas2) print(len(datas2)) for data2 in datas2: if type == "属性名称": attribute = data2[1] insert_attribute_name_data(prt_id, prt_title, series_name, attribute) else: attribute_name = data2[1] attribute_value = data2[2] insert_attribute_value_data(prt_id, prt_title, series_name, attribute_name,attribute_value) time.sleep(1) update_status(prt_id) <file_sep>/日常工作/筛选结算单数据‘’.py import pymysql def get_data(): db = pymysql.connect("localhost", "root", "123456", "daily") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 商品名称 from tmp where status=0 group by 商品名称 " # print(sql) try: cursor.execute(sql) data=cursor.fetchall() return data except Exception as err: db.rollback() print('------insert_img_data---------Error------Message--------:' + str(err)) db.close() cursor.close() def find_detail(prt_title): db = pymysql.connect("localhost", "root", "123456", "daily") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 商品名称,商品编码,数据类型,单据编号,完成时间,是否特单,下单时间,数量,单价,金额 from tmp where 商品名称='%s' and status=0 " %prt_title # print(sql) try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('------insert_img_data---------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": data=get_data() for i in range(len(data)): prt_title=data[i][0] print(prt_title) data2=find_detail(prt_title) for x in range (len(data2)): <file_sep>/untitled/Selenium/工品汇/伊顿电气-20170831/VIPMRO-伊顿电气-数据获取.py import pymysql from selenium import webdriver import time def login_url(uid,pwd): driver.find_element_by_css_selector('.login-text.m-top5.act-bg.J_userName').send_keys(uid) driver.find_element_by_css_selector('.login-text.m-top5.psw-bg.J_psw').send_keys(pwd) driver.find_element_by_css_selector('.login-save.m-top10.ft20.cursor.J_loginIn').click() time.sleep(5) def t(seconds): time.sleep(seconds) def get_category(): a_cates=driver.find_elements_by_xpath("//label[@class='J_cate']/a") for a_cate in a_cates: cate1_name=a_cate.text cate1_url=a_cate.get_attribute('href') print(cate1_name,cate1_url) t(2) if __name__=="__main__": url="http://www.vipmro.com/login" browser="Firefox" if browser=="Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument('--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser=="Firefox": driver=webdriver.Firefox() else: driver=webdriver.PhantomJS() driver.get(url) time.sleep(3) uid='18861779873' pwd='<PASSWORD>' login_url(uid,pwd) print("------finish the login step---------") #开始正规数据 url="http://www.vipmro.com/search?brandId=210" driver.get(url) get_category() <file_sep>/untitled/Selenium/dq123/dq123商品信息1.2.py #1.0 版本,完成基本的数据获取/导入MYSQL操作 #1.1版本,需要加入翻页功能,设定20页数据即可(用于多主机分布获取) #2.0版本, # a. 加入timeoutException,当超时时,可以重新执行当前函数, #try: #except TimeoutException: # return search() # b. 模块化,减少代码冗余, # c. # d. # e. # f. import pymysql import time import re from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait def insert_mysql(id,prt_name,price,company,issuedate,cate1,cate2,series,detail): try: tmp0=detail[0] except: tmp0="NULL" try: tmp1=detail[1] except: tmp1="NULL" try: tmp2=detail[2] except: tmp2="NULL" try: tmp3=detail[3] except: tmp3="NULL" try: tmp4=detail[4] except: tmp4="NULL" try: tmp5=detail[5] except: tmp5="NULL" try: tmp6=detail[6] except: tmp6="NULL" try: tmp7=detail[7] except: tmp7="NULL" try: tmp8=detail[8] except: tmp8="NULL" try: tmp9=detail[9] except: tmp9="NULL" try: tmp10=detail[10] except: tmp10="NULL" try: tmp11=detail[11] except: tmp11="NULL" try: tmp12=detail[12] except: tmp12="NULL" try: tmp13=detail[13] except: tmp13="NULL" try: tmp14=detail[14] except: tmp14="NULL" try: tmp15=detail[15] except: tmp15="NULL" try: tmp16=detail[16] except: tmp16="NULL" try: tmp17=detail[17] except: tmp17="NULL" try: tmp18=detail[18] except: tmp18="NULL" try: tmp19=detail[19] except: tmp19="NULL" try: tmp20=detail[20] except: tmp20="NULL" try: tmp21=detail[21] except: tmp21="NULL" try: tmp22=detail[22] except: tmp22="NULL" try: tmp23=detail[23] except: tmp23="NULL" try: tmp24=detail[24] except: tmp24="NULL" try: tmp25=detail[25] except: tmp25="NULL" try: tmp26=detail[26] except: tmp26="NULL" try: tmp27=detail[27] except: tmp27="NULL" try: tmp28=detail[28] except: tmp28="NULL" try: tmp29=detail[29] except: tmp29="NULL" try: tmp30=detail[30] except: tmp30="NULL" try: tmp31=detail[31] except: tmp31="NULL" try: tmp32=detail[32] except: tmp32="NULL" try: tmp33=detail[33] except: tmp33="NULL" db = pymysql.connect("192.168.180.159", "root", "123456", "test01") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into DQ123PRTINFO" \ " (PRT_ID,PRT_NAME,PRICE,COMPANY,RELEASE_DATE,CATE1,CATE2,SERIES,TYPE1,VALUE1,TYPE2,VALUE2,TYPE3,VALUE3,TYPE4,VALUE4,TYPE5,VALUE5,TYPE6,VALUE6,TYPE7,VALUE7,TYPE8,VALUE8,TYPE9,VALUE9,TYPE10,VALUE10,TYPE11,VALUE11,TYPE12,VALUE12,TYPE13,VALUE13,TYPE14,VALUE14,TYPE15,VALUE15,TYPE16,VALUE16,TYPE17,VALUE17)" \ " values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \ % (id,prt_name,price,company,issuedate,cate1,cate2,series,tmp0,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9,tmp10,tmp11,tmp12,tmp13,tmp14,tmp15,tmp16,tmp17,tmp18,tmp19,tmp20,tmp21,tmp22,tmp23,tmp24,tmp25,tmp26,tmp27,tmp28,tmp29,tmp30,tmp31,tmp32,tmp33) # 使用 fetchone() 方法获取单条数据. # data = cursor.fetchone() try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() # print(prt_name+'--------2-finished') except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() def click_cate(category1,category2): list = driver.find_element_by_id("classlibiao") list.find_element_by_link_text(category1).click() print("一级类目:" + category1) time.sleep(5) list.find_element_by_link_text(category2).click() print("二级类目:" + category2) time.sleep(5) def page_num(orginal_page): if orginal_page>10: num = int((orginal_page - 10) / 4 + 1) print("循环" + str(num) + "次") for page in range(num): m = 10 + 4 * page driver.find_element_by_xpath("//div[@id='pagesdiv']/a[@p='" + str(m) + "']").click() time.sleep(15) try: driver.find_element_by_xpath("//div[@id='pagesdiv']/a[@p='" + str(orginal_page) + "']").click() except: print("当前可能就是" + str(orginal_page)) time.sleep(13) def table_info(catgory2): list_1 = driver.find_element_by_xpath("//table[@class='yjtbs']/tbody[@id='part_list']") tr = list_1.find_elements_by_tag_name("tr") detail=[] tr_num=len(tr) print("当前页共"+str(tr_num)+"条数据") if tr_num==0: time.sleep(5) for i in range(len(tr)): time.sleep(4) colunm = tr[i].find_elements_by_tag_name("td") # print(len(colunm)) # 获取序号、商品名、价格、制造商 td1 = colunm[0].text td2 = colunm[1].text td3 = colunm[2].text td4 = colunm[3].text print(td1 + "//" + td2 + "//" + td3 + "//" + td4) # 点击事件 colunm[1].find_element_by_tag_name("a").click() #time.sleep(6) time.sleep(5) # 准备获取商品的规格信息 # 发布日期 issuedate = driver.find_element_by_id("fissuedate").text series = driver.find_element_by_xpath("//input[@id='classSelele']").get_attribute("value") #print(series) body = driver.find_element_by_id("Part_MainProp") # 规格属性所在的div type = body.find_elements_by_xpath("div[@class='prop_part']") if len(type)<=2: time.sleep(10) type = body.find_elements_by_xpath("div[@class='prop_part']") # print("total "+str(len(type))+" for type") for x in range(len(type)): # 规格属性 try: type_name = type[x].find_element_by_tag_name("label").text except: type_name = "异常记录" #type_name_w=wait.until(EC.presence_of_element_located((By.TAG_NAME,"label"))) #type_name=type_name_w.text try: type_value = type[x].find_element_by_xpath("div[@class='prop_list']/span[@class='opt_s opt_s opt_s_ch']").text except: type_value= "异常记录" detail.append(type_name) detail.append(type_value) # print(type_name+" : "+type_value) # print(detail) #print("共" + str(len(detail) / 2) + "条规格属性") insert_mysql(td1, td2, td3, td4, issuedate, category1, catgory2, series, detail) # print("此条记录已导入") detail = [] #time.sleep(6) # 返回整个产品目录 driver.find_element_by_id("showhidediv1").click() time.sleep(6) return tr_num # 跳转到下一页 if __name__=="__main__": #定义函数 #当前页面的数据条数 category1="隔离电器" category2 = ["刀形隔离器","刀型熔断器开关","负荷开关"] orginal_page=[12,1,1] ##这里使用PhantomJS,并配置了一些参数 driver = webdriver.PhantomJS() ##窗口的大小,不设置的话,默认太小,会有问题 driver.set_window_size(1400, 900) #载入url,点击列表选型 driver.get("http://www.dq123.com/price/index.php") #wait = WebDriverWait(driver, 10) time.sleep(8) for i in range(len(category2)): driver.find_element_by_id("showhidediv1").click() time.sleep(5) # 1. 选择对应的产品目录 #点击到二级类目下的列表 catgory2=category2[i] page=orginal_page[i] click_cate(category1,catgory2) time.sleep(5) #1. 获取整个产品目录,然后进行遍历,一个脚本循环20次,防止异常 #先调整起始页数 page_num(page) for a in range(1000): tr_num=table_info(catgory2) time.sleep(10) if tr_num==50: print("翻页,当前" + str(a + 1 + page) + "页") driver.find_element_by_xpath("//div[@id='pagesdiv']/a[@title='下一页']").click() time.sleep(20) else: print("此项类目结束") break <file_sep>/untitled/test.py import pymysql from selenium import webdriver from bs4 import BeautifulSoup import re def insert_data(name,href): db = pymysql.connect("localhost", "root", "123456", "delixi_diangong", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "insert into jd_delixi_lists (prt_name,prt_url) values('%s','%s')" %(name,href) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_lists(html): soup=BeautifulSoup(html,"html.parser") lis=soup.find('div',attrs={'id':'choose-attr-1'}).find_all('div',attrs={'class':re.compile('item')}) print(str(len(lis))) for i in range (len(lis)): sku_id=lis[i].get('data-sku') sku_name=lis[i].get('data-value') prt_url="http://item.jd.com/"+sku_id+".html#none" insert_data(sku_name, prt_url) if __name__=="__main__": url="http://item.jd.com/11026509921.html#crumb-wrap" driver=webdriver.Firefox() driver.get(url) html=driver.page_source find_lists(html) <file_sep>/untitled/Selenium/天眼查/天眼查.py #coding=utf-8 import random import time import bs4 import xlrd import xlsxwriter from untitled.Selenium import webdriver #随机等待时间 def s(): rand=random.randint(3,5) time.sleep(rand) #将company_name改为list,循环查询 def print_xls(): data=xlrd.open_workbook(r"C:\Users\Administrator\Desktop\test_info.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 Company_Name=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss Company_Name.append(ss) return Company_Name # 函数:获取公司链接 # input :页面资源 # output : 对应的公司详情url链接 def Get_Company_Url(web_source): pages = bs4.BeautifulSoup(web_source, "html.parser") try: company_info_url=pages.find('div',attrs={'class':'col-xs-10 search_repadding2 f18'}).find('a',attrs={'class':'query_name search-new-color'}).get('href') #print(company_info_url) company_province=pages.find('div',attrs={'class':'search_base col-xs-2 search_repadding2 text-right c3 position-rel ng-binding'}).text print('Province:'+company_province) province.append(company_province) return company_info_url except Exception as err: print('不存在相关公司信息'+str(err)) company.append('未找到') province.append('未找到') address.append('未找到') return 'None' def Get_Company_Main(url): driver3 = webdriver.Firefox() driver3.get(url) s() web_source=driver3.page_source #print(web_source) pages = bs4.BeautifulSoup(web_source, "html.parser") #筛选法定代表人 company_name=pages.find('div',attrs={'class':'company_info_text'}).find('div',attrs={'class':'in-block ml10 f18 mb5 ng-binding'}).text print(company_name) company.append(company_name) company_info = pages.find('div', attrs={'class': 'company_info_text'}).findAll('span',attrs={'class': 'ng-binding'}) company_address = company_info[3].text print(company_address) address.append(company_address) print(address) driver3.quit() #print(company_report_url) def save_excel(fin_result1,fin_result2,fin_result3): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'C:\Users\Administrator\Desktop\test1.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result1)): tmp.write(i, 0, fin_result1[i]) tmp.write(i, 1, fin_result2[i]) tmp.write(i, 2, fin_result3[i]) #main函数 if __name__ == '__main__': Company_Info=print_xls() print(Company_Info) #定义多个list,存储地址,代表人,电话 company=[] address=[] province=[] Company_Num=len(Company_Info) for i in range (0,Company_Num): Company_Name=str(Company_Info[i]).replace("['",'').replace("']",'') print(str(i+1)+'/'+str(Company_Num)+' '+Company_Name) driver1 = webdriver.Firefox() driver1.get("http://www.tianyancha.com/search?key="+Company_Name+"&checkFrom=searchBox") s() source = driver1.page_source #print(source) company_info_url=Get_Company_Url(source) if company_info_url!='None': print(company_info_url) Get_Company_Main(company_info_url) driver1.quit() #for i in range (0,len(company)): #print(company[i]+' '+address[i]+' '+leader[i]+' '+phone[i]) save_excel(company,province,address) <file_sep>/TAOBAO/远东电线-店铺数据/淘宝店铺-远东电线-详情获取店铺名称-1.0.py import time import random from selenium import webdriver from bs4 import BeautifulSoup import re import pymysql def s(a,b): x=random.randint(a,b) time.sleep(x) #1. 打开淘宝,远东电线 def update_shop_data(table_id,shop_name,sep): db = pymysql.connect("localhost", "root", "123456", "taobao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update cable_yuandong_shop_info set shop_name='%s',sale_credit_rating='%s' where table_id='%s'" %(shop_name,sep,table_id) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_shop_data-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_data(table_id,html): soup=BeautifulSoup(html,'html.parser') #prt_title print("find_data...") try: shop_info=soup.find('div',attrs={'class':'tb-shop-name'}) shop_name=shop_info.text.replace("\n","") credit_url=soup.find('div',attrs={'class':re.compile('tb-shop-rank')}).find('a').get('href') print(shop_name,credit_url) credit_url="https:"+credit_url driver.get(credit_url) s(1,3) sep=driver.find_element_by_class_name('sep').text print(sep) except AttributeError as e: shop_info = soup.find('div', attrs={'class': 'shop-name-wrap'}) shop_name = shop_info.text.replace("\n", "") credit_url = soup.find('span', attrs={'class': re.compile('shop-rank')}).find('a').get('href') print(shop_name, credit_url) credit_url = "https:" + credit_url driver.get(credit_url) s(1, 3) sep = driver.find_element_by_class_name('sep').text print(sep) update_shop_data(table_id,shop_name,sep) def get_url(): db = pymysql.connect("localhost", "root", "123456", "taobao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,zhanggui_name,prt_url from cable_yuandong_shop_info where shop_name is null " try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------update_prt_desc-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": prt_data=get_url() # 载入url,获取详情数据 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/CC-SERVER/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() for i in range (len(prt_data)): table_id=prt_data[i][0] zhanggui_name=prt_data[i][1] prt_url=prt_data[i][2] url="https:"+prt_url driver.get(url) s(10,15) html = driver.page_source find_data(table_id,html) <file_sep>/untitled/zhilian-master/places_name.py # -*- coding:utf-8 -*- def get_start_url(): ''' 得到不同城市的起始链接 return:是包含不同城市的起始url ''' # 先主要爬主要城市,看不同需求,也可以爬全国,只要把智联的候选地点全部抓取下来即可 place_name = ['北京','上海', '广州', '深圳', '天津', '武汉', '西安', '成都', '大连', '长春', '沈阳', '南京', '济南', '青岛', '杭州', '苏州', '无锡', '宁波', '重庆', '郑州', '长沙', '福州', '厦门', '哈尔滨', '石家庄', '合肥', '惠州'] job_name = '数据分析' list_urls=[] for i in place_name: url='http://sou.zhaopin.com/jobs/searchresult.ashx?jl='+str(i)+'&kw='+job_name list_urls.append(url) return list_urls<file_sep>/ZYDMALL/zydmall产品价格调整监控/test1.py import requests import re from multiprocessing import Pool import time from bs4 import BeautifulSoup import pymysql def get_attributes_name(content): soup=BeautifulSoup(content,'html.parser') category_name=soup.find('div',attrs={'class':'page_posit'}).find_all('a')[3].text print("category_3_name:%s"%category_name) attrs=soup.find('div',attrs={'class':'product_table'}).find('table').find_all('tr')[0].find_all('th') print(len(attrs)) attrs_name=[] #只取第9个以后的属性名称 for i in range(9,len(attrs)): attr_name=attrs[i].text attrs_name.append(attr_name) return category_name,attrs_name def insert_attr_data(prt_id,good_id,category_name,attr_name,attr_value,order_num): db = pymysql.connect("localhost", "root", "123456", "zydmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into category_attribute_link (prt_id,good_id,category_name,attr_name,attr_value,order_num) values('%s','%s','%s','%s','%s','%s')" %(prt_id,good_id,category_name,attr_name,attr_value,order_num) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_pid(url,good_id): s = requests.get(url) content = s.content.decode('utf-8') #print(content) #根据分析ajax请求,需要两个参数,一个goods_id,一个pid #goods_id直接可以从url中获取,pid则需要正则分析源码 soup=BeautifulSoup(content,'html.parser') time=1 try: pid=soup.find('input',attrs={'id':'J-basketNum'}).get('data-id') except AttributeError as e: time+=1 print(e) if time>3: exit() else: return get_pid(url,good_id) ''' pat1=re.compile('var pid = parseInt') m1=pat1.search(content) #print(m1) pat2 = re.compile(r"\(document\).ready") m2 = pat2.search(content) #print(m2) pid=content[m1.end()+2:m2.start()-3] pid=str(pid).replace("');","").replace("\r\n","") print(pid) ''' #图片需要在requests请求主页面时才会加载的吧 num=get_prt_imgs(content, good_id) get_content(content, good_id, num) #我要获取一遍属性名称 category_name, attrs_name=get_attributes_name(content) return pid,category_name, attrs_name def get_prt_imgs(html,good_id): soup = BeautifulSoup(html, 'html.parser') thumblists = soup.find('ul', attrs={'id': 'thumblist'}).find_all('li') num = 0 for li in thumblists: num += 1 img = li.find('img').get('big') original_img_url = img img_name = img[img.rindex("/") + 1:100] img_path = "/upload/prt/zyd/" + good_id + "/" + img_name img_no = num img_type = "prt_img" #print(img_no, img_name, img_path, original_img_url) insert_prt_img(good_id, img_name, img_path, original_img_url, img_no, img_type) #print("++++++++++++++++") return num def insert_prt_img(good_id,img_name,img_path,original_img_url,img_no,img_type): db = pymysql.connect("localhost", "root", "123456", "zydmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_img_info(prt_id,img_name,img_path,original_url,img_num,img_type)" \ "values('%s','%s','%s','%s','%d','%s')" \ % (good_id, img_name, img_path, original_img_url, img_no, img_type) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_json_data(url): s = requests.get(url) content = s.content.decode('utf-8') #print(content) #full_content="<html><head></head><body><table>"+content+"</table></body></html>" content=content.replace("<div>","").replace("</div>","") #print(content) return content def insert_prt_data(prt_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit): db = pymysql.connect("localhost", "root", "123456", "zydmall") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into prt_data (prt_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit)"\ "values('%s','%s','%s','%s','%s','%s','%s','%s')" %(prt_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_prt_data-------Error------Message--------:' + str(err)) cursor.close() db.close() def get_content(html,good_id,num): # 里面分为两块,一块是图片的获取,另一块是整个content的获取,包括修改图片路径 # 1.内容html数据 soup = BeautifulSoup(html, 'html.parser') original_content = soup.find('div', attrs={'class': 'tab_contain'}) # 还需要replace掉所有的图片路径 imgs = original_content.find_all('img') print("当前详情内容里面一共有%s张图片" % str(len(imgs))) # num=0 for img in imgs: num += 1 # 图片的属性,需要名称,url img_title = img.get('title') if img_title == None: img_title = img.get('alt') if img_title == None: img_title = img.get('name') img_title = str(img_title).replace(".jpg", "") original_img_url = img.get('src') try: img_url = original_img_url[0:original_img_url.rindex("?")] except: img_url = original_img_url img_name = img_url[img_url.rindex('/') + 1:100] img_path = "/upload/prt/zyd/" + good_id + "/" + img_name #print(num, img_title, img_name, img_path, img_url) img_no = num img_type = "content" insert_prt_img(good_id, img_name, img_path, img_url, img_no, img_type) # 对content数据进行replace original_content = str(original_content).replace(original_img_url, img_path) insert_prt_desc(good_id, original_content) #print(original_content) #print("++++++++++++++++") def insert_prt_desc(prt_id,prt_desc): db = pymysql.connect("localhost", "root", "123456", "zydmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into prt_desc(prt_id,prt_desc)" \ "values('%s','%s')" \ % (prt_id, prt_desc) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_good_id(solution): db = pymysql.connect("localhost", "root", "123456", "zydmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select good_id from goods_lists_info where status=0 "+solution+" limit 1" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def update_good_id_status(good_id): db = pymysql.connect("localhost", "root", "123456", "zydmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update goods_lists_info set status=1 where good_id='%s' " %good_id try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_good_cnt(): db = pymysql.connect("localhost", "root", "123456", "zydmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select count(good_id) as cnt from goods_lists_info where status=0 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def main(id): # 获取good_id if id ==0: solution="order by table_id" else: solution="order by table_id desc" goods_data = get_good_id(solution) good_id = goods_data[0][0] print("loading the %s ......" % good_id) # 尝试requests请求页面的返回结果 # good_id=str(3752) url = "https://www.zydmall.com/detail/good_" + good_id + ".html" pid, category_name, attrs_name = get_pid(url,good_id) print(pid, category_name, attrs_name) ajax_url = "https://www.zydmall.com/ashx/detail_products.ashx?goods_id=" + good_id + "&pid=" + pid print(ajax_url) content = get_json_data(ajax_url) # 分析html数据 soup = BeautifulSoup(content, 'html.parser') trs = soup.find_all('tr', attrs={'class': 'pro_list'}) print("共%s条SKU数据" % str(len(trs))) for tr in trs: # print(tr) # tr=str(tr).replace("<div>","").replace("</div>","") tds = tr.find_all('td') po_number = tds[0].find('a').text prt_url = tds[0].find('a').get('href') prt_id = prt_url.split('/')[-1].split('.')[0].split('_')[-1] prt_type = tds[1].find('p').text face_price = tds[2].text discount_price = tds[3].text weight = tds[7].text unit = tds[8].text # print(prt_id,po_number,prt_url,prt_type,face_price,discount_price,weight,unit) # ---------------------保存商品基础属性 insert_prt_data(prt_id, po_number, prt_url, prt_type, face_price, discount_price, weight, unit) for i in range(9, len(tds)): attr_value = tds[i].text # print(attr_value) attr_name = attrs_name[i - 9] # ------------------保存商品属性名称,属性值 insert_attr_data(prt_id, good_id, category_name, attr_name, attr_value, str(i - 8)) update_good_id_status(good_id) print("------------------------------ ") if __name__=="__main__": cnt_data=get_good_cnt() cnt=cnt_data[0][0] for_times=round(int(cnt)/2,0)+1 for x in range (int(for_times)): start = time.time() p = Pool() for i in range(2): p.apply_async(func=main, args=(i,)) p.close() p.join() end = time.time() <file_sep>/untitled/Selenium/猫狗充电宝成交额/充电宝成交额-mainV1.0.py #1. 充电宝的品牌获取,包括天猫、淘宝、京东、1688 #TMALL------喵~ #url="https://list.tmall.com/search_product.htm?q=%B3%E4%B5%E7%B1%A6&type=p&spm=a220m.1000858.a2227oh.d100&from=.list.pc_1_searchbutton" import time from selenium import webdriver def get_brand_info(): #1. 点击“更多” #2. 获取页面的li标签 more=driver.find_element_by_css_selector(".j_More.avo-more.ui-more-drop-l").click() pass if __name__=="__main__": driver=webdriver.Firefox() url="https://list.tmall.com/search_product.htm?q=%B3%E4%B5%E7%B1%A6&type=p&spm=a220m.1000858.a2227oh.d100&from=.list.pc_1_searchbutton" driver.get(url) get_brand_info() <file_sep>/MMBAO/产品库数据校验/P1-将spu_id回填更新.py #分为两块,一块是从mysql取出整个产品库模板的数据 #另一块是从oracle的产品库数据表,对每条数据进行核对 #1. excel数据存储,新建数据库,专门存放 import pymysql import cx_Oracle import time class mysql_data(): def mysql_spu_data(self): db = pymysql.connect("localhost", "root", "123456", "产品库", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select spu_id,spu标题 from spu表 " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() class oracle_data(): def oracle_spu_data(self,date_time): db = cx_Oracle.connect('mmbao2_bi/mmbao2_bi@beta.mmbao.com:21252/mmbao2b2c') #print(db.version) cursor = db.cursor() sql = "SELECT dqs_prt_id,spu_title FROM mmbao2.t_dqs_product where create_date>to_date('%s','yy/MM/dd') and is_delete=0 order by create_date " %(date_time) #因为还得分为新增和更新 print(sql) cursor.execute(sql) data = cursor.fetchall() return data if __name__=="__main__": #想了想还是得标注日期进行筛选 date_time='2017/11/29' mysql=mysql_data() oracle=oracle_data() ################################################################## #spu表数据 data=mysql.mysql_spu_data() print('搜索出结果%s条', str(len(data))) #for i in range (len(data)): #spu_id=data[i][0] #spu_title=data[i][1] #print(spu_id,spu_title) data2=oracle.oracle_spu_data(date_time) print('搜索出结果%s条',str(len(data2))) time.sleep(5) ################################################################## <file_sep>/找电缆EXCEL处理2.0新版/布电线/对删减的数据生成excel.py #将新增的数据,从zhaodianlan_data的状态为2的数据,转换成excel import pymysql import xlwt def get_excel_name_from_zhaodianlan_template(): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select excel_name from zhaodianlan_template where status=0 and excel_name like '%中高压电缆%' group by excel_name" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_excel_name_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def get_data_from_zhaodianlan_template(excel_name): db = pymysql.connect("localhost", "root", "123456", "mmbao", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select * from zhaodianlan_template where status=0 and excel_name='%s'" %excel_name try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #从数据表中获取所有的恶excel_name data_excel_name=get_excel_name_from_zhaodianlan_template() for m in range (len(data_excel_name)): excel_name=data_excel_name[m][0] print(excel_name) data=get_data_from_zhaodianlan_template(excel_name) wbk = xlwt.Workbook() sheet1 = wbk.add_sheet('sheet 1') sheet1.write(0, 0, "类目") sheet1.write(0, 1, "型号") sheet1.write(0, 2, "规格") sheet1.write(0, 3, "电压") sheet1.write(0, 4, "厂商") sheet1.write(0, 5, "品牌") sheet1.write(0, 6, "省") sheet1.write(0, 7, "市") sheet1.write(0, 8, "价格(元/单位)") sheet1.write(0, 9, "商品有效期") sheet1.write(0, 10, "是否上架") sheet1.write(0, 11, "交货期(天)") sheet1.write(0, 12, "权重值") sheet1.write(0, 13, "参与均价计算") sheet1.write(0, 14, "属性") sheet1.write(0, 15, "库存") sheet1.write(0, 16, "生产年份") new_path = "D:\BI\找电缆\待删减\\" + excel_name.replace("xlsx", "xls") wbk.save(new_path) x_num = 1 for i in range (len(data)): sheet1.write(i+1, 0, data[i][2]) sheet1.write(i+1, 1, data[i][3]) sheet1.write(i+1, 2, data[i][4]) sheet1.write(i+1, 3, data[i][5]) sheet1.write(i+1, 4, data[i][6]) sheet1.write(i+1, 5, data[i][7]) sheet1.write(i+1, 6, data[i][8]) sheet1.write(i+1, 7, data[i][9]) sheet1.write(i+1, 8, data[i][10]) sheet1.write(i+1, 9, data[i][11]) sheet1.write(i+1, 10, data[i][12]) sheet1.write(i+1, 11, data[i][13]) sheet1.write(i+1, 12, data[i][14]) sheet1.write(i+1, 13, data[i][15]) sheet1.write(i+1, 14, data[i][16]) sheet1.write(i+1, 15, data[i][17]) new_path = "D:\BI\找电缆\待删减\\" + excel_name.replace("xlsx", "xls") wbk.save(new_path)<file_sep>/日常工作/筛选电线类型所对应商品销量-史旭东-2018年5月9日0918.py import pymysql def find_keywords(): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select keyword from keywords_0509" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def get_prt_info(keyword): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select 标题,购买数量,商品属性,month,价格 from prt_sku_0509 where replace(标题,' ','') like '%"+keyword+"%' and status=0" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def insert_type_data(keyword,sale_cnt,sku_title,month,price): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "insert into keyword_sku_0509 (keyword,sale_cnt,sku_title,month,price) values('%s','%s','%s','%s','%s')" %(keyword,sale_cnt,sku_title,month,price) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() def update_status(keyword): db = pymysql.connect("localhost", "root", "123456", "daily_work") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_sku_0509 set status=1 where replace(标题,' ','') like '%"+keyword+"%' " try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('--------insert_spu_data-------Error------Message--------:' + str(err)) db.close() cursor.close() if __name__=="__main__": keyword_data=find_keywords() for i in range (len(keyword_data)): keyword=keyword_data[i][0] print("keyword:",keyword) prt_info=get_prt_info(keyword) title_li=[] sale_cnt_li=[] sku_title_li=[] for x in range (len(prt_info)): title=prt_info[x][0] sale_cnt=prt_info[x][1] sku_title=prt_info[x][2] month = prt_info[x][3] price=prt_info[x][4] print(title,sale_cnt,sku_title,month,price) insert_type_data(keyword,sale_cnt,sku_title,month,price) update_status(keyword) <file_sep>/untitled/Requests/工品汇Requests框架V1.0.py #登录模块 import requests from bs4 import BeautifulSoup url="http://www.vipmro.com/login" UA="Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0" header = { "User-Agent" : UA, "Referer": "http://www.vipmro.com/", "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3" } vipmro_session = requests.Session() f = vipmro_session.get(url, headers=header) soup = BeautifulSoup(f.content, "html.parser") print(soup) uid=soup.find("input",attrs={'class':'login-text m-top5 act-bg J_userName'}) user_name=uid.get('') <file_sep>/工品汇/正泰.NET/spu_filter把sku分类.py import pymysql import time def get_spu_data(): db = pymysql.connect("localhost", "root", "123456", "chint_vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select spu_id,category_name,img_url,prt_name from spu_filter" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_spu_sku(category_name,img_url,prt_name): db = pymysql.connect("localhost", "root", "123456", "chint_vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="select a.prt_id from vipmro_net_data a "\ "left join vipmro_net_url c on a.cate_id=c.table_id " \ "left join vipmro_net_img_info d on a.prt_id=d.prt_id " \ "where cate_2_name ='"+category_name+"' "\ "and original_url='"+img_url+"' " \ "and prt_name like '"+prt_name+"%' " #print(sql) try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def insert_sku_spu_id(sku_id,spu_id,prt_name): db = pymysql.connect("localhost", "root", "123456", "chint_vipmro") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql="insert into spu_sku_link (sku_id,spu_id,spu_title) values('%s','%s','%s')" %(sku_id,spu_id,prt_name) #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #获取spu_filter表的数据 spu_data=get_spu_data() for i in range (len(spu_data)): spu_id=spu_data[i][0] category_name=spu_data[i][1] img_url=spu_data[i][2] prt_name=spu_data[i][3] print(spu_id,category_name,img_url,prt_name) #将每一条数据带入到sql脚本中查询 sku_data=find_spu_sku(category_name, img_url, prt_name) for x in range (len(sku_data)): sku_id=sku_data[x][0] print(sku_id,spu_id) insert_sku_spu_id(sku_id,spu_id,prt_name) #time.sleep(10) <file_sep>/untitled/Selenium/米思米/test2.py import time import pyautogui import xlrd import xlsxwriter from untitled.Selenium import webdriver def print_xls(): data=xlrd.open_workbook(r"D:\BI\米思米\test.xlsx") #打开excel table=data.sheets()[0] #打开excel的第几个sheet nrows=table.nrows #捕获到有效数据的行数 PRT_NAME=[] for i in range(nrows): ss=table.row_values(i) #获取一行的所有值,每一列的值以列表项存在 #print ss PRT_NAME.append(ss) return PRT_NAME def login(): print('准备页面跳转--登录') driver.get('https://cn.misumi-ec.com/mydesk2/s/login') time.sleep(3) #1. 点击LOGO driver.find_element_by_class_name('header__logo').click() time.sleep(3) #2. 切换到Login页面 handles = driver.window_handles driver.switch_to.window(handles[0]) time.sleep(1) #3. 登录 driver.find_element_by_class_name('id').send_keys('<PASSWORD>') driver.find_element_by_class_name('pass').send_keys('<PASSWORD>') driver.find_element_by_css_selector('.loginBtn.VN_opacity').click() time.sleep(10) #4. 刷新页面 #driver.get('http://cn.misumi-ec.com/vona2') time.sleep(5) driver.get('http://cn.misumi-ec.com') #2. #source=driver.page_source #print(source) def Baojia(): driver.get("http://cn.misumi-ec.com") time.sleep(5) print('点击首页的报价按钮') driver.find_element_by_xpath("//div[@class='directInfo__main']/ul/li/a[@class='VN_opacity']").click() time.sleep(10) print('等待中---准备点击Excel获取') try: driver.find_element_by_xpath("//div[@class='tableGreen marginT15']/div/span[@id='copyAndPasteCommand']").click() except: time.sleep(5) driver.find_element_by_xpath("//div[@class='tableGreen marginT15']/div/span[@id='copyAndPasteCommand']").click() time.sleep(3) #嫁接 click_title() def click_title(): handles = driver.window_handles print(handles) driver.switch_to.window(handles[2]) #输入text内容,从Excel中获取list进行批量插入,一次500条 #test_text="DZ47-60 1P C16,DZ47-60 1P C16,正泰(CHINT),1" text = "" for i in range (len(PRT_NAME)): print(PRT_NAME[i]) text=text+"\n"+str(PRT_NAME[i]).replace("['",'').replace("']",'') print(text) driver.find_element_by_xpath("//div[@class='tableGrey marginT10']/table/tbody/tr/td/textarea[@name='uploadText']").send_keys(text) driver.find_element_by_id('DelimiterCOMMA').click() #下一步 driver.find_element_by_id('nextCommand').click() time.sleep(4) #由于下拉选择框的点击异常暂未解决,采药autogui方式试用 table_a=driver.find_element_by_css_selector('.tableGrey.marginT15.setItem_scroll') print(table_a.text) t1=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='columnList_0.uploadItemName']").click() time.sleep(1) pyautogui.click(171,290) #print(t1.text) print('第二个下拉选择框') time.sleep(0.5) t2=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='<EMAIL>']").click() time.sleep(0.5) pyautogui.click(343, 313) #print(t2.text) time.sleep(0.5) t3=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='<EMAIL>']").click() time.sleep(0.5) pyautogui.click(500, 360) time.sleep(0.5) t4=table_a.find_element_by_xpath("//tbody/tr/td/select[@name='<EMAIL>']").click() time.sleep(0.5) pyautogui.click(650, 320) time.sleep(2) driver.find_element_by_id('nextCommand').click() time.sleep(2) driver.find_element_by_id('nextCommand').click() time.sleep(2) #以上属于搞事,准备返回主页面流程 handles = driver.window_handles print(handles) driver.switch_to.window(handles[0]) print('#进入报价结果页面') driver.find_element_by_xpath("//div[@id='contentsArea']/form/div[@class='floatR']/a[@class='btnNext']").click() time.sleep(10) table=driver.find_element_by_xpath("//div[@id='table_Product']/table") for i in range (2,len(PRT_NAME)+2): price=table.find_element_by_xpath("//tbody/tr["+str(i)+"]/td[4]").text price=price.split("\n") price_1.append(price[0]) price_2.append(price[1]) print(price_1) print(price_2) def save_excel(fin_result1, fin_result2): # 将抓取到的信息存储到excel当中 book = xlsxwriter.Workbook(r'D:\BI\米思米\test2.xlsx' ) # 默认存储在桌面上 tmp = book.add_worksheet('sheet2') for i in range(0, len(fin_result1)): tmp.write(i, 1, fin_result1[i]) tmp.write(i, 2, fin_result2[i]) if __name__=="__main__": price_1=[] price_2 = [] PRT_NAME=print_xls() print(PRT_NAME) driver=webdriver.Firefox() login() #driver.find_element_by_id('keyword_input').send_keys('DZ47-60 3P D20') Baojia() save_excel(price_1,price_2) <file_sep>/untitled/Requests/delixi官方店数据获取.py #www.de-ele.com #2017年8月3日14:27:56 #新增prt_id的获取 from urllib import request from bs4 import BeautifulSoup import pymysql import time import multiprocessing import threading import datetime def getHtml(url): req=request.Request(url) req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0") req.add_header("Host","www.de-ele.com") response=request.urlopen(req) html=response.read().decode('utf-8') #print(html) return html #通过html,获取一级类目 class get_cat1(): #将一级类目数据导入数据表 def insert_cat1(self,cat1_id,cat1_name,cat1_href): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into cat1_info " \ " (cat1_id,cat1_name,cat1_href)" \ " values('%s','%s','%s')" \ % (cat1_id,cat1_name,cat1_href) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() #使用BeautifulSoup查找关键类目信息 def find_data(self,url,html): soup=BeautifulSoup(html,'lxml') div_cats=soup.find('div',attrs={'class':'my_left_category float-l'}).find_all('div',attrs={'class':'my_left_cat_list'}) for div_cat in div_cats: span_title = div_cat.find('h3', attrs={'class': 'cat1'}).find('span', attrs={'class': 'title'}) cat1=span_title.text cat1_href=url+span_title.find('a')['href'] cat1_id=str(span_title.find('a')['href']).replace("/list_","").replace(".htm","") print(cat1,cat1_href) self.insert_cat1(cat1_id,cat1,cat1_href) #获取数据中的状态为0的数据count,获取状态为0的第一条数据 class get_table_info(): def get_cat_href(self,sql_content_select): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql=sql_content_select try: execute = cursor.execute(sql) cat1_href = cursor.fetchmany(execute) return cat1_href except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() def update_status_to_log(self,table_name,where_solution,cat1_href,status): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update "+table_name+" set status="+str(status)+" where "+where_solution+"='"+cat1_href+"'" #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def update_pre_status(self,table_name,where_solution,cat1_href): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="update "+table_name+" set pre_status=1 where "+where_solution+"='"+cat1_href+"'" #print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def get_url_cnt(self,table_name): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql="select count(*) as cnt from "+table_name+" where status=0 " #print(sql) try: execute=cursor.execute(sql) cnt=cursor.fetchmany(execute) return cnt except Exception as err: # 如果发生错误则回滚 db.rollback() print('---------------Error------Message--------:' + str(err)) # 关闭数据库连接 db.close() cursor.close() #从cat1_href的每个链接中,得到产品型号的数据 #本来想增加一个属性值获取的,但是后来发现属性值需要在下一级链接(即型号层的数据中进行获取,不同型号的商品,属性不同),需要另起一次循环 class get_cat1_detail(): #获取型号数据 def get_series(self,cat1_id,html): soup=BeautifulSoup(html,'lxml') series_lists=soup.find('ul',attrs={'id':'ul_subcategory'}).find_all('div',attrs={'class':'cats_icon'}) print("inserting the series data to table [de-ele.series_info]") for series in series_lists: series_a=series.find('a',attrs={'class':'pic'}) img_url='http://www.de-ele.com'+series_a.find('img')['src'] #图片url链接 img_name=img_url[img_url.rindex("/") + 1:img_url.rindex(".") + 4] img_path='series'#图片存储路径、类型 series_href='http://www.de-ele.com'+series.find_all('a')[1]['href'] #型号跳转的子链接 #cat1_id=cat1_id series_name=series.find_all('a')[1].text #型号名称 series_id=series_a['href'].replace("/list_","").replace(".htm","") #型号ID #print('testing...', series_id,series_name,cat1_id,img_url,img_path,series_href) #print("inserting the series data to table [de-ele.series_info]") self.insert_series_info(series_id, series_name, cat1_id, img_name,img_url, img_path, series_href) #导入series数据 def insert_series_info(self,series_id,series_name,cat1_id,img_name,img_url,img_path,series_href): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into series_info " \ " (series_id,series_name,cat1_id,img_name,img_url,img_path,series_href)" \ " values('%s','%s','%s','%s','%s','%s','%s')" \ % (series_id,series_name,cat1_id,img_name,img_url,img_path,series_href) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() class get_series_detail(): def get_series_attrs(self,html,series_id): soup=BeautifulSoup(html,'lxml') div_lists=soup.find_all('dl',attrs={'class':'attribute_dl'}) #print(str(len(div_lists))+"类属性") for div_list in div_lists: attr_name=div_list.find('dt',attrs={'class':'attribute_name'}).text attr_name=attr_name.replace(':','') attr_values=div_list.find('dd',attrs={'class':'attribute_val'}).find_all('a') for i in range(len(attr_values)): attr_value=attr_values[i].text #print(attr_name,attr_value) order_num=str(i+1) self.insert_attr_data(attr_name,attr_value,series_id,order_num) #获取商品列表中的商品简单的信息,如名称,url等 def get_series_detail(self,html,series_id): soup = BeautifulSoup(html, 'lxml') div_lists=soup.find('div',attrs={'class','category_pro_list2 pic'}).find_all('li') for div_list in div_lists: img_url='http://www.de-ele.com'+div_list.find('img')['src'] img_name = img_url[img_url.rindex("/") + 1:img_url.rindex(".") + 4] #print(img_url) prt_name=div_list.find('div',attrs={'class':'category_pro_name'}).find('a').text #print(prt_name) prt_href='http://www.de-ele.com'+div_list.find('div',attrs={'class':'category_pro_name'}).find('a')['href'] #print(prt_href) img_path='prt_list' prt_id=div_list.find('div',attrs={'class':'category_pro_name'}).find('a')['href'].replace("/","").replace(".htm","") prt_id=int(prt_id) self.insert_prt_data(prt_id,prt_name,prt_href,series_id,img_name,img_url,img_path) def insert_attr_data(self,attr_name,attr_value,series_id,order_num): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into attr_info " \ " (attr_name,attr_value,series_id,order_num)" \ " values('%s','%s','%s','%s')" \ % (attr_name,attr_value,series_id,order_num) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def insert_prt_data(self,prt_id,prt_name,prt_href,series_id,img_name,img_url,img_path): db = pymysql.connect("localhost","root","123456","de-ele",charset="utf8" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 sql="insert into prt_info " \ " (prt_id,prt_name,prt_href,series_id,img_name,img_url,img_path)" \ " values('%d','%s','%s','%s','%s','%s','%s')" \ % (prt_id,prt_name,prt_href,series_id,img_name,img_url,img_path) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:'+str(err)) db.close() cursor.close() def get_page_num(self,html): soup = BeautifulSoup(html, 'lxml') # 判断下有没有翻页 try: page_span = soup.find('span', attrs={'class': 'page-skip'}).text page_num = str(page_span)[3:6] page_num = page_num.replace("页", "").replace(" ", "") except: page_num = '0' #print("共" + str(page_num) + "页数据") return page_num def exec_multiprocessing(url,series_id): name=multiprocessing.current_process().name print("processing "+name) html=getHtml(str(url)) #print("html") series_data=get_series_detail() series_data.get_series_attrs(html, series_id) series_data.get_series_detail(html, series_id) try: page_num=int(series_data.get_page_num(html)) except: page_num=0 if int(page_num) > 1: for i in range(int(page_num)-1): url=url+"?pageindex="+str(i+2) html = getHtml(str(url)) print('loading the next page '+url) series_data.get_series_detail(html, series_id) time.sleep(5) if __name__=="__main__": ''' #-------------------------------------------------------------------------------------------------------------- logging_time = datetime.datetime.now() print('part 1 begining at %s'%(str(logging_time))) url="http://www.de-ele.com" html=getHtml(url) #执行有关一级类目的操作类get_cat1() get_Cat1=get_cat1() get_Cat1.find_data(url,html) print("waiting for excute the next step <get data from tables>...") time.sleep(0.5) logging_time = datetime.datetime.now() print('part 1 is ended at %s'%(str(logging_time))) ''' #-------------------------------------------------------------------------------------------------------------- #为了后续不出现冗余代码,所以将class-->get_table_info()给参数化了,所以需要增加一个数据字典类型excute_cat_data={} #执行一级类目链接内容,包括属性、型号 logging_time = datetime.datetime.now() print('part 2 is begining at %s'%(str(logging_time))) get_mysql=get_table_info() excute_cat_data={ 'select':"select cat1_id,cat1_href from cat1_info where status=0 limit 1", 'table_name':"cat1_info", 'where_solution':'cat1_href' } #print(excute_cat_data['table_name']) cnt_t=get_mysql.get_url_cnt(excute_cat_data['table_name']) cnt=int(cnt_t[0][0]) print('total counts:',cnt) #对cat1_href进行循环,获取产品型号的数据,存表 for i in range (cnt): cat_t=get_mysql.get_cat_href(excute_cat_data['select']) cat_id_t=cat_t[0][0] cat_href_t=cat_t[0][1] cat_id=str(cat_id_t) cat_href = str(cat_href_t) print(cat_href_t) print("loading the url's html data..." ) cat_html=getHtml(cat_href) #print(cat_html) get_Detail=get_cat1_detail() get_Detail.get_series(cat_id,cat_html) #变更当前执行记录的状态 status=1 get_mysql.update_status_to_log(excute_cat_data['table_name'],excute_cat_data['where_solution'],cat_href,status) time.sleep(5) logging_time = datetime.datetime.now() print('part 2 is ended at %s'%(str(logging_time))) #-------------------------------------------------------------------------------------------------------------- #遍历series_href,准备进行产品型号下,商品信息,及商品属性进行获取 #按照目前思路,对于商品只会精确到url,对于url里面的详细页数据(包括属性值、价格、插图之类的),建议通过第二部分的脚本去做,不建议放在同一个脚本里 logging_time = datetime.datetime.now() print('part 3 is begining at %s'%(str(logging_time))) get_mysql_series = get_table_info() excute_series_data = { 'select': "select series_id,series_href from series_info where pre_status=0 and status=0 limit 1", 'table_name': "series_info", 'where_solution': 'series_href' } cnt_t_2=get_mysql_series.get_url_cnt(excute_series_data['table_name']) cnt_series=int(cnt_t_2[0][0]) print('total counts:', cnt_series) #多线程循环内容 thread_num=5 #线程数量 for i in range(int(cnt_series/thread_num)): #希望通过多线程进行处理,通过for循环,启动5个线程 threads = [] series_ids=[] series_hrefs=[] for j in range (thread_num): cat_t=get_mysql_series.get_cat_href(excute_series_data['select']) series_id=cat_t[0][0] series_href=cat_t[0][1] print(series_id,series_href) get_mysql_series.update_pre_status(excute_series_data['table_name'], excute_series_data['where_solution'], series_href) series_ids.append(series_id) series_hrefs.append(series_href) #print(series_hrefs[0]) worker1 = multiprocessing.Process(name='worker 1', target=exec_multiprocessing, args=(str(series_hrefs[0]),str(series_ids[0]),)) worker1.start() worker2 = multiprocessing.Process(name='worker 2', target=exec_multiprocessing, args=(str(series_hrefs[1]),str(series_ids[1]),)) worker2.start() worker3 = multiprocessing.Process(name='worker 3', target=exec_multiprocessing, args=(str(series_hrefs[2]),str(series_ids[2]),)) worker3.start() worker4 = multiprocessing.Process(name='worker 4', target=exec_multiprocessing, args=(str(series_hrefs[3]),str(series_ids[3]),)) worker4.start() worker5 = multiprocessing.Process(name='worker 5', target=exec_multiprocessing, args=(str(series_hrefs[4]),str(series_ids[4]),)) worker5.start() worker1.join() for series_href in series_hrefs: status=1 get_mysql_series.update_status_to_log(excute_series_data['table_name'],excute_series_data['where_solution'],series_href,status) #get_mysql_series.update_status_to_log(excute_series_data['table_name'],excute_series_data['where_solution'],series_href,status) print('-----------------------') time.sleep(5) #对于无法通过多线程执行的记录,即/5的余数 remainder=cnt_series%thread_num print('剩余'+str(remainder)+"无法通过multiprocessing处理") for x in range (remainder): cat_t = get_mysql_series.get_cat_href(excute_series_data['select']) series_id = cat_t[0][0] series_href = cat_t[0][1] print(series_id, series_href) get_mysql_series.update_pre_status(excute_series_data['table_name'], excute_series_data['where_solution'],series_href) worker = multiprocessing.Process(name='worker remaining', target=exec_multiprocessing, args=(str(series_href),str(series_id),)) worker.start() worker.join() status = 1 get_mysql_series.update_status_to_log(excute_series_data['table_name'], excute_series_data['where_solution'],series_href, status) logging_time = datetime.datetime.now() print('part 3 is ended at %s'%(str(logging_time))) <file_sep>/TMALL/数据分析架构模式化/针对legrand进行流交互尝试/test.py import requests def get_content(url): s = requests.get(url, headers=headers) content = s.content.decode('gbk') print(content) return content if __name__=="__main__": headers = { "Host":"detailskip.taobao.com", "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Referer": "https://item.taobao.com/item.htm?spm=a21cw.8035592.338071.8.733a6565J867kz&id=564438588427", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0" } url="https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?itemId=564438588427&sellerId=2597438137&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,upp,activity,fqg,zjys,couponActivity,soldQuantity,originalPrice,tradeContract&callback=onSibRequestSuccess" get_content(url)<file_sep>/untitled/Requests/test.py import sys,time for i in range(101): sys.stdout.write("\r") #每一次清空原行 sys.stdout.write("%s | %s" % (int(i/100*100),int(i/100*100)*"#")) sys.stdout.flush() #强制刷新屏幕 time.sleep(1) #每隔0.5秒打印一次<file_sep>/TMALL/罗格朗根据商品名称区分系列.py import pymysql def get_series_info(): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select series,color,new_color from series_info " try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_useful_data(series_name,color,new_color): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_lists_info set series='%s',color='%s' where prt_title like '%%%s%%' and prt_title like '%%%s%%'" %(series_name,new_color,series_name,color) print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def find_useful_series_data(series_name): db = pymysql.connect("localhost", "root", "123456", "tmall") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update prt_lists_info set series='%s' where prt_title like '%%%s%%'" %(series_name,series_name) print(sql) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": #获取系列数据 series_data=get_series_info() for i in range (len(series_data)): series_name=series_data[i][0] color=series_data[i][1] new_color=series_data[i][2] print(series_name,color,new_color) find_useful_data(series_name,color,new_color) for i in range (len(series_data)): series_name=series_data[i][0] color=series_data[i][1] new_color=series_data[i][2] print(series_name,color,new_color) if series_name=="": pass else: find_useful_series_data(series_name) <file_sep>/JD后台/JD前台匹配商品url.py import pymysql import time from urllib import parse import random from bs4 import BeautifulSoup from selenium import webdriver class main(): def s(self,a,b): ti=random.randint(a,b) time.sleep(ti) def find_info(self,content,prt_name,prt_code): soup=BeautifulSoup(content,'html.parser') prt_lists=soup.find_all('li',attrs={'class':'jSubObject'}) print("current page have %s records " % (str(len(prt_lists)))) for i in range (len(prt_lists)): price=prt_lists[i].find('div',attrs={'class':'jGoodsInfo'}).find('div',attrs={'class':'jdPrice'}).find('span',attrs={'class':'jdNum'}).text prt_title=prt_lists[i].find('div',attrs={'class':'jGoodsInfo'}).find('div',attrs={'class':'jDesc'}).find('a').text sku=prt_lists[i].find('div',attrs={'class':'jGoodsInfo'}).find('div',attrs={'class':'jDesc'}).find('a').get('href') print(prt_title,price) if prt_title==prt_name: self.update_data(prt_name,price,prt_code,sku) def update_data(self,prt_name,price,prt_code,sku): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "update jd_prt_url set new_jd_price='%s',sku='%s' where prt_name='%s' and prt_code='%s'" %(price,sku,prt_name,prt_code) try: cursor.execute(sql) db.commit() except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() def get_keywords(self): db = pymysql.connect("localhost", "root", "123456", "jd_vcp") cursor = db.cursor() db.set_charset("utf8") cursor.execute("SET NAMES utf8;") cursor.execute("SET CHARACTER SET utf8;") cursor.execute("SET character_set_connection=utf8;") sql = "select prt_name,prt_code from jd_prt_url where sku =''" try: execute = cursor.execute(sql) data = cursor.fetchmany(execute) return data except Exception as err: db.rollback() print('---------------Error------Message--------:' + str(err)) cursor.close() db.close() if __name__=="__main__": # selenium登录 browser = "Firefox" if browser == "Chrome": options = webdriver.ChromeOptions() # options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记 options.add_argument( '--user-data-dir=C:/Users/Coco/AppData/Local/Google/Chrome/User Data/Default') # 设置成用户自己的数据目录 driver = webdriver.Chrome(chrome_options=options) else: if browser == "Firefox": driver = webdriver.Firefox() else: driver = webdriver.PhantomJS() main=main() #url="http://www.baidu.com" url="https://mall.jd.com/view_search-877400-1000097104-1000097104-0-0-0-0-1-1-60.html?keyword=" data=main.get_keywords() for i in range (len(data)): prt_name=data[i][0] prt_code=data[i][1] print(prt_name,prt_code) driver.get(url) # 等待用户自己登陆 time.sleep(5) driver.find_element_by_id('key01').send_keys(prt_name) time.sleep(1) driver.find_element_by_class_name('button01').click() time.sleep(3) # 判断是否登陆成功 page = driver.page_source time.sleep(2) main.find_info(page, prt_name, prt_code)<file_sep>/地址拆分/查找涵盖公司的地址信息.py import pymysql import re def get_address(): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,address from address_data_jd where address like '%公司%' and status is null" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def find_data_from_address(type,pname): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "select table_id,address from address_data_jd where address like '%"+pname+"%' and "+type+" is null" try: cursor.execute(sql) data = cursor.fetchall() return data except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() def update_providence(address,company_name): db = pymysql.connect("localhost", "root", "123456", "tianyancha", charset="utf8") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() sql = "update address_data_jd set company_name='%s',status=1 where address='%s'" %(company_name,address) try: cursor.execute(sql) db.commit() except Exception as err: # 如果发生错误则回滚 db.rollback() print('--------get_data_from_zhaodianlan_template-------Error------Message--------:' + str(err)) # 关闭数据库连接 cursor.close() db.close() if __name__=="__main__": #将address保存到数据表,使用省进行轰炸,把结果更新到数据表,然后再用市轰炸 #取出所有的省份 data_address=get_address() for i in range (len(data_address)): table_id=data_address[i][0] address=data_address[i][1] try: company_name= re.search(r'[^号,幢,道,镇,县,园,区,栋,层]+$', address)[0] except: company_name=address #company_name=company_name[0:company_name.rindex("(")] #company_name=company_name.replace("(","").replace(")","").replace(")","") try: company_name = company_name[0:company_name.rindex("公司")+2] except: pass company_name=company_name.replace(" ","").replace("。","").replace("-","").replace("(","").replace(")","").replace("\n","") print(company_name, "//", address) update_providence(address,company_name) <file_sep>/untitled/Play抽奖.py import random for i in range(1): a=random.randint(1,1000) if a>=10: print("谢谢参与") else: if a>2 and a<10: print("三等奖") else: if a==1: b=random.randint(1,1000) if b==1: print("一等奖") else: if b>=2: print("二等奖")<file_sep>/API调用/练习/中文分词-API调用.py # coding:utf-8 """ Compatible for python2.x and python3.x requirement: pip install requests six """ from __future__ import print_function import requests from six.moves.urllib.parse import urlencode from six.moves import input # 请求示例 url url = "http://api01.bitspaceman.com:8000/nlp/segment/bitspaceman?apikey=<KEY>" headers = { "Accept-Encoding": "gzip", "Connection": "close" } post_param = { 'text':'哈哈' } if __name__ == "__main__": r = requests.post(url, data=urlencode(post_param), headers=headers) json_obj = r.json() print(json_obj)<file_sep>/API调用/练习/身份证.py from urllib import request, parse import json print('send data....') showapi_appid="61534" #替换此值 showapi_sign="feb4bf41ec7f465b9a1e8030b292a5bc" #替换此值 url="http://route.showapi.com/25-3" send_data = parse.urlencode([ ('showapi_appid', showapi_appid) ,('showapi_sign', showapi_sign) ,('id', "320282199209212591") ]) req = request.Request(url) try: response = request.urlopen(req, data=send_data.encode('utf-8'), timeout = 10) # 10秒超时反馈 except Exception as e: print(e) result = response.read().decode('utf-8') result_json = json.loads(result) print ('result_json data is:', result_json)
aa92eaef5c1dc9f1c21e57571f7acde6571fa594
[ "JavaScript", "Python" ]
291
Python
mlg2434s/PyCharmProjects
cf2916306b9f42af9554b8f8851e8de0267efaca
33d32ec18460de422ce1feaf1f1885098c2fca16
refs/heads/master
<file_sep>$(document).ready(function() { console.log("let's go!"); getQuoteApi(); $("#quoteButton").on("click", getQuoteApi); }); var getQuoteApi = function() { $.getJSON("https://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?", function(jd) { console.log("Success!") $("#quoteContainer").fadeOut(500, function() { $("#quote").text(jd.quoteText); $("#author").text(jd.quoteAuthor); $("#quoteContainer").fadeIn(500); $("#tweetText").attr("href", "https://twitter.com/share?text=" + "\"" + jd.quoteText + "\" - " + jd.quoteAuthor + "."); }); }); };
d1aeb7a98af33c64d10bb2e0d996e2532423408d
[ "JavaScript" ]
1
JavaScript
jarekjar/quote-generator
1657fa292d57da41b4399a833276e82c2f3176bb
03061a48b14db935d8ae85823971b5ef063bd0eb
refs/heads/master
<file_sep>Python Dynamic Link Library = 打开命令行,进入目录,执行以下命令。 Mac: /Applications/Autodesk/maya201x/Maya.app/Contents/bin/mayapy py2pyd.py build_ext --inplace Windows: "C:/Program Files/Autodesk/Maya201x/bin/mayapy.exe" py2pyd.py build_ext --inplace 故障排除: error: Unable to find vcvarsall.bat 如果系统上已经安装了Visual Studio,这个问题可以通过事先在命令行中设置排除,听说这个选项写死在编译器,只能这么干。 SET VS90COMNTOOLS=%VS100COMNTOOLS%<file_sep># Windows下利用Cython生成动态链接库pyd pyd在Windows下其实就是dll。如果已经有C文件,可以使用微软开发的Visual Studio系列开发环境(IDE)来编译生成。不同的版本的设置位置可能不同,但所要设置的项目都是一样的: * 新建项目,项目类型选择C++的MFC DLL,注意项目名要全小写(其实只要最后生成的dll是全小写就可以了,这里为了方便起见); * 菜单栏中工具->选项,项目与解决方案->VC++目录,右边选择“包含文件”,添加Python安装路径里面的include目录;选择“库文件”,添加Python安装路径里面的libs目录; * 右击项目->属性,配置属性->C/C++->预编译头,将“创建/使用预编译头”选项设为“不使用预编译头” * 继续在项目属性窗口,配置属性->链接器->输入,将“模块定义文件”的值删除;配置属性->链接器->常规,把“输出文件”的值中的"dll"替换为"pyd" 生成的过程中常常出现error link的情况,这多半是因为文件找不到的情况,解决方法有: 1. 增加include的文件夹; 2. 补充系统或python安装目录缺失的包。 当缺失python27_d.lib时,有三种办法: 1. 将python安装目录下libs目录里的python27复制一份并命名为python27_d.lib,修改include目录下的pyconfig.h,将#define Py_DEBUG注释掉 2. 上网搜索并下载python27_d.lib和python27.dll,分别放入libs目录和C:/windows/system32 如果只提供了pyx文件的话,就需要将pyx转换为c文件,再编译成pyd文件。我所需要处理的pyx文件是[word2vec_inner.pyx](https://github.com/piskvorky/gensim/blob/develop/gensim/models/word2vec_inner.pyx),一开始,我查询了Cython的[官方文档](http://docs.cython.org/src/reference/compilation.html)使用如下代码文件进行c文件生成和编译,为不损坏原文件,我使用副本`word2vec_inner_t.pyx`。 ```python # setup_wv.py from distutils.core import setup from Cython.Build import cythonize import numpy setup( name = "<NAME>", ext_modules = cythonize("word2vec_inner_t.pyx", include_path = [numpy.get_include()]), ) ``` ``` python setup_wv.py build_ext --inplace ``` 命令行给出的信息: ``` running build_ext ``` 后来在Pycharm里运行一遍,才发现完整的信息: ``` running build_ext error: Unable to find vcvarsall.bat ``` 如果系统上已经安装了Visual Studio,这个问题可以通过事先在命令行中设置排除,听说这个选项写死在编译器,只能这么干。 ``` SET VS90COMNTOOLS=%VS100COMNTOOLS% ``` 到了这里,再次编译,报错说无法找到numpy的include文件: ``` Z:\CodeSpace\Python\testPython2\gensim\models>python setup_wv.py build_ext --inplace running build_ext building 'testPython2.gensim.models.word2vec_inner_t' extension C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -ID:\Python27\include -ID:\Python27\PC /Tcword2vec_inner_t.c /Fobuild\temp.win32-2.7\Release\word2vec_inner_t.obj word2vec_inner_t.c word2vec_inner_t.c(346) : fatal error C1083: 无法打开包括文件:“numpy/arrayobject.h”: No such file or directory error: command '"C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\cl.exe"' failed with exit status 2 ``` 在谷歌半天之后,在`StackOverflow`我才发现能通过以下方式加入numpy的include文件夹: ```python from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy extensions = [ Extension("word2vec_inner_t", ["word2vec_inner_t.pyx"], include_dirs=[numpy.get_include()]) ] setup( name="My Hello app", ext_modules=cythonize(extensions), ) ``` 这样虽然没有生成pyd文件,但已经给出了c文件,我使用之前的方法试图利用Visual Studio生成pyd文件,但是遭遇失败,错误几乎无从下手: ``` 1>d:\python27\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(12): warning Msg: Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 1>z:\codespace\cplusplus\com4pyd2\com4pyd2\com4pyd2.cpp(6863): error C2440: “=”: 无法从“void (__cdecl *)(const __pyx_t_5numpy_uint32_t *,const __pyx_t_5numpy_uint8_t *,int *,__pyx_t_11testPython2_6gensim_6models_16word2vec_inner_t_REAL_t *,__pyx_t_11testPython2_6gensim_6models_16word2vec_inner_t_REAL_t *,__pyx_t_11testPython2_6gensim_6models_16word2vec_inner_t_REAL_t *,const int,const __pyx_t_5numpy_uint32_t *,const __pyx_t_11testPython2_6gensim_6models_16word2vec_inner_t_REAL_t,__pyx_t_11testPython2_6gensim_6models_16word2vec_inner_t_REAL_t *,int,int,int,int)”转换为“__pyx_t_11testPython2_6gensim_6models_16word2vec_inner_t_fast_sentence_cbow_hs_ptr” 1> 该转换要求 reinterpret_cast、C 样式转换或函数类型转换 ... 1> 1>生成失败。 ``` 我想大概是C文件也有错误,还是得从pyx文件入手。偶然又在Overflow上发现文件名的问题,我又将`setup_wv.py`中的`word2vec_inner_t`改正: ```python from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy extensions = [ Extension("word2vec_inner", ["word2vec_inner.pyx"], include_dirs=[numpy.get_include()]) ] setup( name="word2vec_inner", ext_modules=cythonize(extensions), ) ``` 重敲命令: ``` python setup_wv.py build_ext --inplace Compiling word2vec_inner.pyx because it changed. Cythonizing word2vec_inner.pyx running build_ext building 'word2vec_inner' extension C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -ID:\Python27\lib\site-packages\numpy\core\include -ID:\Python27\include -ID:\Python27\PC /Tcword2vec_inner.c /Fobuild\temp.win32-2.7\Release\word2vec_inner.obj word2vec_inner.c d:\python27\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(12) : Warning Msg: Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:D:\Python27\libs /LIBPATH:D:\Python27\PCbuild /EXPORT:initword2vec_inner build\temp.win32-2.7\Release\word2vec_inner.obj /OUT:Z:\CodeSpace\Python\testPython2\gensim\models\word2vec_inner.pyd /IMPLIB:build\temp.win32-2.7\Release\word2vec_inner.lib /MANIFESTFILE:build\temp.win32-2.7\Release\word2vec_i nner.pyd.manifest 正在创建库 build\temp.win32-2.7\Release\word2vec_inner.lib 和对象 build\temp. win32-2.7\Release\word2vec_inner.exp ``` 我当时以为这就算大功告成了吗?但我在Pycharm中运行后,发现还是无法`import`,我不信,紧接在命令行敲`python`尝试: ``` Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import word2vec_inner >>> word2vec_inner.train_sentence_sg <built-in function train_sentence_sg> >>> word2vec_inner.train_sentence_cbow <built-in function train_sentence_cbow> >>> word2vec_inner.FAST_VERSION 0 ``` 看来是Pycharm的问题了,重启之,顺利运行~ <file_sep>#======================================== # author: changlong.zang # mail: <EMAIL> # date: Sat, 19 Sep 2015, 09:53:47 #======================================== import sys, re, os import distutils.core, distutils.extension import Cython.Build #--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ def py2pyd(path): ''' ''' os.chdir(path) file_list = os.listdir(path) for f in file_list: if os.path.isdir(f): continue if not re.search('.py$', f): continue if re.match('setup.py', f): continue if re.match('__init__.py', f): continue if re.search('_rc.py', f): continue extensions = [distutils.extension.Extension(os.path.splitext(f)[0], [f], include_dirs=[])] distutils.core.setup(name='pytopyd', ext_modules=Cython.Build.cythonize(extensions)) cpp_file = '{0}.c'.format(os.path.splitext(f)[0]) os.path.isfile(cpp_file) and os.remove(cpp_file) if __name__ == '__main__': path = os.getcwd() py2pyd(path)
e7b23982292380bf03157b2b90c2f7575541aa36
[ "Markdown", "Python" ]
3
Markdown
wblion/Py2Pyd
febe8b00a15713b42cb60203aec5338adc3cf527
3296137fa09606a98e5327ff7e289ac96adf2215
refs/heads/master
<repo_name>spol/Spine<file_sep>/code/src/Spine/Command/RenderCommand.php <?php namespace Spine\Command; use Symfony\Component\Console as Console; class RenderCommand extends Console\Command\Command { public function __construct() { parent::__construct('build'); $this->setDescription('Renders markdown to HTML.'); $this->setHelp('Renders markdown to HTML.'); $this->addArgument('path', Console\Input\InputArgument::REQUIRED, 'The path of the folder containing the markdown files.'); } protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) { $path = $input->getArgument('path'); if ($path[0] != '/') { $path = getcwd() . '/' . $path; } if (!file_exists($path)) { throw new \Exception("path doesn't exist"); } elseif (!is_dir($path)) { throw new \Exception('path is not a directory.'); } $this->buildpath = realpath($path) . '/_epub'; if (file_exists($this->buildpath)) { $this->unlink_dir($this->buildpath); } mkdir($this->buildpath); file_put_contents($this->buildpath . '/mimetype', "application/epub+zip"); mkdir($this->buildpath . '/OEBPS/Text', 0777, true); $chapters = array(); if (file_exists($path . '/contents.txt')) { $files = explode("\n", file_get_contents($path . '/contents.txt')); foreach ($files as $file) { if ($file != "") { if (file_exists($path.'/'.$file)) { $chapters[] = new Chapter($path.'/'.$file); } else { echo "WARNING: File listed in contents.txt not found: {$file}\n"; } } } } else { $files = new \GlobIterator($path.'/*.txt'); foreach ($files as $file) { $chapters[] = new Chapter($file->getPathname()); } // todo: optionally load order from contents.txt usort($chapters, function($a, $b) { $a = pathinfo($a->getPath(), PATHINFO_FILENAME); $b = pathinfo($b->getPath(), PATHINFO_FILENAME); $a_ = strlen($a) - strlen(ltrim($a, "_")); $b_ = strlen($b) - strlen(ltrim($b, "_")); if ($a_ != $b_) { return $a > $b ? -1 : 1; } return strnatcasecmp($a, $b); }); } foreach ($chapters as $chap) { $chap->RenderAndSave($this->buildpath); } $meta = array( 'title' => '', 'author' => '', 'isbn' => '' ); if (file_exists($path.'/meta.ini')) { $meta = array_merge($meta, parse_ini_file($path.'/meta.ini')); } if (!isset($meta['sort_author'])) { $meta['sort_author'] = $meta['author']; } // images $images = new \GlobIterator($path.'/*.jpg'); if (count($images) > 0) { mkdir($this->buildpath.'/OEBPS/Images'); foreach ($images as $image) { copy($image->getPathname(), $this->buildpath.'/OEBPS/Images/'.$image->getFilename()); } } mkdir($this->buildpath.'/OEBPS/Styles'); copy(ROOT . '/tpl/epub.css', $this->buildpath.'/OEBPS/Styles/epub.css'); // cover if (file_exists($this->buildpath.'/OEBPS/Images/cover.jpg')) { $meta['cover'] = true; } else { $meta['cover'] = false; } // content.opf $this->buildContent($chapters, $meta); // toc.ncx $this->buildTOC($chapters, $meta); // meta-inf $this->buildMetaInf(); $this->zip($this->file_title($meta['title'], ' '). '.epub'); if (file_exists($this->buildpath)) { $this->unlink_dir($this->buildpath); } } private $buildpath; private function unlink_dir($dir) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $path) { if ($path->isDir()) { rmdir($path->__toString()); } else { unlink($path->__toString()); } } rmdir($dir); } private function buildContent($contents, $meta) { ob_start(); extract($meta); include ROOT . '/tpl/content.opf.tpl'; $content = ob_get_clean(); file_put_contents($this->buildpath.'/OEBPS/content.opf', $content); } private function buildTOC($contents, $meta) { ob_start(); extract($meta); include ROOT . '/tpl/toc.ncx.tpl'; $content = ob_get_clean(); file_put_contents($this->buildpath.'/OEBPS/toc.ncx', $content); } private function zip($name) { echo $name, "\n"; copy(ROOT.'/tpl/epub.zip', $name); $epub = new Zipper(); $res = $epub->open($name); $epub->addDir($this->buildpath.'/META-INF', 'META-INF/'); $epub->addDir($this->buildpath.'/OEBPS', 'OEBPS/'); // $epub->addFile($this->buildpath.'/mimetype', 'mimetype'); $res = $epub->close(); } private function buildMetaInf() { mkdir($this->buildpath.'/META-INF'); copy(ROOT.'/tpl/container.xml', $this->buildpath.'/META-INF/container.xml'); } function file_title($str) { $trans = array( '&\#\d+?;' => '', '&\S+?;' => '', '\s+' => ' ', '[^a-z0-9\-\._ ]' => '', '[_\-]+' => ' ', '[_\- ]$' => '', '^[\-_ ]' => '', '\.+$' => '' ); $str = strip_tags($str); foreach ($trans as $key => $val) { $str = preg_replace('#'.$key.'#i', $val, $str); } return trim(stripslashes($str)); } }<file_sep>/code/src/Spine/Command/Zipper.php <?php namespace Spine\Command; class Zipper extends \ZipArchive { public function addDir($path, $prefix) { $this->addEmptyDir($prefix); $nodes = glob($path . '/*'); foreach ($nodes as $node) { if (is_dir($node)) { $this->addDir($node, $prefix.pathinfo($node, PATHINFO_BASENAME).'/'); } else if (is_file($node)) { $this->addFile($node, $prefix.pathinfo($node, PATHINFO_BASENAME)); } } } }<file_sep>/code/src/Spine/Command/ExtractCommand.php <?php namespace Spine\Command; use Symfony\Component\Console as Console; class ExtractCommand extends Console\Command\Command { public function __construct() { parent::__construct('extract'); $this->setDescription('Extracts an ePub to Markdown.'); $this->setHelp('Extracts an ePub to Markdown.'); $this->addArgument('file', Console\Input\InputArgument::REQUIRED, 'The ePub file.'); } protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) { $file = $input->getArgument('file'); if ($file[0] != '/') { $file = getcwd() . '/' . $file; } if (!file_exists($file)) { throw new Exception("File doesn't exist"); } $zip = new \ZipArchive(); $zip->open($file); $container = $zip->statName('META-INF/container.xml'); if ($container === false) { throw new Exception("This doesn't appear to be a valid EPUB file."); } $containerXml = $zip->getFromName('META-INF/container.xml'); $contents = $this->readContainerXml($containerXml); $internalPath = pathinfo($contents, PATHINFO_DIRNAME); if ($internalPath != '') $internalPath .= '/'; $contentsXml = $zip->getFromName($contents); list($meta, $files, $spine) = $this->readContentsXml($contentsXml); // create folder $path = pathinfo($file, PATHINFO_DIRNAME) . '/' . pathinfo($file, PATHINFO_FILENAME); if (file_exists($path)) $this->unlink_dir($path); mkdir($path); // save meta $this->write_ini_file($meta, $path.'/meta.ini'); // images (cover) foreach ($files['image/jpeg'] as $images) { $file = pathinfo($images['name'], PATHINFO_BASENAME); $imageData = $zip->getFromName($internalPath . $images['name']); file_put_contents($path.'/'.$file, $imageData); } // export files $contents = array(); foreach ($spine as $pos => $id) { $file = $files['application/xhtml+xml'][$id]['name']; $contents[] = ($pos+1) . '_' . pathinfo($file, PATHINFO_FILENAME) . '.txt'; $target = ($pos+1) . '_' . pathinfo($file, PATHINFO_FILENAME) . '.txt'; // Markdownify $html = $zip->getFromName($internalPath . $file); $markdownify = new \Markdownify(false, false, false); $markdown = $markdownify->parseString($html); file_put_contents($path.'/'.$target, $markdown); } // contents file_put_contents($path.'/contents.txt', implode("\n", $contents)); } private function readContainerXml($xml) { $container = new \SimpleXMLElement($xml); return (string)$container->rootfiles->rootfile['full-path']; } private function readContentsXml($xml) { $package = new \SimpleXmlElement($xml); $meta = array(); foreach (array_keys($package->getNamespaces(true)) as $namespace) { //var_dump($namespace); foreach ($package->metadata->children($namespace, true) as $element) { switch ($namespace) { case "": $meta[(string)$element['name']] = (string)$element['content']; break; case "dc": if (isset($meta[$element->getName()])) { if (!is_array($meta[$element->getName()])) { $meta[$element->getName()] = array($meta[$element->getName()]); } $meta[$element->getName()][] = (string)$element; } else { $meta[$element->getName()] = (string)$element; } break; case "opf": $attr = $element->attributes(); $meta[(string)$attr['name']] = (string)$attr['content']; break; } } } $files = array(); foreach ($package->manifest->item as $item) { $files[(string)$item['media-type']][(string)$item['id']] = array("name" => (string)$item['href'], "id" => (string)$item['id']); } $spine = array(); foreach ($package->spine->itemref as $itemref) { $spine[] = (string)$itemref['idref']; } return array($meta, $files, $spine); } private function write_ini_file($assoc_arr, $path, $has_sections=FALSE) { $content = ""; if ($has_sections) { foreach ($assoc_arr as $key=>$elem) { $content .= "[".$key."]\n"; foreach ($elem as $key2=>$elem2) { if(is_array($elem2)) { for($i=0;$i<count($elem2);$i++) { $content .= $key2."[] = \"".$elem2[$i]."\"\n"; } } else if($elem2=="") $content .= $key2." = \n"; else $content .= $key2." = \"".$elem2."\"\n"; } } } else { foreach ($assoc_arr as $key=>$elem) { if(is_array($elem)) { for($i=0;$i<count($elem);$i++) { $content .= $key."[] = \"".$elem[$i]."\"\n"; } } else if($elem=="") $content .= $key." = \n"; else $content .= $key." = \"".$elem."\"\n"; } } if (!$handle = fopen($path, 'w')) { return false; } if (!fwrite($handle, $content)) { return false; } fclose($handle); return true; } private function unlink_dir($dir) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $path) { if ($path->isDir()) { rmdir($path->__toString()); } else { unlink($path->__toString()); } } rmdir($dir); } }<file_sep>/build/build.php <?php $phar = new Phar('spine.phar', 0, 'spine.phar'); $phar->buildFromDirectory(__DIR__.'/../code'); $phar->setStub(file_get_contents(__DIR__.'/../code/stub.php'));<file_sep>/code/spine.php <?php require_once 'src/autoload.php'; require_once 'vendor/Markdown/Markdown/Parser.php'; require_once 'vendor/markdownify/markdownify.php'; define('ROOT', __DIR__); use Symfony\Component\Console as Console; $application = new Console\Application('spine', '0.9'); $application->add(new Spine\Command\RenderCommand()); $application->add(new Spine\Command\ExtractCommand()); $application->run();<file_sep>/code/src/Spine/Command/Chapter.php <?php namespace Spine\Command; class Chapter { private $path; private $name; private $file; private $id; public function __construct($path) { $this->name = trim(str_replace('Ω', '', str_replace('_', ' ', pathinfo($path, PATHINFO_FILENAME)))); $this->file = str_replace(' ', '_', $this->name) . '.xhtml'; $this->id = str_replace(' ', '_', $this->name); $this->path = $path; } public function getName() { return $this->name; } public function getPath() { return $this->path; } public function getId() { return $this->id; } public function getFilename() { return $this->file; } public function RenderAndSave($buildpath) { $parser = new \Markdown_Parser(); $output_file = $buildpath .'/OEBPS/Text/' . $this->file; $source = file_get_contents($this->path); $source = preg_replace('/^[^#>\n].*\n/m', "$0\n", $source); $source = preg_replace('/(^>.*)\n([^>])/m', "$1\n\n$2", $source); $source = preg_replace('/\n{2,}/m', "\n\n", $source); $rendered_content = $parser->transform($source); $rendered_content = preg_replace('/^<p>([^a-z]?[A-Z][A-Z])/m', "<p class='newsection'>$1", $rendered_content); $title = ""; ob_start(); include ROOT . '/tpl/xhtml.tpl'; $output = ob_get_clean(); file_put_contents($output_file, $output); } }<file_sep>/code/stub.php #!/usr/bin/env php <?php phar::mapPhar('spine.phar'); phar::interceptFileFuncs(); require 'phar://spine.phar/spine.php'; __HALT_COMPILER();
cb3908beee87a3e89f6e3a6add980e774cde4281
[ "PHP" ]
7
PHP
spol/Spine
454ce1c32d5d9b837cacab18b0f1300fcef832a5
d6c783fd6ad498cebc49fbee02e8b54654a524d7
refs/heads/master
<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Company.php"; class CompanyEmailItem extends ModelItem { public $id; public $name; public $email; public $companyId; } class CompanyEmail extends BaseModel { public $tableName = "companies-emails"; public $modelItem = "CompanyEmailItem"; public function sqlBuildGetAllItems($where=null, $order = null, $limit = NULL) { $cmd = 'SELECT a.*, b.name as company, b.nameInvariant as companyInvariant FROM `' . $this->tableName . '` a LEFT JOIN `companies` b ON b.id = a.companyId'; if (isset($where)) $cmd .= $this->sqlBuildWhere($where); return $cmd; } public function getListAction($where = null, $order = null, $limit = NULL) { try { $cmd = $this->sqlBuildGetAllItems(); if (isset($_REQUEST["companyId"])) { $cmd .= $this->sqlBuildWhere(["a.companyId" => $_REQUEST["companyId"]]); } $cmd .= ' Order By a.companyId, a.name '; $queryResult = $this->db->query($cmd); $response = array(); $response["data"] = $queryResult->rows; $response["status"] = true; return $response; } catch (Exception $error) { return $this->catchError($error); } } public function validate(&$data=null) { $itemName = "Company Email"; if (!isset($this->item->companyId)) { $exception = new Exception("Company is required"); $exception->field = "companyId"; throw $exception; } if (!isset($this->item->name)) { $exception = new Exception("$itemName name/alias is required"); $exception->field = "name"; throw $exception; } if (!isset($this->item->email)) { $exception = new Exception("$itemName email is required"); $exception->field = "email"; throw $exception; } return true; } } <file_sep>DROP DATABASE IF EXISTS `invoicing-demo` ; CREATE DATABASE IF NOT EXISTS `invoicing-demo` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `invoicing-demo`; CREATE USER IF NOT EXISTS 'invoicing-demo'@'%' IDENTIFIED BY 'generic8iNbR7'; GRANT SELECT, INSERT, UPDATE, DELETE ON *.* TO 'invoicing-demo'@'%' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;<file_sep>(function () { angular.module("App").controller("citiesCtrl", controller); controller.$inject = ['$scope', "axDataAdapter", "$timeout", "axDataStore", "$element"]; function controller($scope, $adapter, $timeout, axDataStore, $element) { $scope.loader = axDataStore.loader("#right-pane"); $scope.$element = $element; $scope.dataStore = axDataStore; $scope.country = $scope.$parent.launcher ? $scope.$parent.launcher.dataItem : null; $scope.editingMode = $scope.$parent.launcher ? "popup" : ($scope.$parent.$ctrl && $scope.$parent.$ctrl.attributes && $scope.$parent.$ctrl.attributes.config.includes("$$editor.form") ? "editor" : "page"); if (!$scope.$parent.launcher) $scope.$parent.launcher = {openFinish: false}; let dataTable1 = citiesClass.dataTable($adapter, $scope); angular.extend($scope.$parent.launcher, { showButtons: $scope.$parent.launcher.openFinish, dataTable1: dataTable1, }); $scope.countriesEdit = countriesClass.popup( $adapter, { get: function () { return $scope.countries; }, set: function (datasource) { $scope.countries = datasource; } }, dataTable1, { id: "countryId", name: "country", invariant: "countryInvariant" }, "dataTable1", $timeout); if ($scope.editingMode === "editor") { $scope.$parent.$ctrl.config.refreshFormCallback = function (dataItem) { $scope.country = dataItem; if (!dataTable1.$ctrl || !dataTable1.$ctrl.controllerLoaded) return; //because of ax-editor ng-if $scope.dataTable1.$ctrl is not existing yet and must wait until controlelr is fully loaded (2 digest cycles) //console.log("dataItem", dataItem); if (!dataItem) dataTable1.$ctrl.datasourceSet([]); else dataTable1.$ctrl.loadData(); }; // in this moment refreshForm it's already executed on initialization $scope.$parent.$ctrl.config.refreshFormCallback($scope.$parent.$ctrl.config.dataItem); } } }());<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Invoice.php"; class InvoiceDetailItem extends ModelItem { public $id; public $invoiceId; public $position; public $description; public $quantity; public $unit; public $price; public $value; public $vat; public $vatValue; public $discount; public $discountValue; } class InvoiceDetail extends BaseModel { public $tableName = "invoices-details"; public $modelItem = "InvoiceDetailItem"; public $foreignKey = "invoiceId"; public $validateOnWrite = false; public function sqlBuildGetAllItems($where = null, $order = null, $limit = NULL) { $cmd = "SELECT a.* FROM `{$this->tableName}` a"; if (isset($where)) $cmd .= $this->sqlBuildWhere($where); return $cmd; } public function getListAction($where = null, $order = null, $limit = NULL) { try { if (isset($_REQUEST["invoiceId"]) && !isset($where["invoiceId"])) { $where["invoiceId"] = $_REQUEST["invoiceId"]; } $cmd = $this->sqlBuildGetAllItems($where, $order); if (!isset($where["invoiceId"])) { throw new Exception("invoiceId query parameter needed"); } $invoiceId = $where["invoiceId"]; $queryResult = $this->db->query($cmd); $response = array(); $response["data"] = $queryResult->rows; $invoice = (new Invoice($this->db))->getItemAction(array("a.id" => $invoiceId)); if (!$invoice["status"]) return $invoice; if (count($invoice["data"])) { $customerId = $invoice["data"]["customerId"]; $response["descriptions"] = $this->getDetailsDescriptions($customerId); $response["emailTemplates"] = $this->getEmailTemplates($customerId); } else $response["descriptions"] = array(); $response["status"] = true; return $response; } catch (Exception $error) { return $this->catchError($error); } } private function getEmailTemplates($companyId) { $cmd = "SELECT a.* From `companies-email-templates` as a WHERE a.companyId = $companyId ORDER BY a.name "; $queryResult = $this->db->query($cmd ); return $queryResult->rows; } private function getDetailsDescriptions($customerId) { $cmd = "SELECT a.description, i.date, i.number From `invoices-details` as a JOIN invoices i on a.invoiceId = i.id WHERE i.customerId = $customerId AND description != '' ORDER BY i.number DESC, a.description"; $queryResult = $this->db->query($cmd); return $queryResult->rows; } public function getDescriptionsAction() { try { if (!isset($_REQUEST["invoiceId"])) throw new \Exception("No invoice id provided"); if (!isset($_REQUEST["customerId"])) throw new \Exception("No invoice id provided"); $invoiceId = $_REQUEST["invoiceId"]; $customerId = $_REQUEST["customerId"]; $data = $this->getDetailsDescriptions($customerId, $invoiceId); $response["data"] = $data; $response["status"] = true; return $response; } catch (Exception $error) { return $this->catchError($error); } } private function addError($field = null, $message) { if (isset($field)) { if (!isset($this->errors->$field)) $this->errors->$field = array(); $error = $this->errors->$field; $error[] = $message; $this->errors->$field = $error; } else { if (!isset($this->errors->{''})) $this->errors->{''} = array(); $this->errors->{''}[] = $message; } $this->hasErrors = true; } public function validate(&$data = null) { $this->errors = new stdClass(); $this->hasErrors = false; $item = isset($data) ? $data : $this->item; if (!isset($item->position)) { $this->addError("position", "Field is required"); } $item->value = round($item->price * $item->quantity, 2); return !$this->hasErrors; } } <file_sep>(function () { angular.module("App").controller("usersCtrl", controller); controller.$inject = ['$scope', "axDataAdapter", "$element", "axDataStore"]; function controller($scope, $adapter, $element, axDataStore) { $scope.loader = axDataStore.loader("#right-pane"); $scope.$element = $element; $scope.table1 = { dataAdapter: new $adapter({ invariant: ["nume", "prenume"], extend: function () { this.numeComplet = (this.prenume ? this.prenume : "") + (this.nume ? " " + this.nume : ""); this.numeCompletInvariant = (this.prenumeInvariant ? this.prenumeInvariant : "") + this.numeInvariant ? (" " + this.numeInvariant) : ""; return this; }, conversions: { esteActiv: {type: "boolean"}, esteAdmin: {type: "boolean"}, CiDate: {type: "date"} } }) }; } }());<file_sep>var applicationInfo = { "name": "Invoicing", "version": "1.0.0.0008", "copyright": "2018 <NAME>", "language": "en", "theme": {}, }; if (typeof window === 'undefined') { module.exports = applicationInfo; } else { let el = document.querySelector('#environment'); let type = ""; let origin = window.origin; if (origin === "http://192.168.1.10:4001") type = "LIVE"; else if (origin === "http://bogdanim36.asuscomm.com:5019") type = "Demo"; else if (origin === "http://invoicing.demo.spark36.net") type = "Demo"; else if (origin === "https://invoicing.demo.spark36.net") type = "Demo"; else type = el.getAttribute('content'); applicationInfo.type = type; applicationInfo.themes = themes; let versionArr = applicationInfo.version.split('.'); if (versionArr.length > 3) versionArr.splice(versionArr.length - 1, 3); let version = versionArr.join('.'); document.title = applicationInfo.name + " " + version + " " + type; } <file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Company.php"; class OwnerItem extends ModelItem { public $id; public $companyId; public $socialCapital; public $vatPercentsList; public $stampPath; public $logoPath; public $vatRegistred; public $contactPhone; public $contactEmail; public $currencies; } class Owner extends BaseModel { public $tableName = "owners"; public $modelItem = "OwnerItem"; public function sqlBuildGetAllItems($where = null, $order = null, $limit = NULL) { $cmd = 'SELECT a.*, b.name, b.nameInvariant, b.address, b.administratorName, code, tradeRegister, d.name as city, d.nameInvariant as cityInvariant, b.county, c.name as country, c.nameInvariant as countryInvariant FROM `' . $this->tableName . '` a LEFT JOIN `companies` b ON b.id = a.companyId LEFT JOIN countries c on c.id = b.countryId LEFT JOIN cities d on d.id = b.cityId'; if (isset($where)) $cmd .= $this->sqlBuildWhere($where); return $cmd; } public function getListAction($where = null, $order = null, $limit = NULL) { $response = parent::getListAction($where, $order); if (!$response["status"]) return $response; $companies = (new Company($this->db, json_encode($this->postData)))->getListAction(); if (!$companies["status"]) return $companies; $response["companies"] = $companies["data"]; return $response; } public function validate(&$data = null) { $itemName = "Owner"; if (!isset($this->item->companyId)) { $exception = new Exception("Company is required"); $exception->field = "companyId"; throw $exception; } if (!isset($this->item->currencies)) { $exception = new Exception("Currencies is required"); $exception->field = "currencies"; throw $exception; } If (isset($this->item->stampPath)) $this->item->stampPath = explode("?", $this->item->stampPath)[0]; If (isset($this->item->logoPath)) $this->item->logoPath = explode("?", $this->item->logoPath)[0]; If (isset($this->item->vatRegistred) && ($this->item->vatRegistred == 'true' || $this->item->vatRegistred == '1')) $this->item->vatRegistred = 1; return $this->uploadFiles(); } public function uploadFiles() { if (!realpath(UPLOAD_DIR)) return array("status" => false, "message" => "No upload directory exist: " . UPLOAD_DIR); if ($_FILES) { $files = isset($_FILES["files"]) ? $_FILES["files"] : (isset($_FILES["file"]) ? $_FILES["file"] : []); $error = false; foreach ($files["name"] as $key => $name) { if ($files["error"][$key] == 0) continue; $error = true; } if ($error) { $response["status"] = false; $response["message"] = "Error uploading files. Check upload directory rights acces and upload max limit size!"; return $response; } foreach ($files["name"] as $key => $name) { $file = array("name" => $name, "tmpPath" => $files["tmp_name"][$key], "type" => $files["type"][$key], "size" => $files["size"][$key], "category" => $this->postData->filesMap[$key]); $result = $this->moveFile($file); if ($result["status"]) { $this->item->{$file["category"] . 'Path'} = "/upload/" . $result["name"]; } else return $result; } } return true; } public function moveFile($file) { $fileNameParts = explode(".", $file["name"]); $ext = '.' . $fileNameParts[count($fileNameParts) - 1]; $file["storedName"] = $file["category"] . "-" . $this->item->companyId . $ext; $file["storedPath"] = realpath(UPLOAD_DIR) . '/' . $file["category"] . "-" . $this->item->companyId . $ext; normalizePath($file["storedPath"]); $response = rename($file["tmpPath"], $file["storedPath"]); if (!$response) return array("status" => false, "message" => "File " . $file["name"] . "couldn't be uploaded!"); else return array("status" => true, "path" => $file["storedPath"], 'name' => $file["storedName"]); } } <file_sep># ax-components angularJS components Repo for axFrmk components <file_sep>var axAuthConfig = { allowAnonymous: false, urls: { login: "account/login", logoff: "account/logoff", getUserInfo: "account/getUserInfo", resetPassword: "<PASSWORD>" }, loadRoutesFromMenu: true, restorePreviousValues: function (dataStore, $storage, response, dataSet) { // console.log("response", $storage, dataStore, response); if ($storage.user && $storage.user.language) applicationInfo.language = $storage.user.language; this.dataSet = dataSet; if (!response.owners) console.error("NU exista owners in raspuns server getUserInfo"); dataSet.owners = response.owners; }, saveStorageUser: function (user, dataStore) { if (!dataStore.currentOwner && this.dataSet.owners && this.dataSet.owners.length) this.dataSet.currentOwner = this.dataSet.owners[0]; // console.log("saveStorage", user, dataStore) } }; <file_sep>(function () { angular.module("App").controller("countriesCtrl", controller); controller.$inject = ['$scope', "axDataAdapter", "axDataStore", "$element"]; function controller($scope, $adapter, axDataStore,$element) { $scope.loader = axDataStore.loader("#right-pane"); $scope.$element = $element; $scope.dataStore = axDataStore; if (!$scope.$parent.launcher) $scope.$parent.launcher = {openFinish: false}; $scope.editingMode = $scope.$parent.launcher ? "popup" : ($scope.$parent.$ctrl && $scope.$parent.$ctrl.attributes && $scope.$parent.$ctrl.attributes.config.includes("$$editor.form") ? "editor" : "page"); angular.extend($scope.$parent.launcher, { showButtons: $scope.$parent.launcher.openFinish, dataTable1: countriesClass.dataTable($adapter), }); $scope.citiesPopup = { onOpen: function (params) { this.dataItem = params[1]; this.openFinish = true; }, confirm: function () { this.close(); } }; } }());<file_sep>var modules = []; modules.push("ngStorage"); modules.push("ax.components"); modules.push("ckeditor"); <file_sep>class UserModel { constructor(id, email, prenume, nume, numeComplet, numeCompletInvariant, esteActiv, esteAdmin, resetLink, CNP, CiNumber, CiSeries, CiDate, CiIssuedBy) { this.id = id; this.email = email; this.prenume = prenume; this.nume = nume; this.numeComplet = numeComplet; this.numeCompletInvariant = numeCompletInvariant; this.esteActiv = esteActiv; this.esteAdmin = esteAdmin; this.resetLink = resetLink; this.CNP = CNP; this.CiNumber = CiNumber; this.CiSeries = CiSeries; this.CiDate = CiDate; this.CiIssusedBy = CiIssuedBy; } }<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.controller.php"; class Account extends BaseController { public function getUserInfoAction() { require_once $_SERVER["DOCUMENT_ROOT"] . "/api/menu-roles.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Owner.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/User.php"; $response = array(); $response["status"] = false; try { if (!isset($_COOKIE["user-id"]) && !isset($this->postData->email)) throw new Exception("Login user"); $email = isset($_COOKIE["user-id"]) ? $_COOKIE["user-id"] : $this->postData->email; $userClass = new User($this->db); $users = $userClass->getListAction(array("email" => $email)); if (!$users["status"]) return $users; if (count($users["data"]) == 0) throw new Exception("No user found for email: " . $email); if ($users["data"][0]["esteActiv"] == 0) throw new Exception("Access is disabled for email: " . $email); $data = $users["data"][0]; $response["data"] = $data; $expired = 365 * 86400 + time(); setcookie("user-id", $email, $expired, "/"); if ($data["esteAdmin"] === "1") $roles = array(array("id" => "admin", "name" => "admin")); else $roles = array(array("id" => "user", "name" => "user")); $menus = MenuRoles::getMenuList($roles); $owners = (new Owner($this->db))->getListAction(); if (!$owners["status"]) return $owners; // $response["extra"] = array("menus" => $menus, "roles" => array("admin", "user"), "owners" => $owners["data"]); $response["menus"] = $menus; $response["owners"] = $owners["data"]; $response["status"] = true; } catch (Exception $error) { $response["errors"] = $error->getMessage(); $response["status"] = false; } $response["extra"]["version"] = APP_VERSION; return $response; } public function loginAction() { require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/User.php"; $response = array(); try { if (!$this->postData->email) throw new Exception("No email provided"); if (!$this->postData->parola) throw new Exception("Nu e parolaaaaa"); $userObj = new User($this->db, null); $users = $userObj->getUserByEmailAndPassword($this->postData->email, $this->postData->parola); if (!$users["status"] || count($users["data"]) != 1) throw new Exception("No user found for email and password provided!"); $expired = 365 * 86400 + time(); setcookie("user-id", $this->postData->email, $expired, "/"); return $this->getUserInfoAction(); } catch (Exception $error) { $response["errors"] = $error->getMessage(); $response["status"] = false; } $response["extra"]["version"] = APP_VERSION; return $response; } public function logoffAction() { require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/User.php"; $response = array(); try { setcookie("user-id", null, 1 + time(), "/"); unset($_COOKIE["user-id"]); return array("status" => true); } catch (Exception $error) { $response["errors"] = $error->getMessage(); $response["status"] = false; } $response["extra"]["version"] = APP_VERSION; return $response; } private function sendResetPassEmail($userEmail, $userName, $guid) { global $email; $email["Subject"] = "Resetare parola Invoicng app pt. " . $userName; $email["To"] = array("email" => $userEmail, "name" => $userName); $email["MsgHTML"] = ""; $email["MsgHTML"] .= "<br>Utilizeaza acest link (numai cu Chrome browser pt. desktop) ptr. resetare parola:<br> "; $email["MsgHTML"] .= "{$_SERVER['HTTP_REFERER']}#!/resetare-parola?id=$guid"; $email["MsgHTML"] .= "<br>Atentie: linkul este valabil o singura data!"; $email["MsgHTML"] .= "<br>Daca ai probleme cu logarea (sau aplicatia), contacteaza-ma la adresa de email <EMAIL>, sau prin telefon la 0730740392."; return sendMail(); } public function resetPasswordAction() { require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/User.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/send-email.php"; $response = array(); try { if (!isset($this->postData->{"email"})) throw new Exception("No email provided"); $userEmail = $this->postData->email; $guid = guidv4(); $userObj = new User($this->db); $user = $userObj->getItemAction(array("email" => $userEmail)); if ($user["status"] && count($user["data"])) { $user["data"]["resetLink"] = $guid; $updateResponse = $userObj->updateAction(false, $user["data"]); if (!$updateResponse["status"]) return $updateResponse; $userName = $updateResponse["data"]["numeComplet"]; $response = $this->sendResetPassEmail($userEmail, $userName, $guid); if (!$response["status"]) return $response; $response = array("status" => true); } else { throw new Exception("No user found for " . $userEmail); } } catch (Exception $error) { $response["errors"] = $error->getMessage(); $response["status"] = false; } return $response; } public function savePasswordAction() { require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/User.php"; try { if (!isset($this->postData->id)) throw new Exception("No id provided"); if (!isset($this->postData->parola)) throw new Exception("No password provided"); $userObj = new User($this->db); $response = $userObj->savePassword($this->postData->id, $this->postData->parola); if (!$response["status"]) { return array("status" => false, "errors" => "Link isn't valid one. Reset again your password"); } $this->postData->email = $response["data"]["email"]; $this->postData->parola = $response["data"]["parola"]; return $this->loginAction(); } catch (Exception $error) { $response = array(); $response["errors"] = $error->getMessage(); $response["status"] = false; } return $response; } }<file_sep>class Owner{ constructor(id, companyId, socialCapital, vatPercentsList, stampPath, logoPath, varRegistred, contactPhone, contactEmail,currencies){ this.id =id; this.companyId = companyId; } }<file_sep><?php $dbConfig = array( "dbName" => "sparknet_invoicing-demo", "user" => "sparknet_inv-dem", "password" => "<PASSWORD>&", "driver" => "Mysqli", "host" => "localhost"); $email = array( "Username" => "", "Password" => "", "From" => ["email" => "", "name" => "Invoicing app"], "Host" => "smtp.gmail.com", "Port" => 587, "SMTPSecure" => "tls", 'Type' => "POP3", ); <file_sep>(function () { angular.module("App").controller("invoicesCodeCtrl", controller); controller.$inject = ['$scope', "axDataAdapter", "$timeout", "axDataSet", "axDataStore", "axApiAction", "$element"]; function controller($scope, $adapter, $timeout, dataSet, axDataStore,apiAction, $element) { $scope.loader = axDataStore.loader("#right-pane"); $scope.$element = $element; $scope.dataStore = axDataStore; $scope.dataSet = dataSet; $scope.invoices = invoicesClass.dataTable($adapter, $scope); $scope.invoices.dateTo = Date.now(); $scope.invoices.loadDataApiArgs = function () { let args = {ownerId: dataSet.currentOwner.id}; if ($scope.invoices.dateFrom) args.from = moment($scope.invoices.dateFrom).format("YYYY-MM-DD"); if ($scope.invoices.dateTo) args.to = moment($scope.invoices.dateTo).format("YYYY-MM-DD"); return args; }; $scope.getDatasourceForCompany = function (datasource, companyId) { if (!datasource) return []; if (!companyId) return datasource; let filtered = datasource.filter(function (item) { return item.companyId === companyId; }, this); // console.log("datasource for company ", companyId, filtered); return filtered; }; $scope.supplier = new invoiceSupplier($scope, $timeout, $adapter); $scope.customer = new invoiceCustomer($scope, $timeout, $adapter, apiAction); } }());<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Country.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/City.php"; class CompanyItem extends ModelItem { public $id; public $name; public $nameInvariant; public $code; public $tradeRegister; public $administratorName; public $countryId; public $cityId; public $county; public $address; } class Company extends BaseModel { public $tableName = "companies"; public $modelItem = "CompanyItem"; public function sqlBuildGetAllItems($where = null, $order = null, $limit = NULL) { $cmd = 'SELECT a.*, c.name as city, c.nameInvariant as cityInvariant, b.name as country, b.nameInvariant as countryInvariant FROM `' . $this->tableName . '` a LEFT JOIN countries b on b.id = a.countryId LEFT JOIN cities c on c.id = a.cityId'; if (isset($where)) $cmd .= $this->sqlBuildWhere($where); return $cmd; } public function getListAction($where = null, $order = null, $limit = NULL) { $response = parent::getListAction($where, $order); if (!$response["status"]) return $response; $countries = (new Country($this->db, json_encode($this->postData)))->getListAction(); if (!$countries["status"]) return $countries; $response["countries"] = $countries["data"]; $cities = (new City($this->db, json_encode($this->postData)))->getListAction(); if (!$cities["status"]) return $cities; $response["cities"] = $cities["data"]; return $response; } public function getItemDetailsAction() { $response = array(); $id = $this->item->id; try { $response["data"] = array(); $response["data"]["phones"] = $this->db->query("Select * from `companies-phones` Where companyId=" . $id)->rows; $response["data"]["emails"] = $this->db->query("Select * from `companies-emails` Where companyId=" . $id)->rows; $response["data"]["emailTemplates"] = $this->db->query("Select * from `companies-email-templates` Where companyId=" . $id)->rows; $response["data"]["accounts"] = $this->db->query("Select * from `companies-accounts` Where companyId=" . $id)->rows; $response["data"]["addresses"] = $this->db->query( "Select `companies-addresses`.*, cities.name as city, cities.nameInvariant as cityInvariant, countries.name as country, countries.nameInvariant as countryInvariant from `companies-addresses` LEFT JOIN countries on countries.id = `companies-addresses`.countryId LEFT JOIN cities on cities.id = `companies-addresses`.cityId Where companyId=" . $id)->rows; $response["status"] = true; } catch (Exception $error) { $field = isset($error->field) ? $error->field : ""; $response["errors"] = [$field => [$error->getMessage()]]; $response["status"] = false; } return $response; } public function validate(&$data = null) { $itemName = "Company"; if (!isset($this->item->name)) { $exception = new Exception("$itemName name is required"); $exception->field = "name"; throw $exception; } if (!isset($this->item->nameInvariant)) { $exception = new Exception("$itemName name is required"); $exception->field = "name"; throw $exception; } if (strlen($this->item->name) < 3) { $exception = new Exception("$itemName name must have at least three characters."); $exception->field = "name"; throw $exception; } $cmd = 'SELECT * from `' . $this->tableName . '` Where name = "' . $this->item->name . '"' . (isset($this->item->id) ? ' AND id !=' . $this->item->id : ''); $queryResult1 = $this->db->query($cmd); if ($queryResult1->num_rows > 0) { $exception = new Exception('The ' . $itemName . ' with name: "' . $this->item->name . '" already exists!'); $exception->field = "name"; throw $exception; } return true; } } <file_sep><?php class BaseController { public $modelClass; public $db; public $postData; public function __construct($dbConnection, $postData = "[]") { $this->db = $dbConnection; $this->postData = json_decode($postData, false); } public function getServerRoot() { return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off" ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'; } public function action($action) { $action .= "Action"; return $this->$action(); } public function catchError(Exception $error) { $response = array(); $field = isset($error->field) ? $error->field : ""; $response["errors"] = [$field => [$error->getMessage()]]; $response["status"] = false; return $response; } public function setOkResponse($data) { $response = array(); $response["data"] = $data; $response["status"] = true; return $response; } } <file_sep><?php $roles = array("admin", "user"); function addMenu($roleId) { $items = array(); if ($roleId == "admin") $items[] = new MenuItem("Users", "users", "app-modules/invoicing/users/users-index.html", [], "fa fa-users"); $items[] = new MenuItem("Owned Companies", "owned-companies", "app-modules/invoicing/owners/owners-index.html", [], "fa fa-building"); $items[] = new MenuItem("Countries", "countries", "app-modules/invoicing/countries/countries-index.html", [], "fa fa-globe"); $items[] = new MenuItem("Cities", "cities", "app-modules/invoicing/cities/cities-index.html", [], "fa fa-globe"); $items[] = new MenuItem("Companies", "companies", "app-modules/invoicing/companies/companies-index.html", [], "fa fa-building-o"); $items[] = new MenuItem("Invoices", "invoices", "app-modules/invoicing/invoices/invoices-index.html", [], "fa fa-money"); return $items; } <file_sep><?php require_once 'vendor/PHPMailer/PHPMailerAutoload.php'; require_once 'vendor/PHPMailer/class.phpmailer.php'; require_once 'vendor/PHPMailer/class.smtp.php'; require_once 'vendor/PHPMailer/class.pop3.php'; function sendMail() { global $email; $debugLevel = 0; $mail = new PHPMailer(true); $mail->SMTPDebug = $debugLevel; $mail->SMTPAuth = true; $mail->IsSMTP(); $mail->Host = $email['Host']; $mail->Port = $email['Port']; $mail->Username = $email['Username']; $mail->Password = $email['<PASSWORD>']; $mail->CharSet = "UTF-8"; $mail->ContentType = 'text/html; charset=utf-8\r\n'; $mail->Encoding = '8bit'; $mail->SetFrom($email['SetFrom']['email'], $email['SetFrom']['name']); if (isset($email['AddReplyTo'])) { $mail->AddReplyTo($email['AddReplyTo']['email'], $email['AddReplyTo']['name']); $mail->AddCC($email['AddReplyTo']['email'], $email['AddReplyTo']['name']); } $mail->Subject = $email['Subject']; $mail->MsgHTML($email['MsgHTML']); $mail->AddAddress($email['To']['email'], $email['To']['name']); $result = $mail->Send(); if ($result) return array("status"=>true); else return array("status"=>false, "error"=>$mail->ErrorInfo); } <file_sep>(function () { angular.module("App").controller("companiesDetailsCtrl", companiesDetailsCtrl); companiesDetailsCtrl.$inject = ['$scope', "axDataAdapter", "apiAction", "axDataSet", "$timeout", "$document"]; function companiesDetailsCtrl($scope, $adapter, apiAction, dataSet, $timeout, $document) { let createCtrl = function () { return { loadDataApiArgs: function () { if ($scope.company.id === 0) return {}; else return {companyId: $scope.company.id}; }, createCallback: function (dataItem) { let takeFrom = $scope.company ? $scope.company : this.currentItem ? this.currentItem : null; if (takeFrom) { dataItem.companyId = $scope.company ? takeFrom.id : takeFrom.companyId; dataItem.company = $scope.company ? takeFrom.name : takeFrom.company; dataItem.companyInvariant = $scope.company ? takeFrom.nameInvariant : takeFrom.companyInvariant; } }, canAdd: function () { return this.$ctrl.$parent.$parent.company && this.$ctrl.$parent.$parent.company.id > 0; } }; }; $scope.dataSet = dataSet; $scope.phones = createCtrl(); $scope.emails = createCtrl(); $scope.accounts = createCtrl(); $scope.addresses = createCtrl(); $scope.emailTemplates = new emailTemplates(createCtrl, $scope); //details are shown in editor if ($scope.$parent.$ctrl.validateForm) { $scope.$watch("$parent.$ctrl.datasource", function (company) { $scope.company = company; if (company && company.id) apiAction('companies', 'getItemDetails', 'post', {item: company}, "no").then(function (response) { if (!response || !$scope.phones.$ctrl) return; $scope.phones.$ctrl.datasourceSet(response.data.phones); $scope.emails.$ctrl.datasourceSet(response.data.emails); $scope.accounts.$ctrl.datasourceSet(response.data.accounts); $scope.addresses.$ctrl.datasourceSet(response.data.addresses); $scope.emailTemplates.$ctrl.datasourceSet(response.data.emailTemplates); }); else { if ($scope.phones.$ctrl && $scope.phones.$ctrl.controllerLoaded) $scope.phones.$ctrl.datasourceSet([]); if ($scope.phones.$ctrl && $scope.emails.$ctrl.controllerLoaded) $scope.emails.$ctrl.datasourceSet([]); if ($scope.phones.$ctrl && $scope.accounts.$ctrl.controllerLoaded) $scope.accounts.$ctrl.datasourceSet([]); if ($scope.phones.$ctrl && $scope.addresses.$ctrl.controllerLoaded) $scope.addresses.$ctrl.datasourceSet([]); if ($scope.emailTemplates.$ctrl && $scope.emailTemplates.$ctrl.controllerLoaded) $scope.emailTemplates.$ctrl.datasourceSet([]); } }); var parent = $scope.$parent.$ctrl.dataTable ? $scope.$parent.$ctrl : $scope.$parent.$ctrl.$parent.$parent.$parent; let editor = $scope.$parent.$parent.$parent.grid.$$editor; editor.form.refreshFormCallback = function () { if (!$scope.getCitiesForCountry) { $scope.getCitiesForCountry = parent.$parent.getCitiesForCountry; $scope.getDataItemCountry = parent.$parent.getDataItemCountry; $scope.countriesEdit = countriesClass.popup( $adapter, { get: function () { return $scope.dataSet.countries; }, set: function (datasource) { $scope.dataSet.countries = datasource; } }, $scope.addresses, { id: "countryId", name: "country", invariant: "countryInvariant" }, "dataTable1", $timeout); $scope.citiesEdit = citiesClass.popup( $adapter, { get: function () { return $scope.dataSet.cities; }, set: function (datasource) { $scope.dataSet.cities = datasource; } }, $scope.addresses, { id: "cityId", name: "city", invariant: "cityInvariant" }, "dataTable1", $timeout); } if ($scope.phones.$ctrl) $scope.phones.$ctrl.inlineEditing = false; if ($scope.emails.$ctrl) $scope.emails.$ctrl.inlineEditing = false; if ($scope.accounts.$ctrl) $scope.accounts.$ctrl.inlineEditing = false; if ($scope.addresses.$ctrl) $scope.addresses.$ctrl.inlineEditing = false; if ($scope.emailTemplates.$ctrl) $scope.emailTemplates.$ctrl.inlineEditing = false; }; editor.form.refreshFormCallback(); } else if ($scope.$parent.launcher) { //details are shown in popup $scope.company = $scope.$parent.popup.openParams[1]; $scope.serverResponse = null; apiAction('companies', 'getItemDetails', 'post', {item: $scope.company}, "no").then(function (response) { if (!response) return; $scope.serverResponse = response.data; }); $scope.$watch(function () { return $scope.serverResponse && $scope.phones.$ctrl //jshint ignore:line && $scope.emails.$ctrl //jshint ignore:line && $scope.accounts.$ctrl //jshint ignore:line && $scope.addresses.$ctrl //jshint ignore:line && $scope.emailTemplates.$ctrl //jshint ignore:line }, function (value) { if (!value) return; $scope.phones.$ctrl.datasourceSet($scope.serverResponse.phones); $scope.emails.$ctrl.datasourceSet($scope.serverResponse.emails); $scope.accounts.$ctrl.datasourceSet($scope.serverResponse.accounts); $scope.addresses.$ctrl.datasourceSet($scope.serverResponse.addresses); $scope.emailTemplates.$ctrl.datasourceSet($scope.serverResponse.emailTemplates); }); let parent = $scope.launcher.$parent.$ctrl; $scope.getCitiesForCountry = parent.$parent.getCitiesForCountry; $scope.getDataItemCountry = parent.$parent.getDataItemCountry; $scope.countriesEdit = countriesClass.popup( $adapter, { get: function () { return $scope.dataSet.countries; }, set: function (datasource) { $scope.dataSet.countries = datasource; } }, $scope.addresses, { id: "countryId", name: "country", invariant: "countryInvariant" }, "dataTable1", $timeout); $scope.citiesEdit = citiesClass.popup( $adapter, { get: function () { return $scope.dataSet.cities; }, set: function (datasource) { $scope.dataSet.cities = datasource; } }, $scope.addresses, { id: "cityId", name: "city", invariant: "cityInvariant" }, "dataTable1", $timeout); } } }()); <file_sep><?php require_once './module/User.php'; define("API_ROOT", "/api/module"); define("ROUTE_PARAM", "_route_"); $routes = array( array("uri" => "account/getUserInfo", "file" => "Account.php", "authorized" => false), array("uri" => "account/login", "file" => "Account.php", "authorized" => false), array("uri" => "account/logoff", "file" => "Account.php", "authorized" => true), array("uri" => "account/resetPassword", "file" => "Account.php", "authorized" => false), array("uri" => "users/*", "file" => "User.php", "class" => "User"), array("uri" => "countries/*", "file" => "Country.php", "class" => "Country"), array("uri" => "cities/*", "file" => "City.php"), array("uri" => "owners/*", "file" => "Owner.php"), array("uri" => "companies/*", "file" => "Company.php"), array("uri" => "companies/getItemDetails", "file" => "Company.php"), array("uri" => "companies-accounts/*", "file" => "CompanyAccount.php"), array("uri" => "companies-addresses/*", "file" => "CompanyAddress.php"), array("uri" => "companies-emails/*", "file" => "CompanyEmail.php"), array("uri" => "companies-email-templates/*", "file" => "CompanyEmailTemplate.php"), array("uri" => "companies-phones/*", "file" => "CompanyPhone.php"), array("uri" => "invoices/*", "file" => "Invoice.php"), array("uri" => "invoices/getInvoiceNumber", "file" => "Invoice.php"), array("uri" => "invoices-details/*", "file" => "InvoiceDetail.php"), array("uri" => "invoices-details/getDescriptions", "file" => "InvoiceDetail.php"), array("uri" => "export/pdf", "file" => "Export.php"), array("uri" => "export/email", "file" => "Export.php"), array("uri" => "cursValutar/getCurs", "file" => "CursValutar.php", "authorized" => false), ); function routeAuthorizing($route, $dbConnection) { if (isset($_COOKIE["user-id"])) { $userClass = new User($dbConnection); $user = $userClass->getItemAction(array("email" => $_COOKIE["user-id"])); if ($user["status"] && $user["data"]["esteActiv"] === "1") return true; return true; } header('HTTP/1.1 401 Not Authorized', true, 401); exit('Not authorized'); return false; }<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Country.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/City.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Company.php"; class CompanyAddressItem extends ModelItem { public $id; public $companyId; public $name; public $countryId; public $cityId; public $county; public $address; } class CompanyAddress extends BaseModel { public $tableName = "companies-addresses"; public $modelItem = "CompanyAddressItem"; public function sqlBuildGetAllItems($where = null, $order = null, $limit = NULL) { $cmd = 'SELECT a.*, b.name as company, b.nameInvariant as companyInvariant, c.name as country, c.nameInvariant as countryInvariant, d.name as city, d.nameInvariant as cityInvariant FROM `' . $this->tableName . '` a LEFT JOIN companies b on b.id = a.companyId LEFT JOIN countries c on c.id = a.countryId LEFT JOIN cities d on d.id = a.cityId'; if (isset($where)) $cmd .= $this->sqlBuildWhere($where); return $cmd; } public function getListAction($where = null, $order = null, $limit = NULL) { try { $cmd = $this->sqlBuildGetAllItems(); if (isset($_REQUEST["companyId"])) { $cmd .= $this->sqlBuildWhere(["a.companyId" => $_REQUEST["companyId"]]); } $cmd .= ' Order By a.companyId '; $queryResult = $this->db->query($cmd); $response = array(); $response["data"] = $queryResult->rows; $countries = (new Country($this->db, json_encode($this->postData)))->getListAction(); if (!$countries["status"]) return $countries; $response["countries"] = $countries["data"]; $cities = (new City($this->db, json_encode($this->postData)))->getListAction(); if (!$cities["status"]) return $cities; $response["cities"] = $cities["data"]; $response["status"] = true; return $response; } catch (Exception $error) { return $this->catchError($error); } } public function validate(&$data = null) { $itemName = "Address"; if (is_null($data)) $item = $this->item; else $item = json_decode(json_encode($data), FALSE); if (!isset($item->name)) { $exception = new Exception("$itemName name is required"); $exception->field = "name"; throw $exception; } if (!isset($item->countryId)) { $exception = new Exception("$itemName country is required"); $exception->field = "countryId"; throw $exception; } if (!isset($item->cityId)) { $exception = new Exception("$itemName city is required"); $exception->field = "cityId"; throw $exception; } return true; } } <file_sep># Invoicing web app <strong>I made this application for personal use. It's built with <a href="https://github.com/bogdanim36/ax-frmk">AxFramework</a> created also by me:</strong> <br> Watch on <a href="https://www.youtube.com/watch?v=ZVCRkUQPRZU&list=PLpuFGPn9OaxKqOYx87pZm5J7tViPyBXEQ">Youtube</a> <br> - Clone this repo: https://github.com/bogdanim36/invoicing. <br> - Run npm install in project folder. <br> - Create you MySQL date base with init-db.sql and create-table.sql. <br> - Create your server (IIS or apache, or. something else). <br> The project is still in progress.... <file_sep>angular.module('ax.components', ["ngDialog", "ui.bootstrap", "ui.router", "as.sortable", "ngFileUpload", 'hmTouchEvents']); /** * @returns {$axTableConfig} */ var $axTableConfig = function () { var separateLanguageFiles = false; var texts = { common: { cancel: {en: 'Cancel', ro: "Renunta"}, ok: {en: "Ok", ro: "De acord"}, clear: {en: "Clear", ro: "Sterge"}, save: {en: "Save", ro: "Salveaza"}, delete: {en: "Delete", ro: "Sterge"}, change: {en: "Change", ro: "Schimba"}, new: {en: "New", ro: "Nou"}, view: {en: "View", ro: "Vezi"}, edit: {en: "Edit", ro: "Modifica"}, "deleteDone!": {en: "Delete done!", ro: "Stergere efectuata!"}, confirmAction: {en: "Confirm action", ro: "Confirma actiunea"}, deleteCurrentItem: {en: "Delete current item?", ro: "Stergi elementul curent?"}, saveOperationNotFinished: {en: "Save operation not finished! Data is not valid! Please check marked fields!", ro: "Oepratia de salvare nu este finalizata!. Datele nu sunt corecte! Verifica campurile marcate!"}, dataNotMeetingValidationCriteria: {en: "Data is not meeting the validation criteria. Save not finished. Please check the fields!", ro: "Datele nu indeplinesc conditiile necesare. Salvarea nu este efectuata. Verifica campurile marcate!"}, saveSuccessful: {en: "Save successful!", ro: "Salvarea este efectuata!"}, dataIsNotSaved: {en: "Data is not saved!", ro: "Datele nu s-au salvat!"} }, pagination: { totalRecords: {en: "Total records", ro: "Total inregistrari"}, fromPage: {en: "From", ro: "De la"}, goToPage: {en: "Go to page", ro: "Du-te la pagina"}, toPage: {en: "to", ro: "la"}, currentPage: {en: "Current page", ro: "Pagina curenta"}, of: {en: "of", ro: "de"}, previous: {en: "Previous page", ro: "Pagina precedenta"}, next: {en: "Next page", ro: "Pagina urmatoare"}, firstPage: {en: "First page", ro: "Prima pagina"}, lastPage: {en: "Last page", ro: "Ultima pagina"}, noRecords: {en: "No records to show!", ro: "Nu sunt inregistrari!"}, pageSizeSetting: {en: "Change records number on page", ro: "Modifica numarul de inregistrari pe pagina"} }, columnHeader: { openMenu: {en: "Click to open column menu!", ro: "Click pt. a deschide meniul coloanei!"} }, toolbar: { apply: {en: 'Apply orders and filters to changed records', ro: "Executa ordonarea si filtrarea ptr. inregistrarile modificate."}, showEditor: {en: "Show editor for add/change/delete records", ro: "Arata editorul pt. adaugare/stergere/modificare inregistrare"}, btnLoad: {en: "Load", ro: "Incarca"}, btnLoading: {en: "Loading", ro: "Se incarca"}, btnSave: {en: "Save", ro: "Salveaza"}, btnSaving: {en: "Saving", ro: "Se salveaza"}, btnApply: {en: "Apply", ro: "Aplica"}, btnApplying: {en: "Applying", ro: "Se aplica"}, btnApplySelected: {en: "Apply Selected", ro: "Executa selectia"}, btnClearAll: {en: "Clear All", ro: "Sterge tot"}, btnSaveProfile: {en: "Save profile", ro: "Salveaza profil"}, btnRun: {en: "Run", ro: "Executa"}, btnRunning: {en: "Running", ro: "Se executa"}, config: {en: "Data table configuration", ro: "Configurare Data Table"}, globalSearchTitle: {en: "Global search options", ro: "Optiuni de cautare globala"}, toggleEditMode: {en: "Toggle edit/readonly mode for data table", ro: "Comuta modul readonly cu editare"}, checkAll: {en: "Check All", ro: "Selecteaza tot"}, uncheckAll: {en: "Uncheck All", ro: "Deselecteaza tot"}, closePopup: {en: "Close popup", ro: "Inchide popup"}, isReadonly: {en: "Edit Data", ro: "Editeaza datele"}, isEditable: {en: "Lock editing", ro: "Blocheaza editare"}, settings: {en: "Settings", ro: "Setari"}, groupsFilter: {en: "Filter records by groups expressions", ro: "Filtrarea inregistrarilor dupa expresiile de grupare"}, profiles: {en: "Profiles", ro: "Profile"}, profileSave: {en: "Save current profile", ro: "Salveaza profilul curent"}, profileLoad: {en: "Load a profile", ro: "Incarca un profil"}, profileDelete: {en: "Delete a profile", ro: "Sterge un profil"}, arrangeRowOrders: {en: 'Set rows order by columns', ro: "Stabileste ordinea inregistrarilor dupa coloane"}, columnsToggleShow: {en: "Show/hide columns", ro: "Afiseaza/ascunde coloane"}, columnsFreezing: {en: "Set columns layout", ro: "Stabileste modul de afisare a coloanelor"}, dataGrouping: {en: "Grouping data records", ro: "Grupeaza inregistrarile"}, dataGroupingEdit: {en: "Edit group properties", ro: "Modifica propritatile gruparii"}, dataGroupingAddCalculation: {en: "Add calculation", ro: "Adauga calcul"}, allRecordsMustHaveFirstLevel: {en: "Group by 'All records' must be first on grouping list", ro: "Grupeaza dupa 'Toate inregistrarile' trebuie sa fie prima in lista de grupari"}, pivotTable: {en: "Pivot Table Design", ro: "Construire Pivot Table"}, clearFilters: {en: "Clear all filters", ro: "Sterge toate filtrele"}, clearAll: {en: "Clear all", ro: "Sterge tot"}, allColumnsAutoFit: {en: "Auto fit all columns width to their visible content", ro: "Stabileste latimile pt. toate coloanele la continutul acestora"}, loadDataTooltip: {en: "Load/refresh data from server", ro: "Incarca datele din server"}, loadData: {en: "Load data", ro: "Incarca datele"}, initialSelect: {en: 'Initial Select', ro: "Selectare initala"}, initialSelectTooltip: {en: "Load initial parameters for report", ro: "Incarca parameterii initiali ai raportului"}, addRecord: {en: "Add", ro: "Adauga"}, addRecordTooltip: {en: "Add record (Ctrl+I)", ro: "Adauga inregistrare (Ctrl+I)"}, dataExport: {en: "Export", ro: "Export"}, toggleFilters: {en: "Show/hide filters row", ro: "Afiseaza/ascunde randul de fitrari"}, dataExportTooltip: {en: "Select data export type.", ro: "Alege tipul de export al datelor"}, xlsExport: {en: "Export data as Excel file", ro: "Exporta datele intr-un fisier Excel"}, viewForPrint: {en: "View data for print", ro: "Vizualizare date pt. tiparire"}, maximize: {en: "Toggle maximize data-table", ro: "Comuta afisarea maximizata"}, confirmDeletion: {en: "Confirm delete item", ro: "Confirma stergere elementului"}, editField: {en: "Edit Field", ro: "Modifica in camp"}, columnNotGroupable: {en: "Selected column is not groupable", ro: "Coloana selectata nu este disponibila pt. grupari"}, noSortableColumns: {en: "No sortable columns found!", ro: "Nu exista coloane dupa care se poate face ordonarea"}, groupsToggle: {en: "Groups", ro: "Grupari"}, groupLevelToggle: {en: "Toggle groups levels", ro: "Comuta ascundearea/afisarea pe toate nivele de grupare"} } }; var config = { sortableClasses: { sortASC: 'fa fa-long-arrow-up', sortDESC: 'fa fa-long-arrow-down', sortABLE: 'glyphicon glyphicon-sort' }, language: "en", default: "en", languages: {en: "English", ro: "Romana"}, texts: texts, defaultAttrs: { customizableDataGrouping: "true", customizablePivotTable: "false", customizableConfig: "true", freezeColumnsEnabled: "true", hideFiltersRowEnabled: "true", columnsAutofitEnabled: "true", customizableFreezedColumns: "true", rowDataHeight: "24", rowHeaderHeight: "28" }, filters: { menu: function (element) { var type = element.getAttribute("data-type"); var defaultMenu = this.menus[type]; if (!defaultMenu) return element; else return defaultMenu(element); }, multiselectDistinctValues(menu) { createElement("ax-column-filter", { type: "dropdown-list-distinctvalues", "selectable-rows": "multiple", "label": "Multiselect from distinct values" }, "", menu); }, inputValue(menu, type, showInPopup, popupWidth) { createElement("ax-column-filter", { type: type, "show-config": "true", showInPopup: showInPopup ? "true" : "false", popupWidth: popupWidth ? popupWidth + "px" : "", "label": "Filter by input value" }, "", menu); }, menus: { string: function (menu) { if (menu.innerHTML.trim() !== "") return menu; config.filters.multiselectDistinctValues(menu); config.filters.inputValue(menu, "text"); return menu; }, text: function (menu) { return config.filters.menus.string(menu); }, boolean: function (menu) { if (menu.innerHTML.trim() !== "") return menu; if (!menu.hasAttribute("convert-type")) menu.setAttribute("convert-type", "boolean"); config.filters.multiselectDistinctValues(menu); return menu; }, number: function (menu) { if (menu.innerHTML.trim() !== "") return menu; config.filters.multiselectDistinctValues(menu); config.filters.inputValue(menu, "number", true, 280); return menu; }, date: function (menu) { if (menu.innerHTML.trim() !== "") return menu; if (!menu.hasAttribute("convert-type")) menu.setAttribute("convert-type", "date"); if (!menu.hasAttribute("convert-input-format")) menu.setAttribute("convert-input-format", "yyyy-MM-ddThh:mm:ss"); if (!menu.hasAttribute("convert-display-format")) menu.setAttribute("convert-display-format", axDateFormat); config.filters.multiselectDistinctValues(menu); config.filters.inputValue(menu, "date", true); return menu; }, datetime: function (menu) { if (menu.innerHTML.trim() !== "") return menu; if (!menu.hasAttribute("convert-type")) menu.setAttribute("convert-type", "datetime"); if (!menu.hasAttribute("convert-input-format")) menu.setAttribute("convert-input-format", "yyyy-MM-ddThh:mm:ss"); if (!menu.hasAttribute("convert-display-format")) menu.setAttribute("convert-display-format", axDateTimeFormat); config.filters.multiselectDistinctValues(menu); config.filters.inputValue(menu, "datetime", true); return menu; } } } }; var privateConfig = new axTableConfig(); axUtils.objectOverwrite(config, privateConfig, false, false, true); return config; }; var focusableElements = '[has-input]:not([disabled]):not([readonly]):not(ax-dropdown-list):not(ax-dropdown-popup):not(ax-table),' + 'button:not([disabled]):not([readonly]):not([tabindex="-1"])'; //var focusableElements = '[has-input]:not([disabled]):not([readonly]):not(ax-dropdown-list):not(ax-dropdown-popup):not(ax-table),' + // '.form-control:not([has-input]):not([disabled]):not([readonly]):not(ax-dropdown-list):not(ax-dropdown-popup):not(ax-table) [has-input],' + // 'button:not([disabled]):not([readonly]):not([tabindex="-1"])'; var convertDataTypes = { date: function (itemValue) { var value; if (itemValue === null || itemValue === undefined) return undefined; else if (typeof itemValue === "string") { value = this.inputFormat ? moment(itemValue, this.inputFormat, true) : moment(itemValue); if (value && value.isValid && value.isValid()) value = value.toDate(); else console.error("date convert error for", itemValue, this.inputFormat, value._f); } else if (typeof itemValue === "object" && itemValue.getTimezoneOffset) value = itemValue; else console.error("Date value must be string or date object"); value.setMinutes(0); value.setSeconds(0); value.setMilliseconds(0); value.setHours(-value.getTimezoneOffset() / 60); // console.log(value.toLocaleDateString()); return value; }, boolean: function (itemValue) { if (itemValue === "true" || itemValue === "True" || itemValue === true || parseInt(itemValue) > 0) return true; else if (itemValue === "" || itemValue === null || itemValue === undefined) return null; else return false; }, integer: function (itemValue) { if (itemValue === "" || itemValue === null || itemValue === undefined) return null; else return parseInt(itemValue); }, float: function (itemValue) { let result; if (itemValue === "" || itemValue === null || itemValue === undefined) result = null; else result = parseFloat(itemValue); // console.log("convert ", itemValue, "to", result); return result; } }; convertDataTypes["date-range"] = convertDataTypes.date; convertDataTypes.datetime = convertDataTypes.date; convertDataTypes["datetime-range"] = convertDataTypes.date; <file_sep>(function () { angular.module("App").controller("ownersCtrl", controller); controller.$inject = ['$scope', "axDataAdapter", "$timeout", "axDataStore", "$element", "Upload", "guidGenerator", "axDataSet", "$element"]; function controller($scope, $adapter, $timeout, axDataStore, $element, Upload, guidGenerator, dataSet) { $scope.loader = axDataStore.loader("#right-pane"); $scope.$element = $element; $scope.dataStore = axDataStore; $scope.dataSet = dataSet; $scope.editingMode = $scope.$parent.launcher ? "popup" : ($scope.$parent.$ctrl && $scope.$parent.$ctrl.attributes && $scope.$parent.$ctrl.attributes.config.includes("$$editor.form") ? "editor" : "page"); if (!$scope.$parent.launcher) $scope.$parent.launcher = {openFinish: false}; var dataTable1 = ownersClass.dataTable($adapter, $scope, Upload, guidGenerator); angular.extend($scope.$parent.launcher, { showButtons: $scope.$parent.launcher.openFinish, dataTable1: dataTable1, }); $scope.companiesEdit = companiesClass.popup( $adapter, { get: function () { return $scope.companies; }, set: function (datasource) { $scope.companies = datasource; } }, dataTable1, { id: "companyId", name: "company", invariant: "companyInvariant" }, "dataTable1", $timeout); if ($scope.editingMode === "editor") { $scope.$parent.$ctrl.config.refreshFormCallback = function (dataItem) { if (!dataTable1.$ctrl || !dataTable1.$ctrl.controllerLoaded) return; //because of ax-editor ng-if $scope.dataTable1.$ctrl is not existing yet and must wait until controlelr is fully loaded (2 digest cycles) //console.log("dataItem", dataItem); if (!dataItem) dataTable1.$ctrl.datasourceSet([]); else dataTable1.$ctrl.loadData(); }; // in this moment refreshForm it's already executed on initialization $scope.$parent.$ctrl.config.refreshFormCallback($scope.$parent.$ctrl.config.dataItem); } } }());<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; class UserItem extends ModelItem { public $id; public $email; public $nume; public $prenume; public $esteActiv; public $esteAdmin; public $numeComplet; public $numeCompletInvariant; public $CNP; public $CiSeries; public $CiNumber; public $CiIssuedBy; public $CiDate; } class User extends BaseModel { public $tableName = "users"; public $modelItem = "UserItem"; public function getUserByEmailAndPassword($email, $password) { $cmd = 'SELECT a.* FROM `' . $this->tableName . '` a '; $cmd .= "LEFT JOIN `users-pw` b on b.userId = a.id "; $cmd .= "WHERE a.email = '{$this->db->escape($email)}' AND b.password = '{$this->db->escape($password)}'"; $queryResult = $this->db->query($cmd); $response = array(); $response["data"] = $queryResult->rows; $response["status"] = true; return $response; } public function savePassword($resetLink, $password) { $userData = $this->getItemAction(array("resetLink" => $resetLink)); if (!$userData["status"]) return $userData; if (count($userData["data"]) == 0) { $userData["status"] = false; return $userData; } try { $user = $userData["data"]; $user["parola"] = $password; $cmd = "DELETE FROM `users-pw` WHERE userId={$this->db->escape($user["id"])}"; $queryResult = $this->db->query($cmd); $cmd = "INSERT INTO `users-pw` SET userId={$this->db->escape($user["id"])}, password='{$this->db->escape($password)}'"; $queryResult = $queryResult && $this->db->query($cmd); $cmd = "UPDATE `users` SET resetLink='' WHERE id = {$this->db->escape($user["id"])}"; $queryResult = $queryResult && $this->db->query($cmd); $response = array(); $response["data"] = $user; $response["status"] = $queryResult; return $response; } catch (Exception $error) { return $this->rollback("save-password"); } } public function validate(&$data = null) { $itemName = "Utilizator"; $item = $this->getDataItem($data); if (!isset($item->email)) { $exception = new Exception("Email $itemName este obligatoriu"); $exception->field = "email"; throw $exception; } if (!isset($item->nume)) { $exception = new Exception("Nume $itemName este obligatoriu"); $exception->field = "nume"; throw $exception; } if (!isset($item->prenume)) { $exception = new Exception("Prenume $itemName este obligatoriu"); $exception->field = "prenume"; throw $exception; } return true; } } <file_sep>class emailTemplates { constructor(createCtrl, $scope) { Object.assign(this, createCtrl($scope)); this.variables = { items: [ { name: "<NAME>", id: "SupplierName", html: " {{SupplierName}} " }, { name: "Invoice Number", id: "InvoiceNumber", html: " {{InvoiceNumber}} " }, { name: "Invoice Date", id: "InvoiceDate", html: " {{InvoiceDate}} " }, { name: "Previous Month Name", id: "PreviousMonthName", html: " {{PreviousMonthName}} " }], allowDrop: function (event) { event.preventDefault(); // console.log("allow", event); }, drag: function (event) { let item = angular.element(event.target).scope().item; event.dataTransfer.setData("text", item.html); event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.dropEffect = "copy"; return true; }, insertAtCursor: function (input, value) { //IE support if (document.selection) { input.focus(); let sel = document.selection.createRange(); sel.text = value; } //MOZILLA/NETSCAPE support else if (input.selectionStart || input.selectionStart == '0') { let startPos = input.selectionStart; let endPos = input.selectionEnd; input.value = input.value.substring(0, startPos) + value + input.value.substring(endPos, input.value.length); } else { input.value += value; } return input.value; }, dropToSubject: function (event) { event.preventDefault(); let data = event.dataTransfer.getData("text"); let $input = angular.element(event.target); let value = $scope.emailTemplates.variables.insertAtCursor($input[0], data); $scope.emailTemplates.$ctrl.$$grid.$$editor.form.$ctrl.datasource.subject = value; $scope.$apply(); }, dragEnter: function (event) { event.preventDefault(); event.target.style["background-color"] = "orange"; }, dragLeave: function (event) { event.preventDefault(); event.target.style["background-color"] = "transparent"; } }; this.ckEditorConfig = { language: 'en', allowedContent: true, width: "100%", height: "150px", entities: false, ready: false, simpleuploads_allowDropOutside: true, onReady: function (ckEditor) { $scope.emailTemplates.ckEditorConfig.ready = true; }, toolbarGroups: [ {name: 'basicstyles', groups: ['basicstyles']}, {name: 'paragraph', groups: ['list', 'indent', 'align']}, {name: 'font'}, {name: 'styles'}, {name: 'colors'}, {name: 'document', groups: ['mode', 'document', 'doctools']}, ] }; } }<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Company.php"; class CompanyPhoneItem extends ModelItem { public $id; public $name; public $phone; public $companyId; } class CompanyPhone extends BaseModel { public $tableName = "companies-phones"; public $modelItem = "CompanyPhoneItem"; public function sqlBuildGetAllItems($where = null, $order = null, $limit = NULL) { $cmd = 'SELECT a.*, b.name as company, b.nameInvariant as companyInvariant FROM `' . $this->tableName . '` a LEFT JOIN `companies` b ON b.id = a.companyId'; if (isset($where)) $cmd .= $this->sqlBuildWhere($where); return $cmd; } public function getListAction($where = null, $order = null, $limit = NULL) { try { $cmd = $this->sqlBuildGetAllItems(); if (isset($_REQUEST["companyId"])) { $cmd .= $this->sqlBuildWhere(["a.companyId" => $_REQUEST["companyId"]]); } $cmd .= ' Order By a.companyId, a.name '; $queryResult = $this->db->query($cmd); $response = array(); $response["data"] = $queryResult->rows; $response["status"] = true; return $response; } catch (Exception $error) { return $this->catchError($error); } } public function validate(&$data = null) { $itemName = "Company Phone"; if (!isset($this->item->companyId)) { $exception = new Exception("Company is required"); $exception->field = "companyId"; throw $exception; } if (!isset($this->item->name)) { $exception = new Exception("$itemName name/alias is required"); $exception->field = "name"; throw $exception; } if (!isset($this->item->phone)) { $exception = new Exception("$itemName phone/fax is required"); $exception->field = "phone"; throw $exception; } return true; } } <file_sep>(function () { 'use strict'; class controller { /** * * @param $scope * @param $element * @param $attrs * @param dataStore {axDataStore} */ constructor($scope, $element, $attrs, dataStore) { this.data = new EmailModel(); this.dataStore = dataStore; this.user = this.dataStore.user.info; /** * @type {axFormCustomCtrl} */ this.formConfig = { /** * * @param fieldName * @param datasource {EmailModel} */ validateField: function (fieldName, datasource) { let value = datasource[fieldName]; switch (fieldName) { case "to": if (value === undefined || value === null || value === "") { this.$ctrl.addFieldError(fieldName, "Field is required", datasource); return false; } break; case "subject": if (value === undefined || value === null || value === "") { this.$ctrl.addFieldError(fieldName, "Field is required", datasource); return false; } break; case "message": if (value === undefined || value === null || value === "") { this.$ctrl.addFieldError(fieldName, "Field is required", datasource); return false; } break; } return true; } }; this.templateChanged = function (template) { this.data.to = template.to; this.data.from = template.from; this.data.subject = template.subjectParsed; this.data.message = template.messageParsed; }; this.dataClear = function(){ this.data.to = ""; this.data.from = ""; this.data.subject = ""; this.data.message = ""; this.data.attachments = []; this.uploadFilesConfig.$ctrl.$files=[]; this.data.selectedTemplate = null; }; this.popupClose = $scope.popupClose; this.ckEditorConfig = { language: 'en', allowedContent: true, width: "100%", height: "150px", entities: false, toolbarGroups: [ {name: 'basicstyles', groups: ['basicstyles']}, {name: 'paragraph', groups: ['list', 'indent', 'align']}, {name: 'font'}, {name: 'styles'}, {name: 'colors'}, {name: 'document', groups: ['mode', 'document', 'doctools']}, ] }; this.uploadFilesConfig = {}; if ($scope.$parent.ngDialogId && $scope.$parent.params) { angular.extend(this.data, $scope.$parent.params.data); if (this.data.templates.length > 0) { this.data.selectedTemplate = this.data.templates[0]; this.templateChanged(this.data.selectedTemplate); } } } send(removeLoader) { let ctrl = this.formConfig.$ctrl; ctrl.clearAllErrors(this.data); if (!ctrl.validateForm()) return; let data = { to: this.data.to, from: this.user.numeComplet + "<" + this.user.email + ">", subject: this.data.subject, message: this.data.message }; if (this.data.remoteAttachment) { data.remoteAttachments = []; data.remoteAttachments.push(this.data.remoteAttachment); } this.messageWasSend = false; this.messageSending = true; this.messageError = false; let popupClose = this.popupClose; this.uploadFilesConfig.$ctrl.uploadAll('export/email', data).then(response => { this.messageSending = false; if (response && response.data.status) { this.messageWasSend = true; setTimeout(function () { popupClose(); }, 500); } else { this.messageError = true; if (response.data.errors) { for (let error in response.data.errors) { ctrl.addGlobalError(error, response.data.errors [error]); } } else ctrl.addGlobalError("", response.data); console.error(response.data); } if (removeLoader) removeLoader(); }, error => { console.error("eroare", error); }); } } angular.module('App').controller('emailController', controller); controller.$inject = ['$scope', "$element", "$attrs", "axDataStore"]; })();<file_sep><?php require_once $_SERVER["DOCUMENT_ROOT"] . "/api/base.model.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Owner.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/Company.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/CompanyAddress.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/CompanyAccount.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/api/module/InvoiceDetail.php"; class InvoiceItem extends ModelItem { public $id; public $ownerId; public $supplierDeliveryAddressId; public $supplierDeliveryAddress; public $supplierDeliveryCounty; public $supplierDeliveryCityId; public $supplierDeliveryCountryId; public $supplierBankAccountId; public $vatRegistred; public $date; public $serial; public $number; public $customerId; public $customerName; public $customerDeliveryCountryId; public $customerDeliveryCounty; public $customerDeliveryCityId; public $customerDeliveryAddress; public $customerDeliveryAddressId; public $customerBankAccountId; public $customerBank; public $total; public $currency; public $vatValue; public $userId; public $createdAt; } class Invoice extends BaseModel { public $tableName = "invoices"; public $modelItem = "InvoiceItem"; public $childrenItems = []; public $children = array("InvoiceDetail" => array( "postData" => 'invoices.details', "foreignKey" => "invoiceId")); public function validate(&$data = null) { $itemName = "Invoice"; if (!isset($this->item->ownerId)) { $exception = new Exception("$itemName owner is required"); $exception->field = "ownerId"; throw $exception; } if (!isset($this->item->supplierDeliveryAddressId)) { $exception = new Exception("Supplier Delivery address is required"); $exception->field = "supplierDeliveryAddressId"; throw $exception; } if (!isset($this->item->supplierBankAccountId)) { $exception = new Exception("Supplier Bank account is required"); $exception->field = "supplierBankAccountId"; throw $exception; } if (!isset($this->item->date)) { $exception = new Exception("$itemName date is required"); $exception->field = "date"; throw $exception; } if (!isset($this->item->serial)) { $exception = new Exception("$itemName series is required"); $exception->field = "serial"; throw $exception; } if (!isset($this->item->number)) { $exception = new Exception("$itemName number is required"); $exception->field = "number"; throw $exception; } if (!isset($this->item->customerId)) { $exception = new Exception("$itemName customer is required"); $exception->field = "customerId"; throw $exception; } if (!isset($this->item->customerDeliveryAddressId)) { $exception = new Exception("$itemName delivery address is required"); $exception->field = "customerDeliveryAddressId"; throw $exception; } if (!isset($this->item->customerBankAccountId)) { $exception = new Exception("$itemName bank account is required"); $exception->field = "customerBankAccountId"; throw $exception; } If (isset($this->item->vatRegistred) && ($this->item->vatRegistred == 'true' || $this->item->vatRegistred == '1')) $this->item->vatRegistred = 1; $cmd = 'SELECT * from `' . $this->tableName . '` Where ownerId = ' . $this->item->ownerId . ' AND serial = "' . $this->item->serial . '" AND number = ' . $this->item->number . (isset($this->item->id) ? ' AND id !=' . $this->item->id : ''); $queryResult1 = $this->db->query($cmd); if ($queryResult1->num_rows > 0) { $exception = new Exception('The ' . $itemName . ' with number: "' . $this->item->number . '" already exists!'); $exception->field = "number"; throw $exception; } $childrenClass = "InvoiceDetail"; $postDataName = $this->children[$childrenClass]["postData"]; if (!isset($this->postData->extraArgs->children->$postDataName)) { $exception = new Exception("$itemName details are required"); throw $exception; } $details = $this->postData->extraArgs->children->$postDataName; if (count($details) === 0) { $exception = new Exception("$itemName details are required"); throw $exception; } $this->childrenItems = array("InvoiceDetail" => $details); $validateChildren = $this->childrenValidate(); if (!$validateChildren) return false; $totals = array("total" => 0, "vat" => 0); foreach ($this->childrenItems["InvoiceDetail"] as $detail) { $totals["vat"] += $detail->vatValue; $totals["total"] += $detail->vatValue + $detail->value; } $this->item->total = $totals["total"]; $this->item->vatValue = $totals["vat"]; return true; } public function sqlBuildGetAllItems($where = null, $order = null, $limit = null) { $cmd = 'SELECT a.*, b.name as customerName, b.nameInvariant as customerInvariant, b.county as customerCounty, b.code as customerCode, b.tradeRegister as customerTradeRegister, e.name as customerCountry, f.name as customerCity, b.address as customerAddress, h.name as supplierDeliveryCountry, i.name as supplierDeliveryCity, g.account as customerBankAccount, c.name as customerDeliveryCountry, d.name as customerDeliveryCity, g.account as customerBankAccount, j.account as supplierBankAccount, j.bank as supplierBank, total, k.numeComplet as userName, k.CNP as userCNP, k.CiSeries as userCiSeries, k.CiNumber as userCiNumber, k.CiIssuedBy as userCiIssuedBy, k.CiDate as userCiDate FROM `' . $this->tableName . '` a LEFT JOIN `companies` b ON b.id = a.customerId LEFT JOIN `countries` c ON c.id = a.customerDeliveryCountryId LEFT JOIN `cities` d ON d.id = a.customerDeliveryCityId LEFT JOIN `countries` e ON e.id = b.countryId LEFT JOIN `cities` f ON f.id = b.cityId LEFT JOIN `companies-accounts` g ON g.id = a.customerBankAccountId LEFT JOIN `countries` h ON h.id = a.supplierDeliveryCountryId LEFT JOIN `cities` i ON i.id = a.supplierDeliveryCityId LEFT JOIN `companies-accounts` j ON j.id = a.supplierBankAccountId LEFT JOIN `users` k ON k.id = a.userId '; if (isset($where)) $cmd .= $this->sqlBuildWhere($where); if (isset($order)) $cmd .= $this->sqlBuildOrder($order); if (isset($limit)) $cmd .= " limit " . $limit; return $cmd; } public function getListAction($where = null, $order = null, $limit = NULL) { $where = array(); if (isset($_REQUEST["ownerId"])) $where[] = array("field" => "ownerId", "operator" => "=", "value" => $_REQUEST["ownerId"]); if (isset($_REQUEST["from"])) $where[] = array("field" => "date", "operator" => ">=", "value" => $_REQUEST["from"]); if (isset($_REQUEST["to"])) $where[] = array("field" => "date", "operator" => "<=", "value" => $_REQUEST["to"]); $limit = isset($_REQUEST["limit"]) ? $_REQUEST["limit"] : null; $response = parent::getListAction($where, $order, $limit); if (!$response["status"]) return $response; $customers = (new Company($this->db, json_encode($this->postData)))->getListAction(); if (!$customers["status"]) return $customers; $response["companies"] = $customers["data"]; $addresses = (new CompanyAddress($this->db, json_encode($this->postData)))->getListAction(); if (!$addresses["status"]) return $addresses; $response["addresses"] = $addresses["data"]; $accounts = (new CompanyAccount($this->db, json_encode($this->postData)))->getListAction(); if (!$accounts["status"]) return $accounts; $response["accounts"] = $accounts["data"]; return $response; } public function copyFieldValue(array $fields, array $source, array &$destination) { foreach ($fields as $field) { $destination[$field] = isset($source[$field]) ? $source[$field] : null; } } public function newAction() { try { $response = parent::newAction(); $ownerId = $_GET["ownerId"]; $lastId = $this->getLastId(array("a.ownerId" => $ownerId)); $lastItem = $this->getItemAction(array("a.id" => $lastId, "a.ownerId" => $ownerId)); if (!$lastItem["status"]) return $lastItem; $fields = array("supplierDeliveryAddressId", "supplierBankAccountId", "serial"); $this->copyFieldValue($fields, $lastItem["data"], $response["data"]); $ownerSrv = new Owner($this->db); $owner = $ownerSrv->getItemQuery($ownerId); $response["data"]["ownerId"] = $ownerId; $response["data"]["vatRegistred"] = $owner["vatRegistred"]; $response["data"]["id"] = 0; $response["data"]["number"] = count($lastItem["data"]) ? (int)$lastItem["data"]["number"] + 1 : 1; $response["data"]["date"] = date('Y-m-d'); $response["data"]["total"] = 0; $response["data"]["vatValue"] = 0; return $response; } catch (\Exception $ex) { return $this->catchError($ex); } } public function getInvoiceNumberAction() { try { $response = array("status" => false, "data"=>array()); if (!isset($_GET["serial"])) throw new Exception("No serial parameter was send"); if (!isset($_GET["ownerId"])) throw new Exception("No ownerId parameter was send"); $lastId = $this->getLastId(array("a.ownerId" => $_GET["ownerId"], "serial" => $_GET["serial"])); if (is_null($lastId)) { $response["data"]["number"] = 1; } else { $lastItem = $this->getItemAction(array("a.id" => $lastId)); if (!$lastItem["status"]) return $lastItem; $response["data"]["number"] = (int)$lastItem["data"]["number"] + 1; } $response["status"]= true; return $response; } catch (\Exception $ex) { return $this->catchError($ex); } } }
1f72ada5616dcef0e9d4bec70f02b56c42e520d0
[ "JavaScript", "SQL", "Markdown", "PHP" ]
31
PHP
pixehub13/invoicingUI
7a67e6733522e6f1a410d4302ba4b66792fb27fd
d712b2424bfbe13d043d7918781a0b2e8fb80f52
refs/heads/master
<file_sep>package io.locative.app.model; public interface JsonRepresentable<T> { String jsonRepresentation(); T fromJsonRepresentation(String json); } <file_sep>package io.locative.app.utils; import android.annotation.TargetApi; import android.os.Build; import android.support.annotation.Nullable; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; interface UrlEncoderInterface { @Nullable String encode(String string); } @TargetApi(Build.VERSION_CODES.KITKAT) class Api19Encoder implements UrlEncoderInterface { private static final String ENCODING = "utf-8"; @Override @Nullable public String encode(String string) { try { return URLEncoder.encode(string, ENCODING); } catch (Exception ex) { return null; } } } class LegacyEncoder implements UrlEncoderInterface { @Override @Nullable @SuppressWarnings("deprecation") public String encode(String string) { return URLEncoder.encode(string); } } public class UrlEncoder { public static String encode(String string) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { return new Api19Encoder().encode(string); } return new LegacyEncoder().encode(string); } } <file_sep>package io.locative.app.view; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.MenuItem; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.Switch; import android.widget.TextView; import com.google.firebase.iid.FirebaseInstanceId; import java.util.UUID; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; import io.locative.app.LocativeApplication; import io.locative.app.R; import io.locative.app.model.Account; import io.locative.app.model.EventType; import io.locative.app.model.Fencelog; import io.locative.app.model.Geofences; import io.locative.app.network.RequestManager; import io.locative.app.utils.Constants; import io.locative.app.utils.Preferences; public class SettingsActivity extends BaseActivity { private Constants.HttpMethod mHttpMethod = Constants.HttpMethod.POST; @BindView(R.id.global_http_url) EditText mUrlText; @BindView(R.id.global_http_method_button) Button mGlobalHttpMethodButton; @BindView(R.id.global_auth_switch) Switch mGlobalHttpAuthSwitch; @BindView(R.id.global_auth_username) EditText mGlobalHttpAuthUsername; @BindView(R.id.global_auth_password) EditText mGlobalHttpAuthPassword; @BindView(R.id.send_test_button) Button mSendTestButton; @BindView(R.id.notification_success_switch) Switch mNotificationSuccessSwitch; @BindView(R.id.notification_fail_switch) Switch mNotificationFailSwitch; @BindView(R.id.notification_only_latest_switch) Switch mNotificationOnlyLatestSwitch; @BindView(R.id.notification_sound_switch) Switch mNotificationSoundSwitch; @BindView(R.id.trigger_threshold_enabled_switch) Switch mTriggerThresholdEnabled; @BindView(R.id.trigger_threshold_seekbar) SeekBar mTriggerThresholdSeekBar; @BindView(R.id.trigger_threshold_notice) TextView mTriggerThresholdNotice; @Inject RequestManager mRequestManager; private void updateThresholdNotice() { if (mTriggerThresholdEnabled.isChecked()) { mTriggerThresholdNotice.setText(getString(R.string.trigger_threshold_notice, mTriggerThresholdSeekBar.getProgress())); return; } mTriggerThresholdNotice.setText(getString(R.string.trigger_threshold_notice_disabled)); } private void setupThreshold() { mTriggerThresholdEnabled.setChecked(mPrefs.getBoolean(Preferences.TRIGGER_THRESHOLD_ENABLED, false)); mTriggerThresholdSeekBar.setEnabled(mTriggerThresholdEnabled.isChecked()); mTriggerThresholdSeekBar.setProgress(mPrefs.getInt(Preferences.TRIGGER_THRESHOLD_VALUE, Preferences.TRIGGER_THRESHOLD_VALUE_DEFAULT) / 1000); mTriggerThresholdSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { updateThresholdNotice(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mTriggerThresholdEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { mTriggerThresholdSeekBar.setEnabled(b); updateThresholdNotice(); } }); updateThresholdNotice(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((LocativeApplication) getApplication()).getComponent().inject(this); mUrlText.setText(mPrefs.getString(Preferences.HTTP_URL, null)); mGlobalHttpMethodButton.setText( mPrefs.getInt(Preferences.HTTP_METHOD, 0) == 0 ? "POST" : "GET" ); mGlobalHttpAuthSwitch.setChecked( mPrefs.getBoolean(Preferences.HTTP_AUTH, false) ); switchHttpAuth(); mGlobalHttpAuthUsername.setText(mPrefs.getString(Preferences.HTTP_USERNAME, null)); mGlobalHttpAuthPassword.setText(mPrefs.getString(Preferences.HTTP_PASSWORD, null)); mNotificationSuccessSwitch.setChecked(mPrefs.getBoolean(Preferences.NOTIFICATION_SUCCESS, false)); mNotificationFailSwitch.setChecked(mPrefs.getBoolean(Preferences.NOTIFICATION_FAIL, false)); mNotificationOnlyLatestSwitch.setChecked(mPrefs.getBoolean(Preferences.NOTIFICATION_SHOW_ONLY_LATEST, false)); mNotificationSoundSwitch.setChecked(mPrefs.getBoolean(Preferences.NOTIFICATION_SOUND, false)); mHttpMethod = (Constants.HttpMethod.POST.ordinal() == mPrefs.getInt(Preferences.HTTP_METHOD, 0)) ? Constants.HttpMethod.POST : Constants.HttpMethod.GET; } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: save(true); return true; } return false; } @Override protected void onStart() { super.onStart(); setupThreshold(); } @Override public void onResume() { super.onResume(); } @Override protected int getLayoutResourceId() { return R.layout.activity_settings; } @Override protected String getToolbarTitle() { return "Settings"; } @Override protected int getMenuResourceId() { return R.menu.settings; } @OnClick(R.id.global_auth_switch) public void switchHttpAuth() { mGlobalHttpAuthUsername.setEnabled(mGlobalHttpAuthSwitch.isChecked()); mGlobalHttpAuthPassword.setEnabled(mGlobalHttpAuthSwitch.isChecked()); } @OnClick(R.id.send_test_button) public void sendTestRequest() { final String locationId = "test"; if (mUrlText.getText().length() == 0) { new AlertDialog.Builder(this) .setTitle(R.string.note) .setMessage(R.string.please_login_to_test_request) .setNeutralButton(R.string.ok, null) .show(); return; } Geofences.Geofence geofence = new Geofences.Geofence( UUID.randomUUID().toString(), // ID locationId, // Custom ID "Test Location", // Name 0, // Triggers 0.00f, // Lat 0.00f, // Lng 50, // Radius 0, // Auth null, // Auth User null, // Auth Passwd 0, // Enter Method null, // Enter Url 0, // Exit Method null, // Exit Url 0 // Currently Entered ); mRequestManager.dispatch(geofence, EventType.ENTER); new AlertDialog.Builder(this) .setTitle(R.string.note) .setMessage(R.string.test_request_sent_message) .setNeutralButton(R.string.ok, null) .show(); } @OnClick(R.id.global_http_method_button) public void selectMethodForTriggerType() { new AlertDialog.Builder(this) .setMessage("Choose HTTP Method") .setPositiveButton("POST", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mGlobalHttpMethodButton.setText("POST"); mHttpMethod = Constants.HttpMethod.POST; } }) .setNeutralButton("GET", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mGlobalHttpMethodButton.setText("GET"); mHttpMethod = Constants.HttpMethod.GET; } }) .show(); } private void save(boolean finish) { SharedPreferences.Editor editor = mPrefs.edit(); editor.putString(Preferences.HTTP_URL, mUrlText.getText().toString()); editor.putInt(Preferences.HTTP_METHOD, mHttpMethod.ordinal()); editor.putBoolean(Preferences.HTTP_AUTH, mGlobalHttpAuthSwitch.isChecked()); editor.putString(Preferences.HTTP_USERNAME, mGlobalHttpAuthUsername.getText().toString()); editor.putString(Preferences.HTTP_PASSWORD, mGlobalHttpAuthPassword.getText().toString()); editor.putBoolean(Preferences.NOTIFICATION_SUCCESS, mNotificationSuccessSwitch.isChecked()); editor.putBoolean(Preferences.NOTIFICATION_FAIL, mNotificationFailSwitch.isChecked()); editor.putBoolean(Preferences.NOTIFICATION_SHOW_ONLY_LATEST, mNotificationOnlyLatestSwitch.isChecked()); editor.putBoolean(Preferences.NOTIFICATION_SOUND, mNotificationSoundSwitch.isChecked()); editor.putBoolean(Preferences.TRIGGER_THRESHOLD_ENABLED, mTriggerThresholdEnabled.isChecked()); editor.putInt(Preferences.TRIGGER_THRESHOLD_VALUE, mTriggerThresholdSeekBar.getProgress() * 1000); editor.apply(); if (finish) { finish(); } } }
2b1f96404a252d4b969cf8d213dfa3ba2fd7194e
[ "Java" ]
3
Java
bad-bird/Locative-Android
fa9dc4b2a1748757dc0f1505c6c539bab6c7977e
f7677d0965cb84f5a3572065fcd0ea1ca10b010e
refs/heads/master
<repo_name>MTG2000/jwt-cookies<file_sep>/index.js const express = require("express"); const app = express(); const cookieParser = require("cookie-parser"); require("dotenv").config(); const dev = app.get("env") !== "production"; if (!dev) { app.disable("x-powerd-by"); app.use(morgan("common")); app.use(compression()); } const PORT = parseInt(process.env.PORT) || 5000; // server.use(cors()); app.use(cookieParser()); app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use("/api/users", require("./routes/users.route")); app.listen(PORT, () => { console.log(`Listening on port : ${PORT}`); }); <file_sep>/routes/users.route.js const router = require("express").Router(); const authService = require("../services/auth"); const authMiddleware = require("../middleware/auth"); const users = [ { name: "mtg", pwd: "123", role: "admin" }, { name: "ahmad", pwd: "123", role: "doctor" }, { name: "nizar", pwd: "123", role: "user" } ]; router.post("/login", (req, res) => { //Verify credentials const { name, pwd } = req.body; const user = users.filter(u => u.name === name && u.pwd === pwd)[0]; if (!user) //User Doesn't exist or wrong credentials return res.status(500).json("Incorrect Credentials"); const token = authService.generateToken({ name: user.name, role: user.role }); //set cookie with the token res .cookie("token", token, { secure: false, // set to true if your using https httpOnly: true }) .status(200) .send("Successfully login"); }); router.get("/private", authMiddleware, (req, res) => { res.send(req.user); }); module.exports = router;
cd8415d4cf9c348ed3cdba968260c5c26fb66f05
[ "JavaScript" ]
2
JavaScript
MTG2000/jwt-cookies
db09dfa1a3ece23841f6f4a258c292354c5a6981
2f850bf345f30ba712bed0c8a9487cdbd0bf835e
refs/heads/master
<file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "time" // "sync" "net/http" ) // Quote is holder for recent quote data type Quote struct { Symbol string `json:"symbol"` Name string `json:"companyName"` Latest float32 `json:"latestPrice"` LatestUpdate int64 `json:"latestUpdate"` MarketOpen bool `json:"isUSMarketOpen"` NextCheckTime int64 } // Config is a configuration struct type Config struct { Symbols []string } var apiToken string = os.Getenv("IEX_TOKEN") var baseURL string = "https://cloud.iexapis.com/" var configuration Config func getQuote(symbol string) Quote { resp, err := http.Get(baseURL + "/stable/stock/" + symbol + "/quote?token=" + apiToken) if err != nil { log.Fatalln(err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatalln(err) } var quote Quote json.Unmarshal(body, &quote) if quote.MarketOpen { quote.NextCheckTime = time.Unix(quote.LatestUpdate/1000.0+30, 0).Unix() } else { quote.NextCheckTime = time.Now().Add(time.Hour).Unix() } return quote } func main() { // var mu = &sync.Mutex{} fmt.Println("Starting symbol iteration...") file, err := os.Open("./config/config.json") if err != nil { fmt.Println("Error Opening File config.json!!!") fmt.Println(err) } decoder := json.NewDecoder(file) err = decoder.Decode(&configuration) if err != nil { fmt.Println("Error Decoding JSON!!!") fmt.Println(err) } fmt.Println(configuration.Symbols) for _, symbol := range configuration.Symbols { var latestQuote Quote = getQuote(symbol) fmt.Printf("%+v\n", latestQuote) } } <file_sep>package main import "testing" func TestGetQuote(t *testing.T) { // Test for AAPL appleResult := getQuote("AAPL") if appleResult.Name != "Apple Inc" { t.Errorf("getQuote failed, expected %v for Name field, got %v", "Apple Inc", appleResult.Name) } } <file_sep># Go Stonks Go This library is intended to be a simple service for fetching stock data. Over time, the intention is to expand to supporting services like Charting, What-If, and Monitor. # Requirements The following is required for go-stonks * iexcloud API key * go-1.15 * iexcloud API key saved to env variable IEX_TOKEN # Usage First, configure symbols in `config/config.json`. Then, build `go-stonks` and Go!<file_sep>module github.com/dblclik/go-stonks go 1.15
153c36b34f2387ac6b0aeaf31bdbb42f98164cc5
[ "Markdown", "Go Module", "Go" ]
4
Go
dblclik/go-stonks
cbdb87962141772e651dc5d73f0c1c2b71d3d3f6
e078216c91108f6141c6ead66fc90335a2ac3cf9
refs/heads/master
<file_sep>FROM alpine:3.8 # install without cache RUN apk update && apk add --no-cache \ ca-certificates \ iptables \ && update-ca-certificates ADD ./nmi /bin/nmi ENTRYPOINT ["nmi"]<file_sep>FROM alpine:3.8 # install without cache RUN apk update && apk add --no-cache \ ca-certificates \ iptables \ && update-ca-certificates ADD ./mic /bin/mic ENTRYPOINT ["mic"]<file_sep>package cloudprovider import ( "reflect" "testing" "github.com/Azure/go-autorest/autorest/azure" ) func TestParseResourceID(t *testing.T) { type testCase struct { desc string testID string expect azure.Resource xErr bool } notNested := "/subscriptions/asdf/resourceGroups/qwerty/providers/testCompute/myComputeObjectType/testComputeResource" nested := "/subscriptions/asdf/resourceGroups/qwerty/providers/testCompute/myComputeObjectType/testComputeResource/someNestedResource/myNestedResource" for _, c := range []testCase{ {"empty string", "", azure.Resource{}, true}, {"just a string", "asdf", azure.Resource{}, true}, {"partial match", "/subscriptions/asdf/resourceGroups/qwery", azure.Resource{}, true}, {"nested", nested, azure.Resource{ SubscriptionID: "asdf", ResourceGroup: "qwerty", Provider: "testCompute", ResourceName: "testComputeResource", ResourceType: "myComputeObjectType", }, false}, {"not nested", notNested, azure.Resource{ SubscriptionID: "asdf", ResourceGroup: "qwerty", Provider: "testCompute", ResourceName: "testComputeResource", ResourceType: "myComputeObjectType", }, false}, } { t.Run(c.desc, func(t *testing.T) { r, err := ParseResourceID(c.testID) if (err != nil) != c.xErr { t.Fatalf("expected err==%v, got: %v", c.xErr, err) } if !reflect.DeepEqual(r, c.expect) { t.Fatalf("resource does not match expected:\nexpected:\n\t%+v\ngot:\n\t%+v", c.expect, r) } }) } } <file_sep>FROM alpine RUN apk add --no-cache bash && \ apk add --no-cache curl ADD ./identityvalidator ./bin/identityvalidator # Use "kubectl exec <pod name> -- identityvalidator --subscriptionid=<...> --clientid=<...> --resourcegroup=<...>" to execute the validator ENTRYPOINT [ "/bin/bash", "-c" ]<file_sep>ORG_PATH=github.com/Azure PROJECT_NAME := aad-pod-identity REPO_PATH="$(ORG_PATH)/$(PROJECT_NAME)" NMI_BINARY_NAME := nmi MIC_BINARY_NAME := mic DEMO_BINARY_NAME := demo IDENTITY_VALIDATOR_BINARY_NAME := identityvalidator NMI_VERSION=1.3 MIC_VERSION=1.2 DEMO_VERSION=1.2 IDENTITY_VALIDATOR_VERSION=1.0 VERSION_VAR := $(REPO_PATH)/version.Version GIT_VAR := $(REPO_PATH)/version.GitCommit BUILD_DATE_VAR := $(REPO_PATH)/version.BuildDate BUILD_DATE := $$(date +%Y-%m-%d-%H:%M) GIT_HASH := $$(git rev-parse --short HEAD) ifeq ($(OS),Windows_NT) GO_BUILD_MODE = default else UNAME_S := $(shell uname -s) ifeq ($(UNAME_S), Linux) GO_BUILD_MODE = pie endif ifeq ($(UNAME_S), Darwin) GO_BUILD_MODE = default endif endif GO_BUILD_OPTIONS := -buildmode=${GO_BUILD_MODE} --tags "netgo osusergo" -ldflags "-s -X $(VERSION_VAR)=$(NMI_VERSION) -X $(GIT_VAR)=$(GIT_HASH) -X $(BUILD_DATE_VAR)=$(BUILD_DATE) -extldflags '-static'" E2E_TEST_OPTIONS := -count=1 -v # useful for other docker repos REGISTRY ?= mcr.microsoft.com/k8s/aad-pod-identity NMI_IMAGE_NAME := $(REGISTRY)/$(NMI_BINARY_NAME) MIC_IMAGE_NAME := $(REGISTRY)/$(MIC_BINARY_NAME) DEMO_IMAGE_NAME := $(REGISTRY)/$(DEMO_BINARY_NAME) IDENTITY_VALIDATOR_IMAGE_NAME := $(REGISTRY)/$(IDENTITY_VALIDATOR_BINARY_NAME) clean-nmi: rm -rf bin/$(PROJECT_NAME)/$(NMI_BINARY_NAME) clean-mic: rm -rf bin/$(PROJECT_NAME)/$(MIC_BINARY_NAME) clean-demo: rm -rf bin/$(PROJECT_NAME)/$(DEMO_BINARY_NAME) clean-identity-validator: rm -rf bin/$(PROJECT_NAME)/$(IDENTITY_VALIDATOR_BINARY_NAME) clean: rm -rf bin/$(PROJECT_NAME) build-nmi:clean-nmi PKG_NAME=github.com/Azure/$(PROJECT_NAME)/cmd/$(NMI_BINARY_NAME) $(MAKE) bin/$(PROJECT_NAME)/$(NMI_BINARY_NAME) build-mic:clean-mic PKG_NAME=github.com/Azure/$(PROJECT_NAME)/cmd/$(MIC_BINARY_NAME) $(MAKE) bin/$(PROJECT_NAME)/$(MIC_BINARY_NAME) build-demo: build_tags := netgo osusergo build-demo:clean-demo PKG_NAME=github.com/Azure/$(PROJECT_NAME)/cmd/$(DEMO_BINARY_NAME) ${MAKE} bin/$(PROJECT_NAME)/$(DEMO_BINARY_NAME) bin/%: GOOS=linux GOARCH=amd64 go build $(GO_BUILD_OPTIONS) -o "$(@)" "$(PKG_NAME)" build-identity-validator:clean-identity-validator PKG_NAME=github.com/Azure/$(PROJECT_NAME)/test/e2e/$(IDENTITY_VALIDATOR_BINARY_NAME) $(MAKE) bin/$(PROJECT_NAME)/$(IDENTITY_VALIDATOR_BINARY_NAME) build:clean build-nmi build-mic build-demo build-identity-validator deepcopy-gen: deepcopy-gen -i ./pkg/apis/aadpodidentity/v1/ -o ../../../ -O aadpodidentity_deepcopy_generated -p aadpodidentity image-nmi: cp bin/$(PROJECT_NAME)/$(NMI_BINARY_NAME) images/nmi docker build -t $(NMI_IMAGE_NAME):$(NMI_VERSION) images/nmi image-mic: cp bin/$(PROJECT_NAME)/$(MIC_BINARY_NAME) images/mic docker build -t $(MIC_IMAGE_NAME):$(MIC_VERSION) images/mic image-demo: cp bin/$(PROJECT_NAME)/$(DEMO_BINARY_NAME) images/demo docker build -t $(DEMO_IMAGE_NAME):$(DEMO_VERSION) images/demo image-identity-validator: cp bin/$(PROJECT_NAME)/$(IDENTITY_VALIDATOR_BINARY_NAME) images/identityvalidator docker build -t $(IDENTITY_VALIDATOR_IMAGE_NAME):$(IDENTITY_VALIDATOR_VERSION) images/identityvalidator image:image-nmi image-mic image-demo image-identity-validator push-nmi: docker push $(NMI_IMAGE_NAME):$(NMI_VERSION) push-mic: docker push $(MIC_IMAGE_NAME):$(MIC_VERSION) push-demo: docker push $(DEMO_IMAGE_NAME):$(DEMO_VERSION) push-identity-validator: docker push $(IDENTITY_VALIDATOR_BINARY_NAME):$(IDENTITY_VALIDATOR_VERSION) push:push-nmi push-mic push-demo push-identity-validator e2e: go test github.com/Azure/$(PROJECT_NAME)/test/e2e $(E2E_TEST_OPTIONS) unit-test: go test $(shell go list ./... | grep -v /test/e2e) -v .PHONY: build <file_sep>package cloudprovidertest import ( "flag" "testing" "github.com/Azure/aad-pod-identity/pkg/config" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestSimple(t *testing.T) { flag.Set("logtostderr", "true") flag.Set("v", "3") flag.Parse() for _, cfg := range []config.AzureConfig{ config.AzureConfig{}, config.AzureConfig{VMType: "vmss"}, } { desc := cfg.VMType if desc == "" { desc = "default" } t.Run(desc, func(t *testing.T) { cloudClient := NewTestCloudClient(cfg) node0 := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "node0"}} node1 := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "node1"}} node2 := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "node2"}} cloudClient.AssignUserMSI("ID0", node0) cloudClient.AssignUserMSI("ID0", node0) cloudClient.AssignUserMSI("ID0again", node0) cloudClient.AssignUserMSI("ID1", node1) cloudClient.AssignUserMSI("ID2", node2) testMSI := []string{"ID0", "ID0again"} if !cloudClient.CompareMSI("node0", testMSI) { t.Fatal("MSI mismatch") } cloudClient.RemoveUserMSI("ID0", node0) cloudClient.RemoveUserMSI("ID2", node2) testMSI = []string{"ID0again"} if !cloudClient.CompareMSI(node0.Name, testMSI) { t.Fatal("MSI mismatch") } testMSI = []string{} if !cloudClient.CompareMSI(node2.Name, testMSI) { t.Fatal("MSI mismatch") } }) } }
963e71a1b308f20aa82b791814ae956c5f3077c0
[ "Makefile", "Go", "Dockerfile" ]
6
Dockerfile
ASOS/aad-pod-identity
58d2141ea4dc55409da3cd248d1335e4b6451689
63b66c80533ecd94202c1243eb63acf9f33362ba
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; // services can easily fetch data and need to be used bc components should only focus on displaying data import { Observable, of } from 'rxjs'; import { Hero } from '../hero'; import { mockHeroes } from '../mock-heroes'; // importing the whole array import { MessageService } from './message.service'; @Injectable({ providedIn: 'root' // provider provides service to be injected into components }) export class HeroService { getHeroes(): Observable<Hero[]> { this.messageService.add('HeroService fetched the heroes') return of(mockHeroes); // return whole array (as an observable) } getHero(id: number): Observable<Hero> { this.messageService.add('HeroService: fetched ID ' + id) return of(mockHeroes.find(hero => hero.id === id)); } constructor(private messageService: MessageService) { } } <file_sep>import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MessageService { messages: string[] = []; add(message: string) { this.messages.push(message); // push method is available to all arrays and "Appends new elements to an array, and returns the new length." (length = number of elements) } // basically it adds the message from the parameter to the this.message-array clear() { this.messages = []; } }<file_sep>import { createReducer, on } from '@ngrx/store'; import { loadingData } from './api.actions'; export const initialState = {}; const _apiReducer = createReducer( initialState, on(loadingData, (state, { employees }) => ({ ...state, employees: employees })) ); export function apiReducer(state, action) { return _apiReducer(state, action); }<file_sep>import { Component, OnInit } from '@angular/core'; import { ApiService } from '../services/api.service' import { MessageService } from '../services/message.service'; import { HttpClient } from '@angular/common/http' import { fetchData, loadingData } from '../api.actions'; import { Store, select } from '@ngrx/store'; @Component({ selector: 'app-apireq', templateUrl: './apireq.component.html' }) export class ApireqComponent implements OnInit { raw: any; data: any; dataArray = []; constructor(private apiService: ApiService, private messageService: MessageService, private store: Store<{ employees: any }>, private httpClient: HttpClient) { } ngOnInit(): void { // this.raw = this.apiService.getData(); this.store.dispatch(fetchData()); this.store.select(loadingData).subscribe(Response => { this.data = Response; console.log(Response)}); } onClick() { this.dataArray = this.data.list; this.messageService.add('APIRequestComponent: fetched data from API'); // new selector (api.selector.ts) } } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HeroesComponent } from './heroes/heroes.component'; import { HeroDashboardComponent } from './hero-dashboard/hero-dashboard.component'; import { HeroDetailComponent } from './hero-detail/hero-detail.component'; import { ApireqComponent } from './apireq/apireq.component'; const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, // default route { path: 'dashboard', component: HeroDashboardComponent }, // i have no clue what the dashboard is but make a link to it pls or switch the routerLink in appComponent to '' :D { path: 'heroes', component: HeroesComponent }, { path: 'detail/:id', component: HeroDetailComponent }, { path: 'fetch', component: ApireqComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { createAction, props } from '@ngrx/store'; export const fetchData = createAction('[API Component] set to fetched'); export const loadingData = createAction('[API Page] Employees Loaded Success', props<{ employees: any }>()); // increment, decrement and reset are all actions (declared as variables) <file_sep>import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType, Effect } from '@ngrx/effects'; import { EMPTY } from 'rxjs'; import { map, mergeMap, catchError } from 'rxjs/operators'; import { ApiService } from './services/api.service'; @Injectable() export class ApiEffects { loadEmployees$ = this.actions$.pipe( ofType('[API Component] set to fetched'), mergeMap(() => this.apiService.getData().pipe( map(employees => ({ type: '[API Page] Employees Loaded Success', payload: employees })), catchError(() => EMPTY) )) ); constructor( private actions$: Actions, private apiService: ApiService ) { } }
a09e01b9b70cbdfc9f72c01e33eeb2a4d2a09487
[ "TypeScript" ]
7
TypeScript
NicolasHirsig/InternshipProject
1867e313c18df9d6c1b01a38214c3f4038cd2db9
1bbddac7eccb7ea95f115f78bbb9da71c57232c2
refs/heads/master
<repo_name>sajjadgol/contact-package<file_sep>/src/config/contact.php <?php return [ 'send_mail_to' => '<EMAIL>' ]; <file_sep>/src/Http/Controllers/ContactController.php <?php namespace Sgol\Contact\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use Sgol\Contact\Mail\ContactMail; use Sgol\Contact\Models\Contact; class ContactController extends Controller { public function index() { return view('contact::contact'); } public function send(Request $request) { Mail::to(config('contact.send_mail_to'))->send(new ContactMail($request->message , $request->name )); Contact::create($request->all()); return redirect(route('contact')); } }
bd482fed44d8876df302c01c73594564d28cafd3
[ "PHP" ]
2
PHP
sajjadgol/contact-package
6bb739fb49eb42f1f9e741504e845cc90a8c7a67
9a34d7be08f097b64e4e25cffeabd842559dd2c0
refs/heads/master
<repo_name>rosehgal/codeBin<file_sep>/codeBin/snippets/views.py from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer #Allow the clien to make the posst request with out CSRF token @csrf_exempt #Request is a stream of JSON text from api call def snippet_list(request): if request.method == 'POST': data = data.JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status=400) elif request.method == 'GET': snippets = Snippet.objects.all() serializers = SnippetSerializer(snippets,many=True) return JsonResponse(serializers.data,safe=False) def snippet_details(request,pk): try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesnotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SnippetSerializer(snippet) return JsonResponse(serializer.data,safe=False) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet,data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors,status=400) elif request.method == 'DELETE': snippet.delete() return HttpResponse(204) <file_sep>/codeBin/snippets/urls.py from django.conf.urls import url from snippets import views urlpatterns = [ url(r'^snippets/$',views.snippet_list,name='all_snippets'), url(r'^snippets/(?P<pk>[0-9]+)/$',views.snippet_details,name='individual_snippet'), ] <file_sep>/codeBin/requirements.txt Django==1.11.5 djangorestframework==3.6.4 MySQL-python==1.2.5 Pygments==2.2.0 pytz==2017.2 <file_sep>/codeBin/snippets/models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles #getting the list of lexers,languages and the available styles from the Pygments LEXERS = [lexer for lexer in get_all_lexers() if lexer[1]] LANGUAGES = sorted([(item[1][0],item[0]) for item in LEXERS]) STYLECHOICES = sorted((item,item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100,blank=True,default='') linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGES,default='python',max_length=100) style = models.CharField(choices=STYLECHOICES,default='friendly',max_length=100) code = models.TextField() <file_sep>/README.md # codeBin A Simple Dummy application written in Django - A paste bin for Codes
68bcabff8b3d22cbd31e9d900be35158aea6b8c8
[ "Markdown", "Python", "Text" ]
5
Python
rosehgal/codeBin
5ce59ffb1dedc9115473814aa95e050c341572c9
6eb1ad224877b1b851283fcbd029e2a54af1f3e7
refs/heads/master
<repo_name>wybeturing/AfriHackWork<file_sep>/counter.py def counter(filename): k = open(filename, 'r').readlines() num_line = len(k) num_words = 0 num_char = 0 for line in k: num_words += len(line.split()) num_char += len(line) return (num_line, num_words, num_char) def main(): name = input("Enter the name of the file: ") try: print(name, "has", counter(name)[0], "lines") print(name, "has", counter(name)[1], "words") print(name, "has", counter(name)[2], "characters") except: print('Please make sure to check one of the following:\n\t1. The file name is correct\n\t2.The extension is valid for the python file operations, and you are actually typing it in\n\t3. Your script is stored in thesame location as your file\n\tTRY AGAIN PLEASE') main() <file_sep>/kivyStarter.py import kivy kivy.require('1.0.6') from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput class LoginScreen(GridLayout): def __init(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) self.cols = 2 self.add_widget(Label(text = "<NAME>")) self.username = TextInput(multiline = False) self.add_widget(self.username) self.add_widget(Label(text = "password")) self.password = TextInput(password=True, multiline=False) self.add_widget(self.password) class KarlFirst(App): def build(self): return LoginScreen() if __name__ == "__main__": KarlFirst().run()<file_sep>/classWork.py # Question 4 programming exercices chapter 6 # Calculating the sum of the natural numbers def sumN(n): return (n*(n+1))/2 # Calculatinmg the sum of the cubes of the numbers def sumNCubes(n): sumN = 0 for i in range(1,n+1): sumN = sumN + i**3 return sumN def main(): num = int(input("Please enter a natural number: ")) print("The sum of the natural numbers up to", num, "is: ", sumN(num)) print("The sum of the cubes of the natural numbers up to", num, "is:", sumNCubes(num)) # Question 3 programming exercices chapter 6 # Calculating the area of a sphere def sphereArea(r): return (22/7)*4*(r**2) # Calculating the volume of a sphere def sphereVolume(r): return (22/7)*(r**3)*(4/3) def main2(): num = eval(input("Please enter the radius of the sphere: ")) print("The surface area of the sphere is: ", sphereArea(num), "square units") print("The volume of the sphere is: ", sphereVolume(num), "cubic units") # Question 6 programming exercices chapter 6 # calculating the area of a triangle using Heron's formular def triangleArea(a, b, c): from math import sqrt k = (a + b + c) / 2 return sqrt(k * (k - a) * (k - b) * (k - c)) def main3(): sides = input("Enter the three sides, seperated with commas please: ").split(",") sides = [int(k) for k in sides] print("The area of the circle is: ", triangleArea(sides[0], sides[1], sides[2]), "square units.") # FI's exercises # Converting Ghana cedis to pounds def cedisPound(c): return c / 6.54 # Converting Ghana cedis to dollars def cedisDollars(c): return c / 5.28 # Converting Ghana cedis to euros def cedisEuro(c): return c / 5.29 def main4(): amt = eval(input("Please enter the amount in Ghana cedis: ")) conv = open('convertions.txt', 'w') print(str(amt) + " GHC is: " + str(round(cedisDollars(amt), 3)) + " Dollars", file = conv) print(str(amt) + " GHC is: " + str(round(cedisEuro(amt), 3)) + " Euros", file = conv) print(str(amt) + " GHC is: " + str(round(cedisPound(amt), 3)) + " Pounds", file = conv) conv.close() <file_sep>/afrihack13.py def sort_array(source_array): odd = [] positions = [] for i in range(0, len(source_array)): if ( source_array[i] % 2 != 0): odd.append(source_array[i]) positions.append(i) odd.sort() for i in range(0,len(odd)): hold = positions[i] source_array[hold] = odd[i] return source_array <file_sep>/trailingZeros.py def zeros(n): x = n/5 if x: return int(x + zeros(x)) else: return 0 print(zeros(600)) <file_sep>/classAyawaa.py def standing(credits): if credits < 7: return "Freshman" elif credits < 16: return "Junior" elif credits < 26: return "Sophomore" return "Senior" def main(): cr = eval(input("Enter number of credits: ")) print(standing(cr)) # Babysitting expenses def costBSitting(start, stop): # start[0] is the starting hour, start[1] is the starting minute. Same thing for stop # I assume that stop times will always be ahead of start times if stop[0] <= 21: if stop[0] == 21: return 2.50*(stop[0]-start[0]) + (stop[1] * (1.75/60)) + (start[1] * (2.50/60)) # The last two additions handle the costs for the minutes else: return 2.50*(stop[0]-start[0]) + (stop[1] * (2.50/60)) + (start[1] * (2.50/60)) else: if start[0] >= 21: return 1.75*(stop[0]-start[0]) + (stop[1] * (1.75/60)) + (start[1] * (1.75/60)) else: return (2.50*(21 - start[0]) + (1.75 * (stop[0] - 21))) + (start[1] * (2.50/60)) + (stop[1] * (1.75/60)) def main2(): startTime = input("Enter the start time (e.g 22:47): ").split(':') startTime = [eval(x) for x in startTime] stopTime = input("Enter the stop time (e.g 23:30): ").split(':') stopTime = [eval(x) for x in stopTime] print("The cost is", round(costBSitting(startTime, stopTime), 2), '$.') main2() <file_sep>/printEven.py def printeven(ls): return [x for x in ls if (x%2 == 0)] # Using a list comprehension to get the even numbers def main(): user_input = input("Enter the numbers (Seperate with commas): ").split(",") # Getting the elements in a list user_input = [eval(x) for x in user_input] # changing the elements from strings to numbers print("The even numbers are: ", end = "") for i in printeven(user_input): print(i, end = " ") main() <file_sep>/changeCombinations.py def count_change(money, coins): import itertools ls = itertools.permutations(coins) ls = list(ls) print(ls) count_change(3,[1,3,5,2,3]) <file_sep>/pizzaPrize.py def pizzaArea(d): return (((22/7)*(d**2))/4) def pricePSI(d, p): return (p/pizzaArea(d)) def main(): d = eval(input("Enter the diameter of the pizza (Inches): ")) p = eval(input("Enter the price of the pizza (Ghana Cedis): ")) print("The area of your pizza is", pizzaArea(d), "square inches.") print("The price per square inch of a",d,"pizza", "is", pricePSI(d,p), "GHC") main()<file_sep>/kataday.py def choose_best_sum(t, k, ls): final = [] from itertools import combinations solve = combinations(ls,k) for i in solve: final.append(sum(i)) final.append(t) final.sort() final.reverse() i = final.index(t) if i == len(final)-1: return None else: return final[i+1] <file_sep>/mixedFractions.py def mixed_fraction(s): import math import fractions ls = [] num = s.split('/') num[0] = int(num[0]) num[1] = int(num[1]) if (num[0] > 0 and num[1] > 0) or (num[0] < 0 and num[1] < 0): ls.append(1) else: ls.append(0) num[0] = abs(num[0]) num[1] = abs(num[1]) if num[0] % num[1] == 0 and num[0] >= num[1]: ls.append(num[0] // num[1]) else: ls.append(num[0] // num[1]) ls.append(num[0] % num[1]) #simplifying the last remaining digits def printResults(vid): if len(vid) == 2: if vid[0]==1: return (str(vid[1])) else: return (str(-1*vid[1])) elif vid[1] == 0: if vid[0] == 1: re = str(fractions.Fraction(vid[2],num[1])) else: re = str(-fractions.Fraction(vid[2],num[1])) return re else: if vid[0] == 1: re = str(vid[1]) + " " + str(fractions.Fraction(vid[2],num[1])) print(re) return re else: re = str(-1*vid[1]) + " " + str(fractions.Fraction(vid[2],num[1])) print(re) return re return printResults(ls) print(mixed_fraction("-22/-7")) <file_sep>/afrihack10.py def points(games): points = 0 for x in games: if x[0] > x[2]: points = points + 3 elif x[0] == x[2]: points = points +1 return points<file_sep>/afrihack15.py def anagrams(word, words): ans = [] for y in words: if len(y) == len(word): hold1 = hold2 = 0 counter = 0 counter2 = 0 #checking if all the letters that appear in word are in y for x in word: if x in y: counter +=1 if counter == len(word): hold1 = 1 #checking if all the letters in y are in word for x in y: if x in word: counter2 +=1 if counter2 == len(word): hold2 = 1 if (hold1 == 1) and (hold2 == 1): ans.append(y) return ans <file_sep>/updatedCipher.py # Author: <NAME> ## email: <EMAIL> ##Purpose #### This is a substitution cypher that works in a circular manner. This cypher does not encode special characters and encodes capital #### letters only with capital letters and lower case letters with lower case letters only def cipher(c,key): # Arguments are the character to be encoded and the step by which the change is being done if (ord(c) == 32): # Makes sure that there is no attempt to encode spaces return c else: if ord(c) in range(65,91): k = ord(c) + key if k > 90: k = 65 + k%91 # Gets the new character that represents the character in a cyclic manner return chr(k) elif ord(c) in range(97,123): k = ord(c) + key if k > 122: k = 97 + k % 123 # Gets the new character return chr(k) else: return c def decode(i,key): if ord(i) == 32: return i elif ord(i) in range(65,key + 65): # If the character is in the cyclic range return chr(ord(i)+ (26 - key)) elif ord(i) in range(97,key + 97): return chr(ord(i) + (26 - key)) # Also checking if the character is in the cyclic range elif ord(i) in range(65,91) or ord(i) in range(97,123): return chr(ord(i) - key) else: return i def main(): shift = int(input("Please enter the digit by which you want the cipher to shift: ")) plain = input("Enter the string to be encoded: ") cipherText = "" for c in plain: cipherText = cipherText + cipher(c,shift) print(cipherText) etext = input("Enter the text to be decoded: ") plainText = "" for k in etext: plainText += decode(k,shift) print(plainText) main() <file_sep>/detdivisors.py def detdivisors(n): import math divisors = [] sum = 0 for i in range(1,n+1): if n%i == 0: divisors.append(i) for i in range(0, len(divisors)): sum = sum + (divisors[i]**2) if (math.sqrt(sum)%1 == 0): return sum else: return False def list_squared(m, n): answers = [] for i in range(m, n+1): ans = [] if detdivisors(i) != False: ans.append(i) ans.append(detdivisors(i)) answers.append(ans) return answers num = int(input("Enter the beginning: ")) end = int(input("Enter the end: ")) ans = list_squared(num,end) print(ans)<file_sep>/greenNumbers.py # Function to determine if a number is green # Determining if a given number is green def determineGreen(n): ls = list(str(n)) ls2 = list(str(n**2)) ans = ls2[len(ls2) - len(ls) : len(ls2)] if ans == ls: return True else: return False ## Determining the i-th green number def green(i): import time start = time.time() k = 0 num = 1 while k != i: if determineGreen(num): k = k+1 num2 = num if list(str(num))[-1] == '1': num += 4 elif list(str(num))[-1] == '5': num += 1 elif list(str(num))[-1] == '6': num += 5 end = time.time() print((end - start), "seconds were used") return num2 print(green(16)) <file_sep>/writeUpperCase.py def writeUpperCase(filename): inputfile = open(filename, 'r') output = open('upper.txt', 'w') k = inputfile.readlines() for i in k: print(i.upper(), file = output, end = '') inputfile.close() output.close() def main(): name = input("Enter the name of the file: ") try: writeUpperCase(name) print("Check your output in a file called upper.txt") except: print('Please make sure to check one of the following:\n\t1. The file name is correct\n\t2.The extension is valid for the python file operations, and you are actually typing it in\n\t3. Your script is stored in thesame location as your file\n\tTRY AGAIN PLEASE') main()<file_sep>/afrihack9.py def add_length(str_): string = str_.split(" ") wlen = [] ans = [] print(string[1][1:4]) for i in range(0,len(string)): l = len(string[i]) wlen.append(l) for i in range(0, len(string)): ans.append(string[i]+ " " + str(wlen[i])) return ans add_length("gajhkalk hkdjlakd bdhakdaj balka")<file_sep>/afrihack5.py def find_missing_letter(chars): holder = [] final = [] for i in range(1,len(chars)): if ord(chars[i]) == ord(chars[i-1])+1: holder.append(chars[i]) else: final.append(chr(ord(chars[i-1])+1)) return final[0]<file_sep>/lcddisplay.py def printer(a): if a == 1: return (" |\n |") elif a == 2: return ("__\n__|\n|__") elif a == 3: return ("__\n__|\n__|") elif a == 4: return ("|__|\n |") elif a == 5: return (" __\n|__\n___|") elif a == 6: return (" __\n|__\n|__|") elif a == 7: return ("__\n |\n |") elif a == 8: return (" __\n|__|\n|__|") elif a == 9: return (" __\n|__|\n __|") elif a == 0: return (" __\n| |\n|__|") else: print("Ensure that you are entering a digit") num = list(input("Please type in the number: ")) num = [int(k) for k in num] for k in num: print(printer(k) <file_sep>/calculator.py # Author: <NAME> #<EMAIL> ##A calcullator that works with the principle of bodmas """ Create a simple calculator that given a string of operators (+ - * and /) and numbers separated by spaces returns the value of that expression Example: Calculator().evaluate("2 / 2 + 3 * 4 - 6") # => 7 Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right. """ def evaluate(strin): cal = strin.split(" ") i = 0 for i in range(len(cal)): if i < len(cal) and cal[i] == '/': index1 = int(cal[i-1]) / int(cal[i+1]) del cal[i-1:i+2] cal.insert(i-1,index1) print(cal) elif i < len(cal) and cal[i] == '*': index1 = int(cal[i-1]) * int(cal[i+1]) del cal[i-1:i+2] cal.insert(i-1,index1) print(cal) for i in range(len(cal)): if i < len(cal) and cal[i] == '-': index1 = int(cal[i-1]) - int(cal[i+1]) del cal[i-1:i+2] cal.insert(i-1,index1) print(cal) elif i < len(cal) and cal[i] == '+': index1 = int(cal[i-1]) + int(cal[i+1]) del cal[i-1:i+2] cal.insert(i-1,index1) print(cal) #if cal[1] == '+': #ret = int(cal[0]) + int(cal[2]) #elif cal[1] == '-': #ret = int(cal[0]) - int(cal[2]) return cal print(evaluate("2 / 2 + 3 * 4 - 6 + 2")) <file_sep>/afrihack7.py def binary_array_to_number(arr): sum = 0; for i in range(0,len(arr)): sum = sum + arr[i]*(2**(len(arr)-i-1)) return sum;<file_sep>/staircase.py from graphics import * def main(): x = 0 y = 0 win = GraphWin("Stair Case", 400, 400) while (x < win.getWidth()): p = Rectangle(Point(x,y), Point(x + 20, y + 20)) p.draw(win) p.setFill("red") x = x + 20 y = y + 20 win.getMouse() win.close() main() <file_sep>/afrihack12.py def persistence(n): n =str(n) if len(n)==1: return 0 else: counter = 0 while len(n)> 1: counter += 1 multiple = 1 for x in n: multiple *= int(x) n = str(multiple) return counter <file_sep>/firstNonRepeating.py def first_non_repeating_letter(string): s = string if len(s) == 0: return '' else: k = s.upper() ls = [] for i in k: ls.append(k.count(i)) if 1 in ls: j = ls.index(1) print(ls) return s[j] else: return '' <file_sep>/afrihack8.py def iq_test(numbers): numbers = numbers.split(" ") even = [] odd = [] list = [] for i in range(0,len(numbers)): list.append(int(numbers[i])) for i in range(0,len(list)): if list[i] % 2 == 0: even.append(i+1) else: odd.append(i+1) if len(odd) == 1: return odd[0] else: return even[0] <file_sep>/johnZelle9.py def main(): sen = input("Enter your sentence: ") num = len(sen.split()) print("Your sentence has", num, "words")<file_sep>/middlePermutation.py def middle_permutation(string): import itertools ls = itertools.permutations(string) ls2 = [] for x in ls: x = "".join(x) ls2.append(x) ls2.sort() k = (len(ls2) -1)// 2 print(ls2[k]) middle_permutation("abcdxg") <file_sep>/upgradeRGB.py def rgbFunction(d): def changeToHex(n): if n < 10 and n >= 0: ls = "0" ls = ls + str(n) return ls elif n<=16 and n >= 0: ls = ["0A", "0B", "0C", "0D", "0E", "0F", "10"] intern = [10, 11, 12, 13, 14, 15, 16] if n in intern: x = intern.index(n) return ls[x] else: if n > 255: return "FF" elif n < 0: return "00" else: ls = "" while n != 0: x = n % 16 x = changeToHex(x) ls = ls + str(x[1]) n = n // 16 re = "" for i in range(0,len(ls)): re += ls[len(ls)-(1+i)] return re ans = "" for x in d: ans = ans + str(changeToHex(x)) return ans print(rgbFunction((-20,275,125))) <file_sep>/smallestNextInterger.py def next_smaller(n): import itertools import binarysearch num = str(n) if len(num) == 1: return -1 else: num = list(num) var = list(itertools.permutations(num)) print(len(var)) # Make the values in var intergers var2 = [] for i in var: ls = "" for k in range(0, len(i)): ls += i[k] i = str(ls) var2.append(int(i)) #insert the initial argument in the list, and then sort it # This will make it easier to return the closest element var2.sort() h = binarysearch.binarySearch(var2, 0, len(var2)-1, n) # Find the index at which n occurs and return the element before it # index = var2.index(str(n)) if h != 0: return int(var2[h-1]) else: return -1 print(next_smaller(1879)) <file_sep>/caesarCipher.py def cipher(ch): k = ord(ch) + 2 return chr(k) def decode(i): k = ord(i) - 2 return chr(k) def main(): plain = input("Enter the string to be encoded: ") cipherText = "" for c in plain: cipherText += cipher(c) print(cipherText) etext = input("Enter the text to be decoded: ") plainText = "" for k in etext: plainText += decode(k) print(plainText) main()<file_sep>/18PythonClass.py # Checking if a string is a palindrome def palindrome(word): if word == word[::-1]: # Take note that with slicing, if you change the step to -1, python automatically reverses the direction of iteration return ("Palindrome") else: return ("Not Palindrome") # Replacing the vowels in a word def replace(word): word = word.replace("a", "@") word = word.replace("e", "3") word = word.replace("i", "1") word = word.replace("o", "0") word = word.replace("u", "+") return word # Solving quadratic equations def quadSolve(a,b,c): from math import sqrt if a: if ((b**2) - 4*a*c) < 0: return (" Sorry, this equation has complex roots") return [(-b + sqrt((b**2) - 4*a*c)) /(2*a), (-b - sqrt((b**2) - 4*a*c)) /(2*a)] else: return -c / b # Factorial experiment def factorial(x): if x == 1 or x == 0: return 1 else: return x*factorial(x-1) print(factorial(10)) # Drawing the faces import graphics def drawFace(center, size, win): # def drawFace(center1, center2, size, win) C = graphics.Point(center[0], center[1]) # C = graphics.Point(center1, center2) gwin = graphics.GraphWin(win, 500, 500) face = graphics.Circle(C, size) face.draw(gwin) # Creating the left eye graphics.Circle(graphics.Point(C.getX() - 10, C.getY() - 10) , 5).draw(gwin) # Creating the right eye graphics.Circle(graphics.Point(C.getX() + 10, C.getY() - 10) , 5).draw(gwin) gwin.getMouse() gwin.close() # drawFace((200, 150), 60, "KarlWin") print(quadSolve(5,2,1)) <file_sep>/afrihack6.py def nb_year(p0, percent, aug, p): i = 0 while (p0 < p): i += 1; p0 = p0 + (p0 * (percent/100)) + aug; return i<file_sep>/teacherstaircase.py from graphics import * def main(): win = GraphWin() previous = Rectangle(Point(0,0), Point(20,20)) color = color_rgb(255, 0, 100) previous.setFill(color) previous.draw(win) for i in range(9): new = previous#.clone() new.move(20,20) new.draw(win) previous = new main() <file_sep>/fooling.py def super_size(n): n = str(n) list = [] for i in range(0, len(n)): list.append(int(n[i])) list.sort(reverse=True) value = "" for i in range(0,len(n)): value = value+str(list[i]) return int(value)<file_sep>/totalIntervalLength.py def sum_of_intervals(intervals): ls = [] for x in intervals: for i in range(x[0],x[1]): ls.append(i) print(ls) ls = set(ls) return len(ls) print(sum_of_intervals([[1,4], [7,10], [3,5]])) <file_sep>/mode.py ls = [1, 2, 4, 3, 5, 6, 7, 2, 4, 10,12] count = 1 md = [] for el in ls: if ls.count(el)>count: count = ls.count(el) y = el pos = ls.index(el) md.append(ls[pos]) for el in ls: if (ls.count(el) == count) and (el != ls[pos]): md.append(el) if count == 1: print("Sorry, all elements occur thesame number of times") else: if len(md)== 1: print("The element that occurs most is " + str(el) + ".\nIt occurs " + str(count) + " times") else: md = set(md) # This makes the list md a set, inorder to avoid repetition of elements print("The mode elements are:") for i in md: print(i) print("They occur " + str(count) + " times") <file_sep>/afrihack14.py def list_squared(m, n): import math answers = [] for i in range(m,n+1): divisors = [] sum = 0 for j in range(1,i+1): if m % j == 0: divisors.append(j) for i in range(0, len(divisors)): sum = sum + (divisors[i]*divisors[i]) num = math.sqrt(sum) if num % 1 == 0: answers.append(i) return answers ans = list_squared(1,250) print(ans) <file_sep>/currencyCalculator.py """Author: <NAME> Date: 28th November 2018 Use: Determining the number of each denominator that can be used to give a client his change after a purchase Description: This is an attempt to give all the possible combinations that can be used. The methodology is to give priority to a certain denomination and get a maximum of the denominator that can be used, and then proceeds to determine for the number of the other denominations. To optimize this attempt and ensure that all the possible combinations are gotten, a function can be written that will determine all the 9! possible ways of arranging the denominators and then running each through the process below. That should give us an enormous 9*9! different possibilities """ print( "Enter the amout of change you are expecting\nPlease enter the number of pesewas as an attached decimal. \nE.g " "130.6 for GHC130, 60 pesewas\n :") change = float(input()) denominations1 = [50, 20, 10, 5, 2, 1, 50, 20, 10] # storing the denominators in a way that will ease the printing of the results denominations2 = [1, 2, 5, 10, 20, 50, 100, 200, 500] # storing the denominators in a way that will ease the indexing during the iterative # calculations counter = len(denominations1) changeValues = [] # An empty string that will hold the numbers of every denomination that will be used. # Calculating the maximum number of each denominator that can be used, giving priority to a given position and then # working downwards This for for i in range(0, counter): k = counter - (i + 1) tempValues = [] # Initializing an empty list that will be used when the iteration starts at each point money = change * 10 while k >= 0: value = money // denominations2[k] money = money % denominations2[k] tempValues.append(value) k = k - 1 changeValues.append(tempValues) # At the end of this, the list changeValues is a list of lists. With each element representing the combination that # has given proirity to a given position and then worked downwards print(changeValues) print("\n") # storing the various elements of changeValues in independent strings to ease printing element1 = changeValues[0] element2 = changeValues[1] element3 = changeValues[2] element4 = changeValues[3] element5 = changeValues[4] element6 = changeValues[5] element7 = changeValues[6] element8 = changeValues[7] element9 = changeValues[8] # This function ensures that the number of elements in each table correspond with the number of denominators by # checking for and adding zeros before the table till it has as many elements as there are denominators def normalize(element): l = len(element) if l != 9: deficit = 9 - l for i in range(0, deficit): element.insert(0, 0.0) normalize(element1) normalize(element2) normalize(element3) normalize(element4) normalize(element5) normalize(element6) normalize(element7) normalize(element8) normalize(element9) global h h = 1 # writing a function that will print out the various kinds of denominators def functionprint(list): l = len(list) for i in range(0, l): if ((list[i] != 0) and ( i < 6)): # This enables us to print the result differently when we have cedi notes from when we have # pesewas print(str(list[i]) + " of the " + str(denominations1[i]) + " GHC note") if ((list[i] != 0) and (i > 5)): print(str(list[i]) + " of the " + str(denominations1[i]) + " pesewa coin") print("\n") # Printing the various combinations print("\nCOMBINATION 1") functionprint(element1) print("\nCOMBINATION 2") functionprint(element2) print("\nCOMBINATION 3") functionprint(element3) print("\nCOMBINATION 4") functionprint(element4) print("\nCOMBINATION 5") functionprint(element5) print("\nCOMBINATION 6") functionprint(element6) print("\nCOMBINATION 7") functionprint(element7) print("\nCOMBINATION 8") functionprint(element8) print("\nCOMBINATION 9") functionprint(element9)
5214006565c23f8d2af69981548721692c9e8a30
[ "Python" ]
39
Python
wybeturing/AfriHackWork
4117a2f0ee8e3fb41aa7f43e326fa1cad810aa6c
6fa00096c4bf439fb2f12fa30b7e1f14db508119
refs/heads/master
<repo_name>roxyproxy/workshop1<file_sep>/part5/main_test.go package main import ( "bytes" "reflect" "strings" "testing" ) func TestProceedMessage(t *testing.T) { want := `{"Addr":"192.168.1.8:58419","Body":"Test Body"}` r := strings.NewReader("Test Body") buf := bytes.Buffer{} err := proceedMessage(r, &buf, "192.168.1.8:58419") if err != nil { t.Errorf("error is not nil %+v", err) } got := strings.Trim(buf.String(), "\n") if !reflect.DeepEqual(got, want) { t.Errorf("got %+v, want %+v", got, want) } } <file_sep>/part2/client.go package main import ( "bufio" "encoding/json" "flag" "io" "log" "net" "os" ) var dialAddr = flag.String("dial", "localhost:8002", "host:port to dial") type Message struct { Body string } func main() { flag.Parse() conn, err := net.Dial("tcp", *dialAddr) if err != nil { log.Fatal(err) } scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { message := GetMessage(scanner.Text()) //err := SendMessage(message, os.Stdout) err := SendMessage(message, conn) if err != nil { log.Fatal(err) } } if err := scanner.Err(); err != nil { log.Fatal(err) } conn.Close() } func GetMessage(s string) Message { return Message{s} } func SendMessage(m Message, writer io.Writer) error { enc := json.NewEncoder(writer) return enc.Encode(m) } <file_sep>/part3/server.go package main import ( "encoding/json" "flag" "fmt" "io" "log" "net" "os" ) type Message struct { Body string } var listenAddr = flag.String("listen", "localhost:8002", "host:port to listen on") func main() { flag.Parse() l, err := net.Listen("tcp", *listenAddr) if err != nil { log.Fatal(err) } for { conn, err := l.Accept() if err != nil { log.Fatal(err) } go serve(conn, os.Stdout) } } func GetMessage(s string) Message { return Message{s} } func serve(conn io.ReadCloser, w io.Writer) { defer conn.Close() dec := json.NewDecoder(conn) for { message := GetMessage("") err := dec.Decode(&message) if err != nil { //log.Fatal(err) log.Println(err) return } fmt.Fprint(w, message.Body) } } <file_sep>/part2/client_test.go package main import ( "bytes" "os" "reflect" "strings" "testing" ) var MessageBody = "Awesome body!" func TestGetMessage(t *testing.T) { got := GetMessage(MessageBody) want := Message{MessageBody} assertMessage(t, got, want) } func TestSendMessage(t *testing.T) { want := `{"Body":"Awesome body!"}` buf := bytes.Buffer{} err := SendMessage(GetMessage(MessageBody), &buf) if err != nil { t.Errorf("error is not nil %+v", err) } got := strings.Trim(buf.String(), "\n") assertMessage(t, got, want) } func assertMessage(t *testing.T, got interface{}, want interface{}) { t.Helper() if !reflect.DeepEqual(got, want) { t.Errorf("got %+v, want %+v", got, want) } } func ExampleMessage() { message := GetMessage(MessageBody) SendMessage(message, os.Stdout) // Output: {"Body":"Awesome body!"} } <file_sep>/go.mod module workshop1 go 1.16 require github.com/campoy/whispering-gophers v0.0.0-20201009151325-e25c2709da60 // indirect <file_sep>/part3/server_test.go package main import ( "bytes" "encoding/json" "io" "io/ioutil" "os" "reflect" "testing" ) var MessageBody = "Awesome body!" type stubReadCloser struct { closed bool } func (s *stubReadCloser) Close() error { s.closed = true return nil } func (s stubReadCloser) Read(b []byte) (n int, err error) { return 0, io.EOF } func TestServe(t *testing.T) { t.Run("returns an error if got != want", func(t *testing.T) { want := "Awesome body!" m := GetMessage(MessageBody) b, _ := json.Marshal(&m) r := ioutil.NopCloser(bytes.NewBuffer(b)) buf := bytes.Buffer{} serve(r, &buf) got := buf.String() assertMessage(t, got, want) }) t.Run("returns an error id connection is not closed", func(t *testing.T) { want := true r := stubReadCloser{} serve(&r, os.Stdout) //.Println(r.Closed) got := r.closed assertMessage(t, got, want) }) } func assertMessage(t *testing.T, got interface{}, want interface{}) { t.Helper() if !reflect.DeepEqual(got, want) { t.Errorf("got %+v, want %+v", got, want) } } <file_sep>/part6/main_test.go package main import ( "encoding/json" "net" "reflect" "strings" "testing" "time" ) func TestReadInput(t *testing.T) { want := Message{Addr: "192.168.1.8:58419", Body: "Test Body"} m := make(chan Message, 1) done := make(chan interface{}) go func() { defer func() { close(done) }() r := strings.NewReader("Test Body") readInput(m, r, "192.168.1.8:58419") }() <-done select { case got := <-m: if !reflect.DeepEqual(got, want) { t.Errorf("got %+v, want %+v", got, want) } default: t.Errorf(`didn't receive message on channel`) } } func TestDial(t *testing.T) { m := make(chan Message, 1) want := Message{Addr: "192.168.1.8:58419", Body: "Test Body"} m <- want close(m) done := make(chan bool) addr := "localhost:8006" l, err := net.Listen("tcp", addr) if err != nil { t.Error(err) } go func() { defer func() { done <- true }() conn, err := l.Accept() defer conn.Close() if err != nil { t.Error(err) } d := json.NewDecoder(conn) for { var got Message err := d.Decode(&got) if err != nil { t.Error(err) return } if !reflect.DeepEqual(got, want) { t.Errorf("got %+v, want %+v", got, want) } return } }() go dial(addr, m) select { case <-done: case <-time.After(time.Second): t.Errorf("expired timeout") } }
249fef8b9facdd36c4aa994c5f96b7e3d92c7cdc
[ "Go Module", "Go" ]
7
Go
roxyproxy/workshop1
ab836679bf7caeaec246387b3c18cab1a42f5659
e3521274c7a4e7a60841cce9040be84fbcb15c04
refs/heads/master
<file_sep>/************************************************************************ ** Includes *************************************************************************/ #include <string.h> #include "cfe.h" #include "nav_app.h" #include "nav_msg.h" #include "nav_version.h" /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Instantiate the application object. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ NAV oNAV; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Default constructor. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ NAV::NAV() { } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Destructor constructor. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ NAV::~NAV() { } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Initialize event tables. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 NAV::InitEvent() { int32 iStatus=CFE_SUCCESS; /* Register the table with CFE */ iStatus = CFE_EVS_Register(0, 0, CFE_EVS_BINARY_FILTER); if (iStatus != CFE_SUCCESS) { (void) CFE_ES_WriteToSysLog("NAV - Failed to register with EVS (0x%08lX)\n", iStatus); } return iStatus; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Initialize Message Pipes */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 NAV::InitPipe() { int32 iStatus=CFE_SUCCESS; /* Init schedule pipe and subscribe to wakeup messages */ iStatus = CFE_SB_CreatePipe(&SchPipeId, NAV_SCH_PIPE_DEPTH, NAV_SCH_PIPE_NAME); if (iStatus == CFE_SUCCESS) { iStatus = CFE_SB_SubscribeEx(NAV_WAKEUP_MID, SchPipeId, CFE_SB_Default_Qos, NAV_WAKEUP_MID_MAX_MSG_COUNT); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "Sch Pipe failed to subscribe to NAV_WAKEUP_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(NAV_SEND_HK_MID, SchPipeId, CFE_SB_Default_Qos, NAV_SEND_HK_MID_MAX_MSG_COUNT); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to NAV_SEND_HK_MID. (0x%08X)", (unsigned int)iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_HOME_POSITION_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_HOME_POSITION_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_SENSOR_COMBINED_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_SENSOR_COMBINED_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_MISSION_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_MISSION_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_VEHICLE_GPS_POSITION_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_VEHICLE_GPS_POSITION_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_VEHICLE_GLOBAL_POSITION_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_VEHICLE_GLOBAL_POSITION_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_VEHICLE_STATUS_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_VEHICLE_STATUS_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_VEHICLE_LAND_DETECTED_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_VEHICLE_LAND_DETECTED_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } iStatus = CFE_SB_SubscribeEx(PX4_VEHICLE_LOCAL_POSITION_MID, SchPipeId, CFE_SB_Default_Qos, 1); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to PX4_VEHICLE_LOCAL_POSITION_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } } else { (void) CFE_EVS_SendEvent(NAV_PIPE_INIT_ERR_EID, CFE_EVS_ERROR, "Failed to create SCH pipe (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } /* Init command pipe and subscribe to command messages */ iStatus = CFE_SB_CreatePipe(&CmdPipeId, NAV_CMD_PIPE_DEPTH, NAV_CMD_PIPE_NAME); if (iStatus == CFE_SUCCESS) { /* Subscribe to command messages */ iStatus = CFE_SB_Subscribe(NAV_CMD_MID, CmdPipeId); if (iStatus != CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_SUBSCRIBE_ERR_EID, CFE_EVS_ERROR, "CMD Pipe failed to subscribe to NAV_CMD_MID. (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } } else { (void) CFE_EVS_SendEvent(NAV_PIPE_INIT_ERR_EID, CFE_EVS_ERROR, "Failed to create CMD pipe (0x%08lX)", iStatus); goto NAV_InitPipe_Exit_Tag; } NAV_InitPipe_Exit_Tag: return iStatus; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Initialize Global Variables */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void NAV::InitData() { /* Init housekeeping message. */ CFE_SB_InitMsg(&HkTlm, NAV_HK_TLM_MID, sizeof(HkTlm), TRUE); /* Init output messages */ CFE_SB_InitMsg(&VehicleLandDetectedMsg, PX4_VEHICLE_LAND_DETECTED_MID, sizeof(PX4_VehicleLandDetectedMsg_t), TRUE); /* Init output messages */ CFE_SB_InitMsg(&FenceMsg, PX4_FENCE_MID, sizeof(PX4_FenceMsg_t), TRUE); /* Init output messages */ CFE_SB_InitMsg(&ActuatorControls3Msg, PX4_ACTUATOR_CONTROLS_3_MID, sizeof(PX4_ActuatorControlsMsg_t), TRUE); /* Init output messages */ CFE_SB_InitMsg(&MissionResultMsg, PX4_MISSION_RESULT_MID, sizeof(PX4_MissionResultMsg_t), TRUE); /* Init output messages */ CFE_SB_InitMsg(&GeofenceResultMsg, PX4_GEOFENCE_RESULT_MID, sizeof(PX4_GeofenceResultMsg_t), TRUE); /* Init output messages */ CFE_SB_InitMsg(&PositionSetpointTripletMsg, PX4_POSITION_SETPOINT_TRIPLET_MID, sizeof(PX4_PositionSetpointTripletMsg_t), TRUE); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* NAV initialization */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 NAV::InitApp() { int32 iStatus = CFE_SUCCESS; int8 hasEvents = 0; iStatus = InitEvent(); if (iStatus != CFE_SUCCESS) { (void) CFE_ES_WriteToSysLog("NAV - Failed to init events (0x%08lX)\n", iStatus); goto NAV_InitApp_Exit_Tag; } else { hasEvents = 1; } iStatus = InitPipe(); if (iStatus != CFE_SUCCESS) { goto NAV_InitApp_Exit_Tag; } InitData(); iStatus = InitConfigTbl(); if (iStatus != CFE_SUCCESS) { goto NAV_InitApp_Exit_Tag; } NAV_InitApp_Exit_Tag: if (iStatus == CFE_SUCCESS) { (void) CFE_EVS_SendEvent(NAV_INIT_INF_EID, CFE_EVS_INFORMATION, "Initialized. Version %d.%d.%d.%d", NAV_MAJOR_VERSION, NAV_MINOR_VERSION, NAV_REVISION, NAV_MISSION_REV); } else { if (hasEvents == 1) { (void) CFE_ES_WriteToSysLog("NAV - Application failed to initialize\n"); } } return iStatus; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Receive and Process Messages */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 NAV::RcvSchPipeMsg(int32 iBlocking) { int32 iStatus=CFE_SUCCESS; CFE_SB_Msg_t* MsgPtr=NULL; CFE_SB_MsgId_t MsgId; /* Stop Performance Log entry */ CFE_ES_PerfLogExit(NAV_MAIN_TASK_PERF_ID); /* Wait for WakeUp messages from scheduler */ iStatus = CFE_SB_RcvMsg(&MsgPtr, SchPipeId, iBlocking); /* Start Performance Log entry */ CFE_ES_PerfLogEntry(NAV_MAIN_TASK_PERF_ID); if (iStatus == CFE_SUCCESS) { MsgId = CFE_SB_GetMsgId(MsgPtr); switch (MsgId) { case NAV_WAKEUP_MID: /* TODO: Do something here. */ break; case NAV_SEND_HK_MID: ProcessCmdPipe(); ReportHousekeeping(); break; case PX4_HOME_POSITION_MID: memcpy(&CVT.HomePositionMsg, MsgPtr, sizeof(CVT.HomePositionMsg)); break; case PX4_SENSOR_COMBINED_MID: memcpy(&CVT.SensorCombinedMsg, MsgPtr, sizeof(CVT.SensorCombinedMsg)); break; case PX4_MISSION_MID: memcpy(&CVT.MissionMsg, MsgPtr, sizeof(CVT.MissionMsg)); break; case PX4_VEHICLE_GPS_POSITION_MID: memcpy(&CVT.VehicleGpsPositionMsg, MsgPtr, sizeof(CVT.VehicleGpsPositionMsg)); break; case PX4_VEHICLE_GLOBAL_POSITION_MID: memcpy(&CVT.VehicleGlobalPosition, MsgPtr, sizeof(CVT.VehicleGlobalPosition)); break; case PX4_VEHICLE_STATUS_MID: memcpy(&CVT.VehicleStatusMsg, MsgPtr, sizeof(CVT.VehicleStatusMsg)); break; case PX4_VEHICLE_LAND_DETECTED_MID: memcpy(&CVT.VehicleLandDetectedMsg, MsgPtr, sizeof(CVT.VehicleLandDetectedMsg)); break; case PX4_VEHICLE_LOCAL_POSITION_MID: memcpy(&CVT.VehicleLocalPositionMsg, MsgPtr, sizeof(CVT.VehicleLocalPositionMsg)); break; default: (void) CFE_EVS_SendEvent(NAV_MSGID_ERR_EID, CFE_EVS_ERROR, "Recvd invalid SCH msgId (0x%04X)", MsgId); } } else if (iStatus == CFE_SB_NO_MESSAGE) { /* TODO: If there's no incoming message, you can do something here, or * nothing. Note, this section is dead code only if the iBlocking arg * is CFE_SB_PEND_FOREVER. */ iStatus = CFE_SUCCESS; } else if (iStatus == CFE_SB_TIME_OUT) { /* TODO: If there's no incoming message within a specified time (via the * iBlocking arg, you can do something here, or nothing. * Note, this section is dead code only if the iBlocking arg * is CFE_SB_PEND_FOREVER. */ iStatus = CFE_SUCCESS; } else { (void) CFE_EVS_SendEvent(NAV_RCVMSG_ERR_EID, CFE_EVS_ERROR, "SCH pipe read error (0x%08lX).", iStatus); } return iStatus; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Process Incoming Commands */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void NAV::ProcessCmdPipe() { int32 iStatus = CFE_SUCCESS; CFE_SB_Msg_t* CmdMsgPtr=NULL; CFE_SB_MsgId_t CmdMsgId; /* Process command messages until the pipe is empty */ while (1) { iStatus = CFE_SB_RcvMsg(&CmdMsgPtr, CmdPipeId, CFE_SB_POLL); if(iStatus == CFE_SUCCESS) { CmdMsgId = CFE_SB_GetMsgId(CmdMsgPtr); switch (CmdMsgId) { case NAV_CMD_MID: ProcessAppCmds(CmdMsgPtr); break; default: /* Bump the command error counter for an unknown command. * (This should only occur if it was subscribed to with this * pipe, but not handled in this switch-case.) */ HkTlm.usCmdErrCnt++; (void) CFE_EVS_SendEvent(NAV_MSGID_ERR_EID, CFE_EVS_ERROR, "Recvd invalid CMD msgId (0x%04X)", (unsigned short)CmdMsgId); break; } } else if (iStatus == CFE_SB_NO_MESSAGE) { break; } else { (void) CFE_EVS_SendEvent(NAV_RCVMSG_ERR_EID, CFE_EVS_ERROR, "CMD pipe read error (0x%08lX)", iStatus); break; } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Process NAV Commands */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void NAV::ProcessAppCmds(CFE_SB_Msg_t* MsgPtr) { uint32 uiCmdCode=0; if (MsgPtr != NULL) { uiCmdCode = CFE_SB_GetCmdCode(MsgPtr); switch (uiCmdCode) { case NAV_NOOP_CC: HkTlm.usCmdCnt++; (void) CFE_EVS_SendEvent(NAV_CMD_NOOP_EID, CFE_EVS_INFORMATION, "Recvd NOOP. Version %d.%d.%d.%d", NAV_MAJOR_VERSION, NAV_MINOR_VERSION, NAV_REVISION, NAV_MISSION_REV); break; case NAV_RESET_CC: HkTlm.usCmdCnt = 0; HkTlm.usCmdErrCnt = 0; break; default: HkTlm.usCmdErrCnt++; (void) CFE_EVS_SendEvent(NAV_CC_ERR_EID, CFE_EVS_ERROR, "Recvd invalid command code (%u)", (unsigned int)uiCmdCode); break; } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Send NAV Housekeeping */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void NAV::ReportHousekeeping() { CFE_SB_TimeStampMsg((CFE_SB_Msg_t*)&HkTlm); CFE_SB_SendMsg((CFE_SB_Msg_t*)&HkTlm); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Publish Output Data */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void NAV::SendVehicleLandDetectedMsg() { CFE_SB_TimeStampMsg((CFE_SB_Msg_t*)&VehicleLandDetectedMsg); CFE_SB_SendMsg((CFE_SB_Msg_t*)&VehicleLandDetectedMsg); } void NAV::SendFenceMsg() { CFE_SB_TimeStampMsg((CFE_SB_Msg_t*)&FenceMsg); CFE_SB_SendMsg((CFE_SB_Msg_t*)&FenceMsg); } void NAV::SendActuatorControls3Msg() { CFE_SB_TimeStampMsg((CFE_SB_Msg_t*)&ActuatorControls3Msg); CFE_SB_SendMsg((CFE_SB_Msg_t*)&ActuatorControls3Msg); } void NAV::SendMissionResultMsg() { CFE_SB_TimeStampMsg((CFE_SB_Msg_t*)&MissionResultMsg); CFE_SB_SendMsg((CFE_SB_Msg_t*)&MissionResultMsg); } void NAV::SendGeofenceResultMsg() { CFE_SB_TimeStampMsg((CFE_SB_Msg_t*)&GeofenceResultMsg); CFE_SB_SendMsg((CFE_SB_Msg_t*)&GeofenceResultMsg); } void NAV::SendPositionSetpointTripletMsg() { CFE_SB_TimeStampMsg((CFE_SB_Msg_t*)&PositionSetpointTripletMsg); CFE_SB_SendMsg((CFE_SB_Msg_t*)&PositionSetpointTripletMsg); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Verify Command Length */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ boolean NAV::VerifyCmdLength(CFE_SB_Msg_t* MsgPtr, uint16 usExpectedLen) { boolean bResult = TRUE; uint16 usMsgLen = 0; if (MsgPtr != NULL) { usMsgLen = CFE_SB_GetTotalMsgLength(MsgPtr); if (usExpectedLen != usMsgLen) { bResult = FALSE; CFE_SB_MsgId_t MsgId = CFE_SB_GetMsgId(MsgPtr); uint16 usCmdCode = CFE_SB_GetCmdCode(MsgPtr); (void) CFE_EVS_SendEvent(NAV_MSGLEN_ERR_EID, CFE_EVS_ERROR, "Rcvd invalid msgLen: msgId=0x%08X, cmdCode=%d, " "msgLen=%d, expectedLen=%d", MsgId, usCmdCode, usMsgLen, usExpectedLen); HkTlm.usCmdErrCnt++; } } return bResult; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* NAV Application C style main entry point. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ extern "C" void NAV_AppMain() { oNAV.AppMain(); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* NAV Application C++ style main entry point. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void NAV::AppMain() { /* Register the application with Executive Services */ uiRunStatus = CFE_ES_APP_RUN; int32 iStatus = CFE_ES_RegisterApp(); if (iStatus != CFE_SUCCESS) { (void) CFE_ES_WriteToSysLog("NAV - Failed to register the app (0x%08lX)\n", iStatus); } /* Start Performance Log entry */ CFE_ES_PerfLogEntry(NAV_MAIN_TASK_PERF_ID); /* Perform application initializations */ if (iStatus == CFE_SUCCESS) { iStatus = InitApp(); } if (iStatus == CFE_SUCCESS) { /* Do not perform performance monitoring on startup sync */ CFE_ES_PerfLogExit(NAV_MAIN_TASK_PERF_ID); CFE_ES_WaitForStartupSync(NAV_STARTUP_TIMEOUT_MSEC); CFE_ES_PerfLogEntry(NAV_MAIN_TASK_PERF_ID); } else { uiRunStatus = CFE_ES_APP_ERROR; } /* Application main loop */ while (CFE_ES_RunLoop(&uiRunStatus) == TRUE) { RcvSchPipeMsg(NAV_SCH_PIPE_PEND_TIME); iStatus = AcquireConfigPointers(); if(iStatus != CFE_SUCCESS) { /* We apparently tried to load a new table but failed. Terminate the application. */ uiRunStatus = CFE_ES_APP_ERROR; } } /* Stop Performance Log entry */ CFE_ES_PerfLogExit(NAV_MAIN_TASK_PERF_ID); /* Exit the application */ CFE_ES_ExitApp(uiRunStatus); } /************************/ /* End of File Comment */ /************************/ <file_sep>#ifndef NAV_MSGIDS_H #define NAV_MSGIDS_H #ifdef __cplusplus extern "C" { #endif #define NAV_HK_TLM_MID 0x0000 #define NAV_SEND_HK_MID 0x0000 #define NAV_WAKEUP_MID 0x0000 #define NAV_CMD_MID 0x0000 #ifdef __cplusplus } #endif #endif /* NAV_MSGIDS_H */ /************************/ /* End of File Comment */ /************************/
0b15a028a63816c47078ef6e27507f748a27ee7e
[ "C", "C++" ]
2
C++
WindhoverLabs/nav
be67cf06d71d155e424a34c988ff42c817be31f6
8fd7c625e4d28c52f05d8af9072d952bca5f9c49
refs/heads/master
<file_sep>package br.com.cursojsf.converters; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; import br.com.cursojsf.model.Cep; @FacesConverter("converters.CepConverter") public class CepConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { if (value != null && !value.equals("")) { try{ validate(value); String [] cepArguments = value.split("-"); Cep cep = new Cep(); cep.setRegiao(cepArguments[0]); cep.setSufixo(cepArguments[1]); return cep; }catch (Exception e){ FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro de conversão", "O CEP informado não é valido!"); throw new ConverterException(message); } } return value; } private void validate(String value) throws Exception { if (!value.contains("-")) { throw new Exception("CEP inválido!"); } } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { if (value == null) { return ""; } else { return ((Cep) value).toString(); } } }<file_sep>package br.com.cursojsf.validators; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; @FacesValidator("validators.CepValidator") public class CepValidator implements Validator{ private final static String CEP_REGEX = "\\d{5}-\\d{3}"; @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { if (value != null) { String valor = value.toString(); if (!valor.matches(CEP_REGEX)) { FacesMessage message = new FacesMessage(); message.setSeverity(FacesMessage.SEVERITY_ERROR); message.setSummary("Erro de Validação"); message.setDetail("CEP Inválido"); throw new ValidatorException(message); } } } }<file_sep>package br.com.cursojsf.managedbean; import static br.com.cursojsf.util.MessageHelper.addErrorMessage; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import br.com.cursojsf.business.EstadoBusiness; import br.com.cursojsf.business.PibInalidoException; import br.com.cursojsf.model.Estado; /** * Classe de visao para o caso de uso Cadastro de Estados. * @author <NAME> */ @ManagedBean @SessionScoped public class EstadoBean { /** * Regra de negocio da entidade Estado. */ @ManagedProperty("#{estadoBusiness}") private EstadoBusiness estadoBusiness; /** * Lista de estados selecionados para ser usado na tabela do cadastro. */ private List<Estado> estados; /** * Estado selecionado para edicao. */ private Estado estado; public void setEstadoBusiness(EstadoBusiness estadoBusiness) { this.estadoBusiness = estadoBusiness; } public List<Estado> getEstados() { return estados; } public void setEstados(List<Estado> estados) { this.estados = estados; } public Estado getEstado() { return estado; } public void setEstado(Estado estado) { this.estado = estado; } public String consultar() { estados = estadoBusiness.selecionarTodos(); return "estados"; } public String novo() { estado = new Estado(); return "estadosEditar"; } public String salvar() { try { estadoBusiness.salvarEstado(estado); } catch (PibInalidoException e) { addErrorMessage("estadoForm", "bean.estadoBean.pibInalidoException"); return null; } return consultar(); } public String excluir() { estado = estadoBusiness.selecionar(estado); estadoBusiness.excluirEstado(estado); return consultar(); } public String editar() { estado = estadoBusiness.selecionar(estado); return "estadosEditar"; } } <file_sep>package br.com.cursojsf.listeners; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletRequest; public class ContadorPageViewsListener implements ServletRequestListener { private static final String CONTADOR = "contador"; @Override public void requestInitialized(ServletRequestEvent event) { ServletRequest servletRequest = event.getServletRequest(); HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; String url = httpRequest.getRequestURL().toString(); if (url.endsWith(".xhtml")) { ServletContext context = httpRequest.getServletContext(); // Utilizando ConcurrentHashMap para garantir o controle de // concorrencia em caso de muitos acessos a aplicacao ConcurrentHashMap<String, Integer> contador = getContador(context); // Somente inicializa se nao existir Integer quantidade = 0; contador.putIfAbsent(url, quantidade); do { // Obtem a quantidade de acessos quantidade = contador.get(url); // Altera o valor se este ainda nao foi alterado } while (!contador.replace(url, quantidade, ++quantidade)); } } @Override public void requestDestroyed(ServletRequestEvent event) { } @SuppressWarnings("unchecked") private ConcurrentHashMap<String, Integer> getContador(ServletContext context) { ConcurrentHashMap<String, Integer> contador = (ConcurrentHashMap<String, Integer>) context.getAttribute(CONTADOR); if (contador == null) { contador = new ConcurrentHashMap<String, Integer>(); context.setAttribute(CONTADOR, contador); } return contador; } } <file_sep>package br.com.cursojsf.dao.impl; import java.util.List; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import br.com.cursojsf.dao.EstadoDao; import br.com.cursojsf.model.Estado; /** * DAO da entidade Estado. * @author <NAME> */ @ApplicationScoped @ManagedBean(name = "estadoDao") public class EstadoDaoImpl extends SimpleDaoGenerico<Estado> implements EstadoDao { public EstadoDaoImpl() { for (int i = 1; i <= 10; i++) { Estado estado = new Estado(); estado.setNome("Nome do estado " + i); estado.setSigla("EST" + i); salvarEntidade(estado); } } /** {@inheritDoc} */ public void salvarEstado(Estado estado) { super.salvarEntidade(estado); } /** {@inheritDoc} */ public void excluirEstado(Estado estado) { super.excluirEntidade(estado); } /** {@inheritDoc} */ @Override public Estado selecionar(Estado estado) { return super.selecionar(estado); } /** {@inheritDoc} */ @Override public List<Estado> selecionarTodos() { return super.selecionarTodos(); } } <file_sep>package br.com.cursojsf.managedbean; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import br.com.cursojsf.model.Cidade; /** * Classe de visao para o caso de uso Cadastro de Estados durante a edicao de * cidades. * * @author <NAME> */ @ManagedBean @SessionScoped public class CidadeBean { /** * Referenciapara o bean de Estado. Necessario por usar metodos do mesmo. */ @ManagedProperty("#{estadoBean}") private EstadoBean estadoBean; /** * Cidade a ser editada. */ private Cidade cidade; public void setEstadoBean(EstadoBean estadoBean) { this.estadoBean = estadoBean; } public Cidade getCidade() { return cidade; } public void setCidade(Cidade cidade) { this.cidade = cidade; } public String novo() { cidade = new Cidade(); return "cidadesEditar"; } public String salvar() { if (estadoBean.getEstado().getCidades() == null) { estadoBean.getEstado().setCidades(new ArrayList<Cidade>()); } List<Cidade> cidades = estadoBean.getEstado().getCidades(); cidade.setEstado(estadoBean.getEstado()); if (cidades.contains(cidade)) { int pos = cidades.indexOf(cidade); cidades.set(pos, cidade); } else { cidades.add(cidade); } return "estadosEditar"; } public String excluir() { estadoBean.getEstado().getCidades().remove(cidade); return "estadosEditar"; } }
fc40b92c85b807fd43daff61907a451dd804be10
[ "Java" ]
6
Java
Ribeiro/CursoJSF
52b413fe0a9ed157ddab4a2c327d3305f310fc9d
4f6c55b7181a2c605379ea274f527074ac14b3be
refs/heads/main
<repo_name>ayinla7/TRUTHORDARE<file_sep>/app/src/main/java/com/example/ayinlakwamdeen/truthordare/students.java package com.example.ayinlakwamdeen.truthordare; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.animation.RotateAnimation; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import java.util.Random; import static com.example.ayinlakwamdeen.truthordare.R.id.answer1; import static com.example.ayinlakwamdeen.truthordare.R.id.students; import static com.example.ayinlakwamdeen.truthordare.R.id.type1; public class students extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_students); Button btn; ActionBar a = getSupportActionBar(); a.setDisplayHomeAsUpEnabled(true); a.setTitle("Student"); final ImageView coin; Random r; int side; Button darebtn,truthbtn;; final TextView display; //darebtn=(Button)findViewById(R.id.darebtn); //truthbtn=(Button)findViewById(R.id.truthbtn); display=(TextView) findViewById(R.id.display); coin=(ImageView) findViewById(R.id.coin); coin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Random r = new Random(); int side = r.nextInt(6); if (side == 1) { coin.setImageResource(R.drawable.dice1); Toast.makeText(students.this, "DARE", Toast.LENGTH_SHORT).show(); } else if (side == 2) { coin.setImageResource(R.drawable.dice2); Toast.makeText(students.this, "TRUTH", Toast.LENGTH_SHORT).show(); } if (side == 3) { coin.setImageResource(R.drawable.dice3); Toast.makeText(students.this, "DARE", Toast.LENGTH_SHORT).show(); } else if (side == 4) { coin.setImageResource(R.drawable.dice4); Toast.makeText(students.this, "TRUTH", Toast.LENGTH_SHORT).show(); } if (side == 5) { coin.setImageResource(R.drawable.dice5); Toast.makeText(students.this, "DARE", Toast.LENGTH_SHORT).show(); } else if (side == 6) { coin.setImageResource(R.drawable.dice6); Toast.makeText(students.this, "TRUTH", Toast.LENGTH_SHORT).show(); } ////////////////////TO ROTATE THE COIN RotateAnimation rotate = new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); rotate.setDuration(1000); coin.startAnimation(rotate); if ((side==2)||(side==4)||(side==6)){ String truth[]= { "How people have you slept with on campus?" ,"What is your real GPA?" ,"What is your least favourite frat on campus?" ,"What did you do on your first night of freshman year?" ,"Would you ever have sex with one of your professors? If so, which one?" ,"Have you ever blacked out from drinking too much?" ,"What is the craziest thing that you have ever done while drunk?" ,"Who is the best roommate that you have ever had?" ,"What is the most annoying thing that your roommate has ever done?" ,"Have you ever had sex anywhere on campus?" ," Who was your first crush at school?" ,"Who is the most handsome guy/beautiful girl at school?" ,"What’s your idea of a perfect date?" ,"Where would you like to go on a first date?" ,"Do you have a boyfriend?" ,"How many boyfriends have you had?" ,"Have you been kissed yet?" ,"When did you have your first kiss, and with who?" ,"Did you ever break your boyfriend’s/girlfriend’s heart?" ,"Was your heart ever broken by your boyfriend/girlfriend?" ,"If you could go out on a date with a celebrity, who would it be?" ,"If you are stranded on a remote island, who would you choose for company?" ,"If you had to go out on a date with one of us in the room, who would it be?" ,"Of all the people you have dated, who has the most beautiful eyes?" ,"Tell us about your most embarrassing date?" ,"What was your most awkward moment on a date?" ,"Who do you think is the most beautiful/handsome teacher at school?" ,"Did you ever have a crush on any of your best friend’s boyfriends/girlfriends?" ,"Have you ever flirted with your best friend’s siblings?" ,"Would you use a dating website?" ,"If you had to pick one of us to go on a prom date, who would it be?" ,"Are you obsessed with a celebrity?" ,"Would you break up with someone by sending them a text?" ,"Are you jealous of someone because of who they date?" ,"How would you want the love of your life to propose to you?" ,"What kind of a person would you want to be married to in the future?" ,"Have you ever fallen in love with someone at first sight?" ,"Who is your best friend (when the person has two good friends) – name only one?" ,"Did you ever lie to your best friend/bud?" ,"Did you make them do something for you by lying?" ,"What were your first impressions about “best friend’s name”?" ,"Would you lie or cheat for a friend?" ,"What would you do if you had a crush on your bestie’s boyfriend/girlfriend?" ,"Would you go behind your bestie’s back with a crush?" ,"Would you ditch a lunch date with your bestie to go on a date?" ,"Name one quality that you do not like in your friend." ,"What do you like most about your best friend?" ,"What are the three most important qualities you look for in a friend?" ,"Who was the worst friend you have had and why?" ,"What is the cruelest thing you have done to a friend?" ,"Have you ever shared your best friend’s secrets with anyone else?" ,"Can you go for weeks or even months without talking to your bestie?" ,"Did you have an imaginary friend? What was his or her name?" ,"Did you ever cheat in a test?" ,"Did you actually enjoy reading a romantic poem in literature class but pretended that it was lame?" ,"What’s your career ambition?" ,"How confident are you about achieving your dreams?" ,"Which subject do you hate the most?" ,"Which is the most boring class you had to attend?" ,"Did you ever skip school by telling a lie and lie about it to your parents?" ,"Did you ever mock a teacher or classmate behind their back?" ,"What is the first thing you do after school every day?" ,"What is your favorite thing to do at school?" ,"Do you like gym class?" ,"Are you into sports?" ,"Who is your favorite teacher and why?" ,"Have you ever played a prank on a teacher?" ,"How many times have you been punished and sent to the principal’s office?" ,"Who is the creepiest kid you know in school?" ,"What is the lowest/worst grade you got in school?" ,"Have you ever fallen asleep in class?" ,"Did you pretend to be sick so you can skip class or avoid a test?" ,"Who was the first boy that you kissed in school?" ,"Have you ever had sex in your roommate’s bed?" ,"Did you smoke or drink before college? Or did you start when you got here?" ,"Have you ever been a stripper?" ,"Have you ever slept with your roommate’s bf/gf?" ,"Have you ever had sex in your parent’s bed?" ,"Would you drop out of school if you were to win the lottery?" ,"What is the best party that you’ve ever been to?" ,"How many parties have you thrown at your house?" ,"Have you ever had a threesome?" ,"Have you ever wanted to have an orgy?" ,"Have you used a toy while have sex?" ,"What is the longest you’ve had sex in one session?" ,"What is most amount of shots that you have taken in one night?" ,"Have you ever thrown up in someone’s car?" ,"Have you ever wet bed from being too drunk?" ,"What is the longest you have gone without sleep?" ,"What is the longest you’ve gone without sex?" ,"How many times have you skipped class for no reason?" ,"Have you ever gotten an STD?" ,"Have you ever woken up to a stranger in your bed?" ,"What is the earliest you have ever started drinking in the day?" ,"Have you ever spent your parent’s money on alcohol?" ,"How many freshmen have you slept with?" ,"Have you ever taken money from a freshman?" ,"Have you ever lied to your parents about if you were in classes or not?" ,"Have you ever taken money from your roommate?" ,"What is the most annoying thing your roommate does?" ,"Have you been in any fights while in school?" ,"Have you ever had someone write a paper for you?" ,"Have you ever done a sex train?"}; Random rand = new Random(); int random = rand.nextInt((truth).length); String guess1 = (truth[random]).toString(); display.setText(guess1); } else{ String dare[] = { "Take a shot" ,"Take a shot off of the person to your right" ,"Run down the street in only your underwear" ,"Slap the person to your left on the booty" ,"Speak like <NAME> for the next 10 minutes" ,"Give the person to your right a hickie" ,"Eat toilet paper" ,"Snort a line of sugar" ,"Eat some soap" ,"Twerk on a handstand" ,"Let someone give you haircut with their weak hand" ,"Make a freestyle rap song about each person in the group" ,"Lick someone’s foot" ,"Give a topless lap dance" ,"Call someone random, and talk freaky to them" ,"Twerk while in a split" ,"Spin the bottle, whoever it lands on you must take their shirt off, only using your teeth" ,"Send a nude to one of your exes" ,"Email one of your professor’s and tell them you love them" ,"Lick the wall" ,"Blindfolded, spin around for 10 seconds, kiss the person in front you at the end of your spinning" ,"Close your eyes, go to the refrigerator and eat whatever you grab" ,"Give some head with their underwear still on" ,"Take two shots of a dark and a light liquor ( 4 shots total )" ,"Blindfolded, let someone tie you to a chair and give you a lapdance" ,"Go outside completely naked and walk slowly up to the mailbox and back" ,"Let someone lick a full circle around your face" ,"Stand in the corner in “time out”, not say a word for the next 3 rounds" ,"Make out with someone’s boyfriend or girlfriend" ,"Raise your shirt play with your nipples" ,"Chug a whole beer in 15 seconds" ,"it in the trash can for the next round" ,"Chug an entire beer, then spin around for 15 seconds, after that try to run to the door" ,"Wearing only high heels do a strip dance for the group" ,"Take 2 shots and do a cartwheel" ,"Call your parents and tell them you’re dropping out" }; Random rand = new Random(); int random = rand.nextInt((dare).length); String guess = (dare[random]).toString(); display.setText(guess); } } }); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id=item.getItemId(); if(id==android.R.id.home){ this.finish(); } return super.onOptionsItemSelected(item); }} <file_sep>/app/src/main/java/com/example/ayinlakwamdeen/truthordare/HOME1.java package com.example.ayinlakwamdeen.truthordare; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class HOME1 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home1); Button reset,credit, playgame, quit; // getActionBar().hide(); playgame = (Button) findViewById(R.id.playgame); reset = (Button) findViewById(R.id.rules); credit = (Button) findViewById(R.id.about); playgame.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent int1 = new Intent(getApplicationContext(), Home2.class); startActivity(int1); } }); credit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent int1 = new Intent(getApplicationContext(), MainActivity1.class); startActivity(int1); } }); quit = (Button) findViewById(R.id.quit); quit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(HOME1.this); builder.setTitle("QUIT"); builder.setMessage("Are you sure you want to exit?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { moveTaskToBack(true); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int id) { dialogInterface.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }); } } <file_sep>/app/src/main/java/com/example/ayinlakwamdeen/truthordare/SplashScreen.java package com.example.ayinlakwamdeen.truthordare; import android.app.Activity; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.content.Intent; public class SplashScreen extends Activity { private static int SPLASH_TIME= 6000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); getActionBar().hide(); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i= new Intent(SplashScreen.this,HOME1.class); startActivity(i); finish(); } },SPLASH_TIME); } } <file_sep>/README.md # TRUTHORDARE
b5e1b12ccd1e65b079921b1af44364893b819bc8
[ "Markdown", "Java" ]
4
Java
ayinla7/TRUTHORDARE
5803e6cd1619391fdaf7969e58551f53171bf503
528c6cdcb672584bed6b0712f31dc5b60638cbb2
refs/heads/master
<repo_name>kuangdan-png/git<file_sep>/bookshopping/src/com/book/shopping/service/BookInfoManagerServiceImpl.java package com.book.shopping.service; import java.util.List; import com.book.shopping.dao.BookInfoManagerDaoImpl; import com.book.shopping.dao.BookInfoManagerDaoInter; import com.book.shopping.entity.BookInfo; public class BookInfoManagerServiceImpl implements BookInfoManagerServiceInter { private BookInfoManagerDaoInter bookInfoManagerDaoImpl = new BookInfoManagerDaoImpl(); /* * (non-Javadoc) * @see com.book.shopping.service.BookInfoManagerServiceInter#searchBookListInfoByBookTypeNo(java.lang.String) */ @Override public List<BookInfo> searchBookListInfoByBookTypeNo(String bookTypeNo, int currentPageNumber, int pageSize) { String sql = "select * from bookinfo where bookTypeNo = ? limit ? , ? "; Object[] arrays = {bookTypeNo,((currentPageNumber-1)*pageSize),pageSize}; return bookInfoManagerDaoImpl.searchBookListInfoByBookTypeNo(sql,arrays); } /* * (non-Javadoc) * @see com.book.shopping.service.BookInfoManagerServiceInter#calcTotalPages(java.lang.String, int) */ @Override public int calcTotalPages(String bookTypeNo, int pageSize) { String sql = "select count(booktypeno) counumber from bookinfo where booktypeno = ? "; Object[] arrays = {bookTypeNo,pageSize}; return bookInfoManagerDaoImpl.calcTotalPages(sql,arrays); } /* * (non-Javadoc) * @see com.book.shopping.service.BookInfoManagerServiceInter#searchBookDescriptionByBookInNo(java.lang.String) */ @Override public BookInfo searchBookDescriptionByBookInNo(String bookInfoNo) { String sql = "select * from bookinfo where bookNo = ?"; Object[] arrays = {bookInfoNo}; return bookInfoManagerDaoImpl.searchBookInfoDesc(sql, arrays); } } <file_sep>/bookshopping/src/com/book/shopping/service/BookInfoManagerServiceInter.java package com.book.shopping.service; import java.util.List; import com.book.shopping.entity.BookInfo; public interface BookInfoManagerServiceInter { /** * 1、根据传递的图书类型编号查询返回图书列表信息 * @param bookTypeNo * @param pageSize * @param currentPageNumber * @return */ List<BookInfo> searchBookListInfoByBookTypeNo(String bookTypeNo, int currentPageNumber, int pageSize); /** * 2、根据图书类型编号与每页显示条数计算出总页数 * @param bookTypeNo * @param pageSize * @return */ int calcTotalPages(String bookTypeNo , int pageSize); /** * 3、根据图书信息编号查询返回图书详情 * @param bookInfoNo * @return */ BookInfo searchBookDescriptionByBookInNo(String bookInfoNo); } <file_sep>/bookshopping/src/com/book/shopping/servlet/BookTypeManagerServlet.java package com.book.shopping.servlet; import javax.servlet.http.HttpServlet; /** * 图书类型管理servlet * @author Administrator * */ public class BookTypeManagerServlet extends HttpServlet { private static final long serialVersionUID = 3062237676508554601L; } <file_sep>/bookshopping/build/classes/bookshopping.properties bookshopping.driverclass=com.mysql.jdbc.Driver bookshopping.url=jdbc:mysql://localhost:3306/bookshopping bookshopping.dbusername=root bookshopping.dbuserpass=<PASSWORD> bookshopping.maxActive=80 bookshopping.maxIdle=10 bookshopping.minIdle=5 bookshopping.maxWait=100<file_sep>/bookshopping/src/com/book/shopping/dao/BookInfoManagerDaoInter.java package com.book.shopping.dao; import java.util.List; import com.book.shopping.entity.BookInfo; public interface BookInfoManagerDaoInter { /** * 根据传递的SQL语句及图书类型编号查询返回图书信息列表 * @param sql * @param arrays * @return */ List<BookInfo> searchBookListInfoByBookTypeNo(String sql, Object[] arrays); /** * 2、根据图书类型计算总页数 * @param sql * @param arrays * @return */ int calcTotalPages(String sql, Object[] arrays); /** * 3、查询图书详情 * @param sql * @param arrays * @return */ BookInfo searchBookInfoDesc(String sql, Object[] arrays); } <file_sep>/bookshopping/src/com/book/shopping/entity/BookInfo.java package com.book.shopping.entity; import java.io.Serializable; import java.util.Date; public class BookInfo implements Serializable{ private static final long serialVersionUID = 2728232728916527422L; /**图书编号*/ private String bookNo; /**图书名称*/ private String bookName; /**出版社名称*/ private String bookPublisher; /**图书原价*/ private double bookPrice; /**图书图片URL*/ private String bookImage; /**出版日期*/ private Date bookPubDate; /**图书作者*/ private String bookAuthor; /**图书内容简介*/ private String bookContent; /**图书描述摘要*/ private String bookDesciption; /**图书所属分类*/ private String bookTypeNo; private int bookNumber; public int getBookNumber() { return bookNumber; } public void setBookNumber(int bookNumber) { this.bookNumber = bookNumber; } public String getBookNo() { return bookNo; } public void setBookNo(String bookNo) { this.bookNo = bookNo; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getBookPublisher() { return bookPublisher; } public void setBookPublisher(String bookPublisher) { this.bookPublisher = bookPublisher; } public double getBookPrice() { return bookPrice; } public void setBookPrice(double bookPrice) { this.bookPrice = bookPrice; } public String getBookImage() { return bookImage; } public void setBookImage(String bookImage) { this.bookImage = bookImage; } public Date getBookPubDate() { return bookPubDate; } public void setBookPubDate(Date bookPubDate) { this.bookPubDate = bookPubDate; } public String getBookAuthor() { return bookAuthor; } public void setBookAuthor(String bookAuthor) { this.bookAuthor = bookAuthor; } public String getBookContent() { return bookContent; } public void setBookContent(String bookContent) { this.bookContent = bookContent; } public String getBookDesciption() { return bookDesciption; } public void setBookDesciption(String bookDesciption) { this.bookDesciption = bookDesciption; } public String getBookTypeNo() { return bookTypeNo; } public void setBookTypeNo(String bookTypeNo) { this.bookTypeNo = bookTypeNo; } public BookInfo(String bookNo, String bookName, String bookPublisher, double bookPrice, String bookImage, Date bookPubDate, String bookAuthor, String bookContent, String bookDesciption, String bookTypeNo) { super(); this.bookNo = bookNo; this.bookName = bookName; this.bookPublisher = bookPublisher; this.bookPrice = bookPrice; this.bookImage = bookImage; this.bookPubDate = bookPubDate; this.bookAuthor = bookAuthor; this.bookContent = bookContent; this.bookDesciption = bookDesciption; this.bookTypeNo = bookTypeNo; } public BookInfo() { super(); } @Override public String toString() { return "BookInfo [bookNo=" + bookNo + ", bookName=" + bookName + ", bookPublisher=" + bookPublisher + ", bookPrice=" + bookPrice + ", bookImage=" + bookImage + ", bookPubDate=" + bookPubDate + ", bookAuthor=" + bookAuthor + ", bookContent=" + bookContent + ", bookDesciption=" + bookDesciption + ", bookTypeNo=" + bookTypeNo + ", bookNumber=" + bookNumber + "]"; } } <file_sep>/bookshopping/src/com/book/shopping/dao/BookTypeManagerDaoImpl.java package com.book.shopping.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.book.shopping.entity.BookTypeInfo; public class BookTypeManagerDaoImpl implements BookTypeManagerDaoInter{ @Override public List<BookTypeInfo> searchBookTypeList(String sql) { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; List<BookTypeInfo> bookTypeList = new ArrayList<>(); try { connection = BaseDao.createConnection(); statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(); while(resultSet.next()){//while(true) , while(false) String bookTypeNo= resultSet.getString("bookTypeNo"); String bookTypeName= resultSet.getString("bookTypeName"); String bookTypeLinkUrl= resultSet.getString("bookTypeLinkUrl"); String bookTypeImgUrl= resultSet.getString("bookTypeImgUrl"); String bookTypeParentNo= resultSet.getString("bookTypeParentNo"); int bookTypeOrderNo= resultSet.getInt("bookTypeOrderNo"); String bookTypeDescipt= resultSet.getString("bookTypeDescipt"); BookTypeInfo bookTypeInfo = new BookTypeInfo(bookTypeNo, bookTypeName, bookTypeLinkUrl, bookTypeImgUrl, bookTypeParentNo, bookTypeOrderNo, bookTypeDescipt); bookTypeList.add(bookTypeInfo); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); }finally{ BaseDao.freeSource(connection, statement, resultSet); } return bookTypeList; } public static void main(String[] args) { String sql = "select bookTypeNo,bookTypeName,bookTypeParentNo,bookTypeLinkUrl,bookTypeImgUrl,bookTypeOrderNo,bookTypeDescipt from booktypeinfo"; System.out.println(new BookTypeManagerDaoImpl().searchBookTypeList(sql).size()); } } <file_sep>/bookshopping/src/com/java/web/chapter08/servlet/ManagerBookTypeServlet.java package com.java.web.chapter08.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.book.shopping.entity.BookTypeInfo; public class ManagerBookTypeServlet extends HttpServlet{ private static final long serialVersionUID = 6763156711737604389L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(" doGet method "); //1)null(没有指向的具体对象) //2)size=0 (空数据) List<BookTypeInfo> typeInfos = new ArrayList<BookTypeInfo>(); /*for(int i = 10 ; i <= 20; i++){ BookTypeInfo obj = new BookTypeInfo("T00" + (i+10), "计算机" + i, "bookManagerServlet", "computer" +i+".jpg", "T0001", i, "...."); typeInfos.add(obj); } */ req.getSession().setAttribute("BOOK_TYPE_LIST", typeInfos); //resp.sendRedirect("chapter08/jstlcore.jsp"); resp.sendRedirect("chapter08/codtion.jsp"); } } <file_sep>/bookshopping/src/com/book/shopping/servlet/ShoppingcarServlet.java package com.book.shopping.servlet; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.book.shopping.entity.BookInfo; import com.book.shopping.service.BookInfoManagerServiceImpl; public class ShoppingcarServlet extends HttpServlet { private static final long serialVersionUID = 7201270845502418928L; private BookInfoManagerServiceImpl bookInfoManagerServiceImpl = new BookInfoManagerServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1、获取超链接携带的图书信息的编号 String bookInfoNo = req.getParameter("bookInfoNo"); System.out.println("bookInfoNo=" + bookInfoNo); //2、调用原有的业务逻辑类中根据图书编号查询图书信息对象的方法 BookInfo bookInfoObj = bookInfoManagerServiceImpl.searchBookDescriptionByBookInNo(bookInfoNo); //3、将当前点击购买的图书对象放在购物车中 //3_1)第一次进行先从session中取Map判断是否为空 HttpSession session = req.getSession(); System.out.println("session id = " + session.getId()); Map<String, BookInfo> shoppMap = (Map<String,BookInfo>)session.getAttribute("SHOPPING_CAR"); if(null != shoppMap && !shoppMap.isEmpty()){ //1、最简洁方式 /*Set<Entry<String, BookInfo>> entrySet = shoppMap.entrySet(); for (Entry<String, BookInfo> entry : entrySet) { System.out.println(entry.getKey() +"\t" + entry.getValue()); }*/ //2、普通方式 /*Set<String> keySet = shoppMap.keySet(); for (String string : keySet) { System.out.print("key=" + string + " --> value=" + shoppMap.get(string)); }*/ } //如果满足if则不是表示第一次,而是后续次数 if(null != shoppMap && !shoppMap.isEmpty()){ //xxx.containsKey()=true 表示原来有这本书 if(shoppMap.containsKey(bookInfoObj.getBookNo())){ //表示原来存在有key,则根据key快速找到原来那本书的对象 bookInfoObj = shoppMap.get(bookInfoObj.getBookNo()); //对当前这本书将原来的购买数量获取到在此基础上加1操作 bookInfoObj.setBookNumber((bookInfoObj.getBookNumber() + 1)); }else{//xxx.containsKey() = false 表示原来这本书未存在 bookInfoObj.setBookNumber(1); shoppMap.put(bookInfoObj.getBookNo(),bookInfoObj); } }else{//表示第一次 shoppMap = new HashMap<String,BookInfo>(); bookInfoObj.setBookNumber(1); //B0001 , new BookInfo(xxx,xxx,xxx,xxx,xxx,xxx,xxx); shoppMap.put(bookInfoObj.getBookNo(),bookInfoObj); } //4、将Map集合存入session范围 session.setAttribute("SHOPPING_CAR", shoppMap); //5、重定向至cart.jsp页面 resp.sendRedirect("cart.jsp"); } }
976ab15b5b8fe3ed8db800eca3af44a1fafeb1e9
[ "Java", "INI" ]
9
Java
kuangdan-png/git
4f986e031b927cb6bba7947c6b151bb3ff36f7d1
a3a225699e68bfdcb00fd337eeb501cdce49ada6
refs/heads/master
<repo_name>AmityTek/api-nodejs<file_sep>/server/index.js /* Ici c'est le point d'entrée du serveur, je te conseille de faire d'autres fichiers/dossiers pour l'api Il faut que tu démarre un serveur express sur le port 8080 (c'est important pour le front) Tu peux voir dans le package.json pour le script start on utilise nodemon donc tes changements sont instantanément appliqués, pas besoin de relancer le serveur Le front est une application qui tourne sur le port 3000 et le serveur sur le port 8080, du coup pour ton navigateur c'est deux apps différentes donc tu auras forcement des problèmes de cors (Cross-origin resource sharing) à un moment pour régler le soucis il faudra que tu fasses un middleware express et que tu regardes du cote de la méthode "setHeader" Pour l'api il faut 3 routes: - /entries/all en GET qui retourne la liste des entrées de l'annuaire - /entry/[ID] en GET qui retourne une entrée specifique - /entry en POST pour créer une nouvelle entrée et retourne un json de la forme { msg: 'message de création réussie ou d'échec avec la raison' } Pour l'anuaire tu es libre de faire comme tu veux, pour le moment le plus simple est surement de le faire in-memory let entries = [ { id: 1, firstname: 'Thibs', lastname: 'Le Francais', email: '<EMAIL>', phone: '+33678901234'}, { id: 2, firstname: 'Jean', lastname: 'Michel', email: '<EMAIL>', phone: '+33678901234'} ]; Mais si tu veux tu peux aussi faire une db genre sqlLite ou encore un fichier csv. Normalement si tu respectes bien tout tu ne devrais pas avoir à toucher au client/front mais il est possible que tu fasses aussi différement de moi donc si tu dois le modifier un peu c'est pas un problème je t'ai laissé les sources pour ça */ var express = require('express'), app = express(), port = process.env.PORT || 8080; var cors = require('cors') // importing cors var bodyParser = require('body-parser') // importing parsing let routes = require('./routes/route'); //importing route app.use(bodyParser.urlencoded({ extended: true})); // allow parsing json app.use(bodyParser.json()); // allow parsing json app.use(function (req, res, next) // app.use() here is used to setHeader to allow api { cors(); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); res.setHeader('Access-Control-Allow-Credentials', true); next(); }); routes(app); //register the route in app app.listen(port); // listen app on port console.log('server star: ' + port); <file_sep>/client/src/App.js import React, { Component } from 'react'; import BrowserRouter from 'react-router-dom/BrowserRouter'; import Switch from 'react-router-dom/Switch'; import Route from 'react-router-dom/Route'; import Link from 'react-router-dom/Link'; import List from './pages/List'; import Details from './pages/Details'; import Add from './pages/Add'; class App extends Component { render() { return ( <BrowserRouter> <div> <h1>Node test</h1> <nav> <ul> <li><Link to="/">List</Link></li> <li><Link to="/add">Add new entry</Link></li> </ul> </nav> <div> <Switch> <Route exact path="/" component={List}/> <Route exact path="/entry/:id" component={Details}/> <Route exact path="/add" component={Add} /> </Switch> </div> </div> </BrowserRouter> ); } } export default App; <file_sep>/client/src/pages/List.js import React from 'react'; import Link from 'react-router-dom/Link'; class List extends React.Component { state = { entries: [] }; componentDidMount() { fetch('http://localhost:8080/entries/all', { method: 'GET' }).then((res) => res.json()).then(res => { this.setState({entries: res}); }); } renderEntries = () => ( this.state.entries.map(entry => ( <tr key={entry.id}> <td>{entry.id}</td> <td>{entry.firstname[0]}. {entry.lastname}</td> <td><Link to={`/entry/${entry.id}`}>Details</Link></td> </tr> )) ); render () { return ( <div> <table style={{width: '100%'}}> <thead> <tr> <th style={{textAlign: 'left'}}>#ID</th> <th style={{textAlign: 'left'}}>Name</th> <th style={{textAlign: 'left'}}>Actions</th> </tr> </thead> <tbody> { this.renderEntries() } </tbody> </table> </div> ); } } export default List; <file_sep>/client/src/pages/Add.js import React from 'react'; class Add extends React.Component { onSubmit = (e) => { e.preventDefault(); const fields = { firstname: this.firstname.value, lastname: this.lastname.value, email: this.email.value, phone: this.phone.value }; fetch(`http://localhost:8080/entry`, { method: 'POST', headers: { 'Content-Type': 'application/json'}, body: JSON.stringify(fields) }) .then((res) => res.json()).then(res => { alert(res.msg); }); }; render () { return ( <form onSubmit={this.onSubmit}> <div> <input required type="text" placeholder="firstname" ref={node => this.firstname = node}/> </div> <div> <input required type="text" placeholder="lastname" ref={node => this.lastname = node}/> </div> <div> <input required type="email" placeholder="email" ref={node => this.email = node}/> </div> <div> <input required type="text" placeholder="phone" ref={node => this.phone = node}/> </div> <div> <button type="submit">Create</button> </div> </form> ); } } export default Add; <file_sep>/server/routes/route.js 'use strict'; var annuaire = require('../controllers/annuaireController'); module.exports = function(app) { // Annuaire Routes app.route('/').get(annuaire.getAllContact) app.route('/entries/all').get(annuaire.getAllContact) app.route('/entry/:id').get(annuaire.getContactById) app.route('/entry').post(annuaire.postContact); }; <file_sep>/client/src/pages/Details.js import React from 'react'; import Link from 'react-router-dom/Link'; class Details extends React.Component { state = { entry: null }; componentDidMount() { fetch(`http://localhost:8080/entry/${this.props.match.params.id}`, { method: 'GET' }).then((res) => res.json()).then(res => { this.setState({entry: res}); }); } render () { if (!this.state.entry) { return <div>Loading</div> } const { entry } = this.state; return ( <div> <h1>{entry.firstname} {entry.lastname}</h1> <div>Id: #{entry.id}</div> <div>Email: {entry.email}</div> <div>Phone: {entry.phone}</div> </div> ); } } export default Details;
937adf1ddbe53721b045781e0c3fc7672446e151
[ "JavaScript" ]
6
JavaScript
AmityTek/api-nodejs
6b0dca8b5db44c8661be84050dd44aa46e86220d
3b50dd668928c64b95ff70ee67f8bdef67f9ed2f
refs/heads/master
<repo_name>jjruri/R_TaskApp<file_sep>/R_TaskApp/ViewController.swift // // ViewController.swift // R_TaskApp // // Created by 佐藤るり on 2020/02/19. // Copyright © 2020 junya.satou. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //tableViewの表示・挙動をTableview自身で解決せずにViewControllerに任せるという処理を記載 tableView.delegate = self tableView.dataSource = self } // データの数(=セルの数)を返すメソッド ★必須 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } // 各セルの内容を返すメソッド ★必須 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 再利用可能な cell を得る let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) return cell } // 各セルを選択した時に実行されるメソッド func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier:"cellSegue",sender: nil) } // セルが削除が可能なことを伝えるメソッド func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath)-> UITableViewCell.EditingStyle { return.delete } // Delete ボタンが押された時に呼ばれるメソッド func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { //★現時点では空にしておく } }
00f010e2fef65de0f42e29a0d583d2eaedf8c652
[ "Swift" ]
1
Swift
jjruri/R_TaskApp
d91d6683edacd0dc40d916ec3f7794918462288f
b5fec794d130177b12e84cff47068ec0b255e995
refs/heads/main
<file_sep># read csv's words <- read.csv("C:\\Users\\cml3t\\Desktop\\Shows\\word_counts_theoffice.csv", stringsAsFactors = FALSE); ratings <- read.csv("C:\\Users\\cml3t\\Desktop\\Shows\\episode_ratings.csv", stringsAsFactors = FALSE); # drop the duplicate columns drop <- c("Show","Season","Episode") words = words[,!(names(words) %in% drop)] # join them library("dplyr"); joined <- inner_join(words, ratings, by = "Episode_ID",stringsAsFactors = FALSE); # drop the ones with bad data # joined <- joined[joined$Drop=="No",]; # adjust the double episodes # joined$Words <- ifelse(joined$Duplicate == "Yes", joined$Words / 2, joined$Words) # get each shows frame himym <- joined[joined$Show=="How I Met Your Mother",]; office <- joined[joined$Show=="The Office",]; friends <- joined[joined$Show=="Friends",]; # HOW I MET YOUR MOTHER SECTION # himym_results <- data.frame(Character = character(0), Coefficient = double(0), stringsAsFactors = FALSE); characters <- unique(as.character(himym$Character)); for (char in characters) { # get correlation char <- as.character(char); trimmed <- himym[himym$Character == char,]; correl = cor(trimmed$Words,trimmed$Rating); # get the new row to add newrow <- data.frame(Character = c(char), Coefficient = c(correl), stringsAsFactors = FALSE); himym_results <- rbind(newrow,himym_results); } # THE OFFICE SECTION # office_results <- data.frame(Character = character(0), Coefficient = double(0), stringsAsFactors = FALSE); characters <- unique(as.character(office$Character)); for (char in characters) { # get correlation char <- as.character(char); trimmed <- office[office$Character == char,]; correl = cor(trimmed$Words,trimmed$Rating); # get the new row to add newrow <- data.frame(Character = c(char), Coefficient = c(correl), stringsAsFactors = FALSE); office_results <- rbind(newrow,office_results); } # FRIENDS SECTION # friends_results <- data.frame(Character = character(0), Coefficient = double(0), stringsAsFactors = FALSE); characters <- unique(as.character(friends$Character)); for (char in characters) { # get correlation char <- as.character(char); trimmed <- friends[friends$Character == char,]; correl = cor(trimmed$Words,trimmed$Rating); # get the new row to add newrow <- data.frame(Character = c(char), Coefficient = c(correl), stringsAsFactors = FALSE); friends_results <- rbind(newrow,friends_results); } # save the office results to a csv write.csv(office_results,"C:\\Users\\cml3t\\Desktop\\Shows\\office_results.csv", row.names = FALSE)
99185d2bea4351967c67dfd201228af021b0f655
[ "R" ]
1
R
cml3ta/theoffice
fc089258d8e932180d71d1f7c20fcd5c19145972
83bca0893684c216fc18d7fdb1458812b8d9c68b
refs/heads/master
<repo_name>akkivaghasiya5/lv-socialite<file_sep>/.env.example APP_NAME=LV-Socialite APP_ENV=local APP_KEY= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://lv-socialite.com DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=lv_socialite DB_USERNAME=root DB_PASSWORD=<PASSWORD> BROADCAST_DRIVER=log CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync REDIS_HOST=127.0.0.1 REDIS_PASSWORD=<PASSWORD> REDIS_PORT=6379 MAIL_DRIVER=log GITHUB_CLIENT_ID= GITHUB_CLIENT_SECRET= GITHUB_REDIRECT=http://lv-socialite.com/login/github/callback GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= GOOGLE_REDIRECT=http://lv-socialite.com/login/google/callback <file_sep>/app/Http/Controllers/Api/v1/Auth/LoginController.php <?php namespace App\Http\Controllers\Api\v1\Auth; use App\Traits\PassportToken; use Auth; use App\Models\User; use Laravel\Passport\Client; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class LoginController extends Controller { use PassportToken; private $client; public function __construct() { $this->client = Client::find(2); } public function loginProvider(Request $request, $service) { $serviceIdCol = $service . '_id'; $user = User::where($serviceIdCol, $request->{$serviceIdCol})->orWhere('email', $request->email)->first(); if ($user) { if (!$user->{$serviceIdCol}) { $user->{$serviceIdCol} = $request->{$serviceIdCol}; } $user->save(); } else { $user = new User; $user->{$serviceIdCol} = $request->{$serviceIdCol}; $user->email = $request->email; $user->name = $request->name; $user->save(); } return $this->getBearerTokenByUser($user, 2, true); } public function login(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => '<PASSWORD>' ]); $params = [ 'grant_type' => 'password', 'client_id' => $this->client->id, 'client_secret' => $this->client->secret, 'username' => request('email'), 'password' => request('<PASSWORD>'), 'scope' => '*', ]; $request->request->add($params); $proxy = \Request::create('oauth/token', 'POST'); return \Route::dispatch($proxy); } public function refresh(Request $request) { $this->validate($request, [ 'refresh_token' => 'required' ]); $params = [ 'grant_type' => 'refresh_token', 'client_id' => $this->client->id, 'client_secret' => $this->client->secret, ]; $request->request->add($params); $proxy = \Request::create('oauth/token', 'POST'); return \Route::dispatch($proxy); } public function logout(Request $request, $devices = FALSE) { $this->logoutMultiple(\Auth::user(), $devices); return response()->json([], 204); } private function logoutMultiple(\App\Models\User $user, $devices = FALSE) { $accessTokens = $user->tokens(); if ($devices == 'all') { } else if ($devices == 'other') { $accessTokens->where('id', '!=', $user->token()->id); } else { $accessTokens->where('id', '=', $user->token()->id); } $accessTokens = $accessTokens->get(); foreach ($accessTokens as $accessToken) { $refreshToken = \DB::table('oauth_refresh_tokens') ->where('access_token_id', $accessToken->id) ->update(['revoked' => TRUE]); $accessToken->revoke(); } } } <file_sep>/app/Http/Controllers/Auth/LoginController.php <?php namespace App\Http\Controllers\Auth; use App\Models\User; use Socialite; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { use AuthenticatesUsers; protected $redirectTo = '/home'; public function __construct() { $this->middleware('guest')->except('logout'); } public function redirectToProvider($service) { return Socialite::driver($service)->redirect(); } public function handleProviderCallback($service) { if ($service == 'twitter') { $providerUser = Socialite::driver($service)->user(); } else { $providerUser = Socialite::driver($service)->stateless()->user(); } $serviceIdCol = $service . '_id'; $user = User::where($serviceIdCol, $providerUser->getId())->orWhere('email', $providerUser->getEmail())->first(); if ($user) { if (!$user->{$serviceIdCol}) { $user->{$serviceIdCol} = $providerUser->getId(); } $user->save(); } else { $user = new User; $user->{$serviceIdCol} = $providerUser->getId(); $user->email = $providerUser->getEmail(); $user->name = $providerUser->getName(); $user->save(); } \Auth::login($user); return redirect('home'); } } <file_sep>/routes/api.php <?php use Illuminate\Http\Request; Route::group(['namespace' => 'Api\v1'], function () { Route::group(['namespace' => 'Auth'], function () { Route::post('login', 'LoginController@login'); Route::post('login/{provider}', 'LoginController@loginProvider'); Route::post('refresh', 'LoginController@refresh'); }); }); Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); });
a49e1b1d5627528409a0bc247c9e3fb2a64e9fdb
[ "PHP", "Shell" ]
4
Shell
akkivaghasiya5/lv-socialite
a44e553d80a1da36b853a6c67bddc18947a7cda0
a1df5258391ddd04f1b7de1d27c34297144b47d3
refs/heads/master
<file_sep>"use strict" const data = [8, 9, 10, 11, 12, 13, 14, 100, 45, 60, 30] const newDataEven = data.filter(num => { return (num % 2 === 0) }) const newDataOdd = data.filter(num => { return (num % 2 !== 0) }) const toBiggerNumber = data.map(num => { if (num > 20) { return num } }).filter(item => item != undefined) const toLowerNumber = data.map(num => { if (num < 20) { return num * 2 } }).filter(item => item !== undefined) console.log(newDataEven); console.log(newDataOdd); console.log(toBiggerNumber); console.log(toLowerNumber); const originalArray = [1, 2, undefined, 3, 'asdakjlsdjlkasdjasd']; const newArray = originalArray .filter(value => { return Number.isInteger(value); }).map(value => { return value * 2; }); console.log(newArray);<file_sep># Project Javascript Number Methods It's recommended to create multiple pages for each particular functions. So we can test those functions better. Use multiple variables to contain variety of numbers. Create multiple functions to operate on those variables. - You can log or alert those data - You can operate those data and then return a new data
b1bbb2a6201255246925411a322cbaced82b5a89
[ "JavaScript", "Markdown" ]
2
JavaScript
rizariza69/project-javascript-number-methods
f6cfcf979822754f47ce20997206f932032e13c7
bed59a811e1e546979bea42c405303519fdcd271
refs/heads/master
<repo_name>gutyoh/Multilingual-Online-Translator<file_sep>/Multilingual Online Translator/task/translator/translator.py import requests import sys from bs4 import BeautifulSoup url = "https://context.reverso.net/translation/" language_list = ["arabic", "german", "english", "spanish", "french", "hebrew", "japanese", "dutch", "polish", "portuguese", "romanian", "russian", "turkish", "all"] em_list = [] text_list = [] text_list2 = [] translation_list = [] j = 0 my_arg_list = str(sys.argv) # print("Hello, welcome to the translator. Translator supports:") # # for i in range(len(language_list)): # print(str(i + 1) + ".", language_list[i]) # # print("Type the number of your language:") # # lang_input_a = int(input()) # # print("Type the number of a language you want to translate to or '0' to translate to all languages:") # # lang_input_b = int(input()) # # if lang_input_a == lang_input_b: # print("ERROR") # exit() # print("Type the word you want to translate:") # # word = str(input()) word = sys.argv[3] word = word.lower() if sys.argv[1].lower() not in language_list: print("Sorry, the program doesn't support", sys.argv[1]) exit() elif sys.argv[2].lower() not in language_list: print("Sorry, the program doesn't support", sys.argv[2]) exit() r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) if r.status_code != 200: print("Something wrong with your internet connection") exit() test = requests.get("https://context.reverso.net/translation/english-spanish/" + word, headers={'User-Agent': 'Mozilla/5.0'}) if test.status_code == 404: print("Sorry, unable to find", word) exit() if sys.argv[1] == "arabic": lang_a = "arabic" lang_input_a = 1 elif sys.argv[1] == "german": lang_a = "german" lang_input_a = 2 elif sys.argv[1] == "english": lang_a = "english" lang_input_a = 3 elif sys.argv[1] == "spanish": lang_a = "spanish" lang_input_a = 4 elif sys.argv[1] == "french": lang_a = "french" lang_input_a = 5 elif sys.argv[1] == "hebrew": lang_a = "hebrew" lang_input_a = 6 elif sys.argv[1] == "japanese": lang_a = "japanese" lang_input_a = 7 elif sys.argv[1] == "dutch": lang_a = "dutch" lang_input_a = 8 elif sys.argv[1] == "polish": lang_a = "polish" lang_input_a = 9 elif sys.argv[1] == "portuguese": lang_a = "portuguese" lang_input_a = 10 elif sys.argv[1] == "romanian": lang_a = "romanian" lang_input_a = 11 elif sys.argv[1] == "russian": lang_a = "russian" lang_input_a = 12 elif sys.argv[1] == "turkish": lang_a = "turkish" lang_input_a = 13 if sys.argv[2] == "all": while j < 13: if j+1 == lang_input_a: j += 1 else: r = requests.get("https://context.reverso.net/translation/" + sys.argv[1] + "-" + language_list[j].lower() + "/" + word, headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(r.content, 'html.parser') em = soup.find_all("em") translation = soup.find_all('a', {"class": 'link_highlighted'}) text = soup.find_all('div', {"class": "src ltr"}) text2 = soup.find_all('div', {"class": ["trg ltr", "trg rtl arabic", "trg rtl"]}) for i in translation: translation_list.append(i.get_text()) for i in text: text_list.append(i.get_text().strip()) for i in text2: text_list2.append(i.get_text().strip()) # print("English Translations:") # for i in em_list[:5]: # print(i) # # print("\nEnglish Examples:") # for i in range(0, 5): # print(text_list[i]) # print(text_list2[i], "\n") with open(word + ".txt", "a", encoding='utf-8') as file: # print("\n" + language_list[j], "Translations:") file.writelines(language_list[j] + " Translations:" + "\n") for i in range(0, 1): # print(em_list[i]) file.writelines(translation_list[i] + "\n" + "\n") # print("\n" + language_list[j], "Examples:") file.writelines(language_list[j] + " Example:" + "\n") for i in range(0, 1): # print(text_list[i]) file.writelines(text_list[i] + "\n") # print(text_list2[i], "\n") file.writelines(text_list2[i] + "\n" + "\n") file.writelines("\n") j += 1 em_list = [] translation_list = [] text_list = [] text_list2 = [] if j == 13: with open(word + ".txt", "r", encoding='utf-8') as file: print(file.read()) file.close() exit() elif sys.argv[2] == "turkish": lang_b = "turkish" lang_input_b = 1 elif sys.argv[2] == "german": lang_b = "german" lang_input_b = 2 elif sys.argv[2] == "english": lang_b = "english" lang_input_b = 3 elif sys.argv[2] == "spanish": lang_b = "spanish" lang_input_b = 4 elif sys.argv[2] == "french": lang_b = "french" lang_input_b = 5 elif sys.argv[2] == "hebrew": lang_b = "hebrew" lang_input_b = 6 elif sys.argv[2] == "japanese": lang_b = "japanese" lang_input_b = 7 elif sys.argv[2] == "dutch": lang_b = "dutch" lang_input_b = 8 elif sys.argv[2] == "polish": lang_b = "polish" lang_input_b = 9 elif sys.argv[2] == "portuguese": lang_b = "portuguese" lang_input_b = 10 elif sys.argv[2] == "romanian": lang_b = "romanian" lang_input_b = 11 elif sys.argv[2] == "russian": lang_b = "russian" lang_input_b = 12 elif sys.argv[2] == "turkish": lang_b = "turkish" lang_input_b = 13 r = requests.get("https://context.reverso.net/translation/" + sys.argv[1] + "-" + sys.argv[2] + "/" + word, headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(r.content, 'html.parser') em = soup.find_all("em") translation = soup.find_all('a', {"class": 'link_highlighted'}) text = soup.find_all('div', {"class": "src ltr"}) text2 = soup.find_all('div', {"class": "trg ltr"}) for i in translation: translation_list.append(i.get_text()) for i in text: text_list.append(i.get_text().strip()) for i in text2: text_list2.append(i.get_text().strip()) print("\n") with open(word + ".txt", "a", encoding='utf-8') as file: file.writelines(language_list[lang_input_b-1] + " Translations:" + "\n") for i in range(0, 1): file.writelines(translation_list[i] + "\n" + "\n") file.writelines(language_list[lang_input_b - 1] + " Example:" + "\n") for i in range(0, 1): file.writelines(text_list[i] + "\n") file.writelines(text_list2[i] + "\n" + "\n") file.writelines("\n") with open(word + ".txt", "r", encoding='utf-8') as file: print(file.read()) file.close() exit()
c5d2186e11c9e9db7acf85fb8f7fbd9397c8070e
[ "Python" ]
1
Python
gutyoh/Multilingual-Online-Translator
17b3218b85f26e701d5e02cd8830b22815c55508
6fc94afbcdce87460050aed7203cdaa97acb3f99
refs/heads/master
<file_sep># -*- coding: utf-8 -*- #!/usr/bin/env python """ Runs the Meissnert SNPiR RNA-variant discovery pipeline in optimized mode in one Node See below for options """ def create_wf_meta(options, output_dir, tmp_dir): # reads fastq = options.fastq if options.rfastq: rfastq = options.rfastq read_length = get_readLength(fastq) # get sample name sample_name = get_sampleName(fastq) # get ncores ncpu = get_ncores() nthreads = ncpu/2 # get memory jvm_heap = get_linuxRAM() # get the reference datasets reference_db = options.gatk_ref dbsnp="/mnt/galaxyIndices/genomes/Hsapiens/human_g1k_v37/annotation/dbsnp_138.b37.vcf" mills="/mnt/galaxyIndices/genomes/Hsapiens/human_g1k_v37/annotation/Mills_and_1000G_gold_standard.indels.b37.vcf" mask="/mnt/galaxyIndices/genomes/Hsapiens/human_g1k_v37/annotation/b37_cosmic_v54_120711.vcf" #GATK3_PATH = os.environ['GATK3_PATH'] GATK3_PATH = "/mnt/galaxyTools/tools/gatk3/GenomeAnalysisTK-3.4-0" #JAVA_JAR_PATH = os.environ['JAVA_JAR_PATH'] JAVA_JAR_PATH = "/mnt/galaxyTools/tools/picard/1.134" bwa_index = options.bwa_ref ## Setup workflow command_meta = {} read_group = "--rgid=\"%s\" --rglb=\"%s\" --rgpl=\"%s\" --rgsm=\"%s\"" % (options.rgid, options.rglb, options.rgpl, options.rgsm) if options.rgcn: read_group += " --rgcn=\"%s\"" % options.rgcn if options.rgds: read_group += " --rgds=\"%s\"" % options.rgds if options.rgdt: read_group += " --rgdt=\"%s\"" % options.rgdt if options.rgfo: read_group += " --rgfo=\"%s\"" % options.rgfo if options.rgks: read_group += " --rgks=\"%s\"" % options.rgks if options.rgpg: read_group += " --rgpg=\"%s\"" % options.rgpg if options.rgpi: read_group += " --rgpi=\"%s\"" % options.rgpi if options.rgpu: read_group += " --rgpu=\"%s\"" % options.rgpu # step = 0 ncpu_step = int(ncpu) - 2 command_meta[step] = [] input1 = fastq input2 = rfastq input_files = [input1, input2] outputF = "%s/%s-bwa-out.bam" % (output_dir, sample_name) output_files = [outputF] cmd = " python /opt/galaxy/tools/sr_mapping/bwa_mem.py --threads=%s --fileSource=indexed --ref=%s --fastq=%s --rfastq=%s --output=%s --genAlignType=paired --params=full --minSeedLength 19 --bandWidth 100 --offDiagonal 100 --internalSeeds 1.5 --seedsOccurrence 10000 --seqMatch 1 --mismatch 4 --gapOpen 6 --gapExtension 1 --clipping 5 --unpairedReadpair 17 --minScore 30 %s -M --bam" % (ncpu_step, bwa_index, input1, input2, outputF, read_group) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files": output_files}) inputF = rfastq fastqc_dir = "%s/%s-FastQCr2_dir" % (output_dir, sample_name) name = "FastQCr2" input_files = [inputF] outputF = "%s/%s-fastqc_out_2.html" % (output_dir, sample_name) output_files = [outputF, fastqc_dir] cmd = "python /opt/galaxy/tools/rgenetics/rgFastQC.py -i %s -d %s -o %s -n %s -f fastqsanger -j %s -e /nfs/software/galaxy/tool-data/shared/jars/FastQC/fastqc" % (inputF, fastqc_dir, outputF, name, name) command_meta[step].append({"cl":cmd, "input_files": input_files, "output_file":outputF, "output_files":output_files}) inputF = fastq fastqc_dir = "%s/%s-FastQCr1_dir" % (output_dir, sample_name) name = "FastQCr1" input_files = [inputF] outputF = "%s/%s-fastqc_out_1.html" % (output_dir, sample_name) output_files = [outputF, fastqc_dir] cmd = "python /opt/galaxy/tools/rgenetics/rgFastQC.py -i %s -d %s -o %s -n %s -f fastqsanger -j %s -e /nfs/software/galaxy/tool-data/shared/jars/FastQC/fastqc" % (inputF, fastqc_dir, outputF, name, name) command_meta[step].append({"cl":cmd, "input_files": input_files, "output_file":outputF, "output_files":output_files}) # step = 1 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/%s-bwa-out.sort.bam" % (output_dir, sample_name) input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/sambamba/sambamba_sort.py --memory %sM --input=%s --order=coordinate --output=%s" % (jvm_heap, inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 2 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/%s-bwa-out.sort.rd.bam" % (output_dir, sample_name) outputMetrics = "%s/%s-SM1.dups" % (output_dir, sample_name) input_files = [inputF] output_files = [outputF, outputMetrics] cmd = "python /opt/galaxy/tools/picard/picard_wrapper.py --maxjheap %sm -i %s -n Dupes_Marked --tmpdir %s -o %s --remdups true --assumesorted true --readregex \"[a-zA-Z0-9]+:[0-9]:([0-9]+):([0-9]+):([0-9]+).*\" --optdupdist 100 -j \"%s/picard.jar MarkDuplicates\" -d %s -t %s -e bam" % (jvm_heap, inputF, tmp_dir, outputF, JAVA_JAR_PATH, tmp_dir, outputMetrics) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 3 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/%s-bwa-out.sort.rd.bam.bai" % (output_dir, sample_name) input_files = [inputF] output_files = [outputF] cmd = "samtools index %s" % (inputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 4 command_meta[step] = [] inputF = command_meta[step-2][0]["output_file"] inputIndex = command_meta[step-1][0]["output_file"] outputF = "%s/%s-output.intervals" % (output_dir, sample_name) outputLog = "%s/%s-output.intervals.log" % (output_dir, sample_name) input_files = [inputF, inputIndex] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T RealignerTargetCreator -ip %s -o %s --num_threads %s -R %s\" -d \"--intervals\" \"%s\" \"bed\" \"input_intervals_0\" -d \"-known:dbsnp,%%(file_type)s\" \"%s\" \"vcf\" \"input_dbsnp_0\" -d \"-known:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_0\"" % (outputLog, inputF, inputIndex, GATK3_PATH, options.ip, outputF, ncpu, reference_db, options.bed, dbsnp, mills) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 5 command_meta[step] = [] inputBam = command_meta[step-3][0]["output_file"] inputF = command_meta[step-1][0]["output_file"] inputIndex = command_meta[step-2][0]["output_file"] outputF = "%s/%s-bwa-out.sort.rd.realigned.bam" % (output_dir, sample_name) outputLog = "%s/%s-bwa-out.sort.rd.realigned.log" % (output_dir, sample_name) input_files = [inputF, inputIndex, inputBam] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T IndelRealigner -ip %s -o %s -R %s -LOD 5.0\" -d \"--intervals\" \"%s\" \"bed\" \"input_intervals_0\" -d \"-known:dbsnp,%%(file_type)s\" \"%s\" \"vcf\" \"input_dbsnp_0\" -d \"-known:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_0\" -d \"-targetIntervals\" \"%s\" \"gatk_interval\" \"gatk_target_intervals\"" % (outputLog, inputBam, inputIndex, GATK3_PATH, options.ip, outputF, reference_db, options.bed, dbsnp, mills, inputF ) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 6 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/%s-bwa-out.sort.rd.realigned.bam.bai" % (output_dir, sample_name) input_files = [inputF] output_files = [outputF] cmd = "samtools index %s" % (inputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 7 command_meta[step] = [] inputBam = command_meta[step-2][0]["output_file"] inputIndex = command_meta[step-1][0]["output_file"] outputF = "%s/%s-recal_data.table" % (output_dir, sample_name) outputLog = "%s/%s-bwa-out.sort.rd.realigned.log" % (output_dir, sample_name) input_files = [inputBam, inputIndex] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T BaseRecalibrator -ip %s -nct %s -R %s --out %s\" -d \"--intervals\" \"%s\" \"bed\" \"input_intervals_0\" -d \"--knownSites:dbsnp,%%(file_type)s\" \"%s\" \"vcf\" \"input_dbsnp_0\" -d \"--knownSites:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_0\"" % (outputLog, inputBam, inputIndex, GATK3_PATH, options.ip, ncpu, reference_db, outputF, options.bed, dbsnp, mills ) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 8 command_meta[step] = [] inputBam = command_meta[step-3][0]["output_file"] inputTable = command_meta[step-1][0]["output_file"] inputIndex = command_meta[step-2][0]["output_file"] #outputF = "%s/%s-bwa-out.sort.rd.realigned.recal.bam" % (output_dir, sample_name) outputF = options.output_bam outputLog = "%s/%s-bwa-out.sort.rd.realigned.recal.log" % (output_dir, sample_name) input_files = [inputTable, inputBam, inputIndex] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -d \"--intervals\" \"%s\" \"bed\" \"input_intervals_0\" -p \"java -jar %s/GenomeAnalysisTK.jar -T PrintReads -ip %s -o %s -nct %s -R %s --BQSR %s\"" % (outputLog, inputBam, inputIndex, options.bed, GATK3_PATH, options.ip, outputF, ncpu, reference_db, inputTable) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 9 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/%s-bwa-out.sort.rd.realigned.recal.bam.bai" % (output_dir, sample_name) input_files = [inputF] output_files = [outputF] cmd = "samtools index %s" % (inputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 10 command_meta[step] = [] inputBam = command_meta[step-2][0]["output_file"] inputIndex = command_meta[step-1][0]["output_file"] outputF = "%s/%s-raw_variants.vcf" % (output_dir, sample_name) outputLog = "%s/%s-raw_variants.log" % (output_dir, sample_name) input_files = [inputBam, inputIndex] output_files = [outputF, outputLog, inputIndex] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap %sm --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input_0\" -d \"\" \"%s\" \"bam_index\" \"gatk_input_0\" -d \"--dbsnp:dbsnp,%%(file_type)s\" \"%s\" \"vcf\" \"input_dbsnp_0\" -d \"--intervals\" \"%s\" \"bed\" \"input_intervals_0\" -p \"java -jar %s/GenomeAnalysisTK.jar -T HaplotypeCaller -ip %s -nct %s --out %s -R %s --output_mode EMIT_VARIANTS_ONLY\"" % (jvm_heap, outputLog, inputBam, inputIndex, dbsnp, options.bed, GATK3_PATH, options.ip, ncpu, outputF, reference_db) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 11 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/%s-raw_variants.filter.vcf" % (output_dir, sample_name) outputLog = "%s/%s-raw_variants.filter.log" % (output_dir, sample_name) input_files = [inputF] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap %sm --stdout %s -d \"--variant:variant,%%(file_type)s\" \"%s\" \"vcf\" \"input_variant\" -d \"--intervals\" \"%s\" \"bed\" \"input_intervals_0\" -p \"java -jar %s/GenomeAnalysisTK.jar -T VariantFiltration -ip %s -o %s -R %s --maskExtension 0 --maskName Mask\" -d \"--mask:Mask,%%(file_type)s\" \"%s\" \"vcf\" \"input_mask_Mask\"" % (jvm_heap, outputLog, inputF, options.bed, GATK3_PATH, options.ip, outputF, reference_db, mask) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 12 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] #outputF = "%s/%s-raw_variants.filter.select.vcf" % (output_dir, sample_name) outputF = options.output_vcf outputLog = "%s/%s-raw_variants.filter.select.log" % (output_dir, sample_name) input_files = [inputF] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap %sm --stdout %s -d \"--variant:variant,%%(file_type)s\" \"%s\" \"vcf\" \"input_variant\" -d \"--intervals\" \"%s\" \"bed\" \"input_intervals_0\" -p \"java -jar %s/GenomeAnalysisTK.jar -T SelectVariants -ip %s --num_threads %s -o %s -R %s\"" % (jvm_heap, outputLog, inputF, options.bed, GATK3_PATH, options.ip, ncpu, outputF, reference_db) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) return command_meta <file_sep># -*- coding: utf-8 -*- #!/usr/bin/env python """ Runs the Meissnert SNPiR RNA-variant discovery pipeline in optimized mode in one Node See below for options """ def create_wf_meta(options, output_dir, tmp_dir): # reads fastq = options.fastq if options.rfastq: rfastq = options.rfastq read_length = get_readLength(fastq) # get ncores ncpu = get_ncores() nthreads = ncpu/2 # get memory jvm_heap = get_linuxRAM() # get the reference datasets hg19_reference="/mnt/galaxyIndices/genomes/Hsapiens/hg19/seq/hg19_jxn.fa" RepeatMasker="/mnt/galaxyIndices/genomes/Hsapiens/hg19/annotation/repeatmasker.bed" gene_annotation="/mnt/galaxyIndices/genomes/Hsapiens/hg19/annotation/hg19_gene_annotation.gtf" rnaedit="/mnt/galaxyIndices/genomes/Hsapiens/hg19/annotation/rnaedit.bed" dbsnp="/mnt/galaxyIndices/genomes/Hsapiens/hg19/annotation/dbsnp_138.hg19.vcf" mills="/mnt/galaxyIndices/genomes/Hsapiens/hg19/annotation/Mills_and_1000G_gold_standard.indels.hg19.vcf" g1000="/mnt/galaxyIndices/genomes/Hsapiens/hg19/annotation/1000G_phase1.indels.hg19.vcf" GATK3_PATH = "/mnt/galaxyTools/tools/gatk3/GenomeAnalysisTK-3.4-0" JAVA_JAR_PATH = "/mnt/galaxyTools/tools/picard/1.134" #bwa_index = None #if read_length <= 45: # bwa_index="/scratch/averahealth/galaxy/data/genomes/Hsapiens/hg19/bwa_0.7.10_junctions/45bp/hg19_genome_junctions_45.fa" #elif read_length <= 75: # bwa_index="/scratch/averahealth/galaxy/data/genomes/Hsapiens/hg19/bwa_0.7.10_junctions/75bp/hg19_genome_junctions_75.fa" #elif read_length <= 95: # bwa_index="/scratch/averahealth/galaxy/data/genomes/Hsapiens/hg19/bwa_0.7.10_junctions/95bp/hg19_genome_junctions_95.fa" #elif read_length <= 140: # bwa_index="/scratch/averahealth/galaxy/data/genomes/Hsapiens/hg19/bwa_0.7.10_junctions/140bp/hg19_genome_junctions_140.fa" bwa_index=options.ref ## Setup workflow command_meta = {} read_group = "--rgid=\"%s\" --rglb=\"%s\" --rgpl=\"%s\" --rgsm=\"%s\"" % (options.rgid, options.rglb, options.rgpl, options.rgsm) if options.rgcn: read_group += " --rgcn=\"%s\"" % options.rgcn if options.rgds: read_group += " --rgds=\"%s\"" % options.rgds if options.rgdt: read_group += " --rgdt=\"%s\"" % options.rgdt if options.rgfo: read_group += " --rgfo=\"%s\"" % options.rgfo if options.rgks: read_group += " --rgks=\"%s\"" % options.rgks if options.rgpg: read_group += " --rgpg=\"%s\"" % options.rgpg if options.rgpi: read_group += " --rgpi=\"%s\"" % options.rgpi if options.rgpu: read_group += " --rgpu=\"%s\"" % options.rgpu # step = 0 command_meta[step] = [] inputF = fastq input_files = [inputF] outputF = "%s/bwa-out1.sam" % output_dir output_files = [outputF] cmd = "python /opt/galaxy/tools/sr_mapping/bwa_wrapper.py --threads=%s --fileSource=indexed --ref=%s --do_not_build_index --input1=%s --output=%s --genAlignType=single --params=full --maxEditDist=0 --fracMissingAligns=0.04 --maxGapOpens=1 --maxGapExtens=-1 --disallowLongDel=16 --disallowIndel=5 --seed=-1 --maxEditDistSeed=2 --mismatchPenalty=3 --gapOpenPenalty=11 --gapExtensPenalty=4 --suboptAlign=\"\" --noIterSearch=false --outputTopN=3 --outputTopNDisc=10 --maxInsertSize=500 --maxOccurPairing=100000 %s --suppressHeader=false" % (nthreads, bwa_index, inputF, outputF, read_group) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files": output_files}) inputF = rfastq input_files = [inputF] outputF = "%s/bwa-out2.sam" % output_dir output_files = [outputF] cmd = "python /opt/galaxy/tools/sr_mapping/bwa_wrapper.py --threads=%s --fileSource=indexed --ref=%s --do_not_build_index --input1=%s --output=%s --genAlignType=single --params=full --maxEditDist=0 --fracMissingAligns=0.04 --maxGapOpens=1 --maxGapExtens=-1 --disallowLongDel=16 --disallowIndel=5 --seed=-1 --maxEditDistSeed=2 --mismatchPenalty=3 --gapOpenPenalty=11 --gapExtensPenalty=4 --suboptAlign=\"\" --noIterSearch=false --outputTopN=3 --outputTopNDisc=10 --maxInsertSize=500 --maxOccurPairing=100000 %s --suppressHeader=false" % (nthreads, bwa_index, inputF, outputF, read_group) command_meta[step].append({"cl":cmd, "input_files": input_files, "output_file":outputF, "output_files":output_files}) # step = 1 command_meta[step] = [] inputF = command_meta[step-1][1]["output_file"] outputF = "%s/grep1.sam" % output_dir input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/filters/grep.py -i %s -o %s -pattern '^@' -v true" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 2 command_meta[step] = [] outputF = "%s/merged.sam" % output_dir input_files = [command_meta[0][0]["output_file"], command_meta[1][0]["output_file"]] output_files = [outputF] cmd = "python /opt/galaxy/tools/filters/catWrapper.py %s %s %s" % (outputF, command_meta[0][0]["output_file"], command_meta[1][0]["output_file"]) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 3 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/merged.conv.sam" % output_dir input_files = [inputF] output_files = [outputF] cmd = "cat %s | java -Xmx2g convertCoordinates > %s" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 4 command_meta[step] = [] inputF = command_meta[step-1][0]["output_file"] outputF = "%s/header.sam" % output_dir input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/filters/grep.py -i %s -o %s -pattern '^@' -v false" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 5 command_meta[step] = [] inputF = command_meta[4][0]["output_file"] outputF = "%s/t1.sam" % output_dir input_files = [inputF] output_files = [outputF] cmd = "perl /opt/galaxy/tools/filters/headWrapper.pl %s 25 %s" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # inputF = command_meta[4][0]["output_file"] outputF = "%s/t2.sam" % output_dir input_files = [inputF] output_files = [outputF] cmd = "perl /opt/galaxy/tools/filters/tailWrapper.pl %s 2 %s" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 6 command_meta[step] = [] input1 = command_meta[5][0]["output_file"] input2 = command_meta[5][1]["output_file"] outputF = "%s/new_header.sam" % output_dir input_files = [input1, input2] output_files = [outputF] cmd = "python /opt/galaxy/tools/filters/catWrapper.py %s %s %s" % (outputF, input1, input2) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 7 command_meta[step] = [] input1 = command_meta[3][0]["output_file"] input2 = command_meta[6][0]["output_file"] outputF = "%s/merged.conv.nh.sam" % output_dir input_files = [input1, input2] output_files = [outputF] cmd = "python /opt/galaxy/tools/picard/picard_wrapper.py --input %s -o %s --header-file %s --output-format sam -j \"%s/picard.jar ReplaceSamHeader\" --tmpdir %s" % (input1, outputF, input2, JAVA_JAR_PATH, tmp_dir) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 8 command_meta[step] = [] inputF = command_meta[7][0]["output_file"] outputF = "%s/merged.conv.nh.sort.bam" % output_dir input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/samtools/samtools_filter_bam.py -p '-bS' -p '-q 20' -p '-F 4' --input %s --output %s --sorted-bam" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 9 command_meta[step] = [] inputF = command_meta[8][0]["output_file"] outputF = "%s/merged.conv.nh.sort.rd.bam" % output_dir outputMetrics = "%s/SM1.dups" % output_dir input_files = [inputF] output_files = [outputF, outputMetrics] cmd = "python /opt/galaxy/tools/picard/picard_wrapper.py --maxjheap %sm -i %s -n Dupes_Marked --tmpdir %s -o %s --remdups true --assumesorted true --readregex \"[a-zA-Z0-9]+:[0-9]:([0-9]+):([0-9]+):([0-9]+).*\" --optdupdist 100 -j \"%s/picard.jar MarkDuplicates\" -d %s -t %s -e bam" % (jvm_heap, inputF, tmp_dir, outputF, JAVA_JAR_PATH, tmp_dir, outputMetrics) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 10 command_meta[step] = [] inputF = command_meta[9][0]["output_file"] outputF = "%s/merged.conv.nh.sort.rd.bam.bai" % output_dir input_files = [inputF] output_files = [outputF] cmd = "samtools index %s" % (inputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 11 command_meta[step] = [] inputF = command_meta[9][0]["output_file"] inputIndex = command_meta[10][0]["output_file"] outputF = "%s/output.intervals" % output_dir outputLog = "%s/output.intervals.log" % output_dir input_files = [inputF, inputIndex] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T RealignerTargetCreator -o %s --num_threads %s -R %s\" -d \"-known:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_0\" -d \"-known:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_1\" -p \"--filter_reads_with_N_cigar\"" % (outputLog, inputF, inputIndex, GATK3_PATH, outputF, ncpu, hg19_reference, mills, g1000) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 12 command_meta[step] = [] inputBam = command_meta[9][0]["output_file"] inputF = command_meta[11][0]["output_file"] inputIndex = command_meta[10][0]["output_file"] outputF = "%s/merged.conv.sort.rd.realigned.bam" % output_dir outputLog = "%s/merged.conv.sort.rd.realigned.log" % output_dir input_files = [inputF, inputIndex, inputBam] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T IndelRealigner -o %s -R %s -LOD 0.4 --filter_reads_with_N_cigar --consensusDeterminationModel KNOWNS_ONLY\" -d \"-known:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_0\" -d \"-known:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_1\" -d \"-targetIntervals\" \"%s\" \"gatk_interval\" \"gatk_target_intervals\"" % (outputLog, inputBam, inputIndex, GATK3_PATH, outputF, hg19_reference, mills, g1000, inputF ) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 13 command_meta[step] = [] inputBam = command_meta[12][0]["output_file"] inputIndex = "%s/merged.conv.sort.rd.realigned.bam.bai" % output_dir outputF = "%s/recal_data.table" % output_dir outputLog = "%s/merged.conv.sort.rd.realigned.log" % output_dir input_files = [inputBam] output_files = [outputF, outputLog, inputIndex] cmd = "samtools index %s && python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T BaseRecalibrator -nct %s -R %s --out %s\" -d \"--knownSites:dbsnp,%%(file_type)s\" \"%s\" \"vcf\" \"input_dbsnp_0\" -d \"--knownSites:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_0\" -d \"--knownSites:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_1\"" % (inputBam, outputLog, inputBam, inputIndex, GATK3_PATH, ncpu, hg19_reference, outputF, dbsnp, g1000, mills ) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 14 command_meta[step] = [] inputBam = command_meta[12][0]["output_file"] inputIndex = "%s/merged.conv.sort.rd.realigned.bai" % output_dir inputTable = command_meta[13][0]["output_file"] outputF = "%s/post_recal_data.table" % output_dir outputLog = "%s/merged.conv.sort.rd.realigned.log" % output_dir input_files = [inputBam, inputTable, inputIndex] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T BaseRecalibrator -nct %s --BQSR %s -R %s --out %s\" -d \"--knownSites:dbsnp,%%(file_type)s\" \"%s\" \"vcf\" \"input_dbsnp_0\" -d \"--knownSites:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_0\" -d \"--knownSites:indels,%%(file_type)s\" \"%s\" \"vcf\" \"input_indels_1\"" % (outputLog, inputBam, inputIndex, GATK3_PATH, ncpu, inputTable, hg19_reference, outputF, dbsnp, g1000, mills ) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 15 command_meta[step] = [] inputTable1 = command_meta[13][0]["output_file"] inputTable2 = command_meta[14][0]["output_file"] outputF = "%s/recalibration_plots.pdf" % output_dir outputLog = "%s/recalibration_plots.log" % output_dir input_files = [inputTable1, inputTable2] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 -p \"java -jar %s/GenomeAnalysisTK.jar -T AnalyzeCovariates -before %s -after %s -R %s -csv %s -plots %s\" " % (GATK3_PATH, inputTable1, inputTable2, hg19_reference, outputLog, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 16 command_meta[step] = [] inputBam = command_meta[12][0]["output_file"] inputTable = command_meta[13][0]["output_file"] inputIndex = "%s/merged.conv.sort.rd.realigned.bai" % output_dir #outputF = "%s/merged.conv.sort.rd.realigned.recal.bam" % output_dir outputF = options.output_bam outputLog = "%s/merged.conv.sort.rd.realigned.recal.log" % output_dir input_files = [inputTable, inputBam, inputIndex] output_files = [outputF, outputLog] cmd = "python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap_fraction 1 --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input\" -d \"\" \"%s\" \"bam_index\" \"gatk_input\" -p \"java -jar %s/GenomeAnalysisTK.jar -T PrintReads -o %s -nct %s -R %s --BQSR %s\"" % (outputLog, inputBam, inputIndex, GATK3_PATH, outputF, ncpu, hg19_reference, inputTable) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 17 command_meta[step] = [] inputBam = command_meta[16][0]["output_file"] inputIndex = "%s/merged.conv.sort.rd.realigned.recal.bai" % output_dir outputF = "%s/raw_variants.vcf" % output_dir outputLog = "%s/raw_variants.log" % output_dir outputMetrics = "%s/raw_variants_metrics.txt" % output_dir input_files = [inputBam] output_files = [outputF, outputLog, outputMetrics, inputIndex] cmd = "samtools index %s && python /opt/galaxy/tools/gatk3/gatk3_wrapper.py --max_jvm_heap %sm --stdout %s -d \"-I\" \"%s\" \"bam\" \"gatk_input_0\" -d \"\" \"%s\" \"bam_index\" \"gatk_input_0\" -d \"--dbsnp:dbsnp,%%(file_type)s\" \"%s\" \"vcf\" \"input_dbsnp_0\" -p \"java -jar %s/GenomeAnalysisTK.jar -T UnifiedGenotyper --num_threads %s --out %s --metrics_file %s -R %s --read_filter BadCigar --output_mode EMIT_VARIANTS_ONLY -stand_call_conf 0 -stand_emit_conf 0\"" % (inputBam, jvm_heap, outputLog, inputBam, inputIndex, dbsnp, GATK3_PATH, ncpu, outputF, outputMetrics, hg19_reference) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 18 command_meta[step] = [] inputF = command_meta[17][0]["output_file"] outputF = "%s/raw_variants.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "convertVCF.sh %s %s 20" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 19 command_meta[step] = [] inputF = command_meta[18][0]["output_file"] inputBam = command_meta[16][0]["output_file"] outputF = "%s/raw_variants.rmhex.txt" % output_dir input_files = [inputF, inputBam] output_files = [outputF] cmd = "filter_mismatch_first6bp.pl -infile %s -outfile %s -bamfile %s" % (inputF, outputF, inputBam) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 20 command_meta[step] = [] inputF = command_meta[19][0]["output_file"] outputF = "%s/raw_variants.rmhex.add_column.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/stats/column_maker.py %s %s \"c2-1\" yes 6 \"str,int,list,str,str,float\"" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 21 command_meta[step] = [] inputF = command_meta[20][0]["output_file"] outputF = "%s/raw_variants.rmhex.cut_column.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "perl /opt/galaxy/tools/filters/cutWrapper.pl %s \"c1,c7,c2,c3,c4,c5,c6\" T %s" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 22 command_meta[step] = [] inputF = command_meta[21][0]["output_file"] outputF = "%s/raw_variants.rmhex.intersect.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "intersectBed -a %s -b %s -v > %s" % (inputF, RepeatMasker, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 23 command_meta[step] = [] inputF = command_meta[22][0]["output_file"] outputF = "%s/raw_variants.rmhex.rmsk.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "perl /opt/galaxy/tools/filters/cutWrapper.pl %s \"c1,c3,c4,c5,c6,c7\" T %s" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 24 command_meta[step] = [] inputF = command_meta[23][0]["output_file"] outputF = "%s/raw_variants.rmhex.rmsk.rmintron.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "filter_intron_near_splicejuncts.pl -infile %s -outfile %s -genefile %s -splicedist 4" % (inputF, outputF, gene_annotation) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 25 command_meta[step] = [] inputF = command_meta[24][0]["output_file"] outputF = "%s/raw_variants.rmhex.rmsk.rmintron.rmhom.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "filter_homopolymer_nucleotides.pl -infile %s -outfile %s -refgenome %s" % (inputF, outputF, hg19_reference) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 26 command_meta[step] = [] inputF = command_meta[25][0]["output_file"] inputBam = command_meta[16][0]["output_file"] outputF = "%s/raw_variants.rmhex.rmsk.rmintron.rmhom.rmblat.txt" % output_dir input_files = [inputF, inputBam] output_files = [outputF] cmd = "samtools index -b %s && BLAT_candidates.pl -infile %s -outfile %s -bamfile %s -refgenome %s" % (inputBam, inputF, outputF, inputBam, hg19_reference) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 27 command_meta[step] = [] inputF = command_meta[26][0]["output_file"] outputF = "%s/raw_variants.rmhex.rmsk.rmintron.rmhom.rmblat.add_column.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/stats/column_maker.py %s %s \"c2-1\" yes 6 \"str,int,list,str,str,float\"" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 28 command_meta[step] = [] inputF = command_meta[27][0]["output_file"] outputF = "%s/raw_variants.rmhex.rmsk.rmintron.rmhom.rmblat.cut_column.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "perl /opt/galaxy/tools/filters/cutWrapper.pl %s \"c1,c7,c2,c3,c4,c5,c6\" T %s" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 29 command_meta[step] = [] inputF = command_meta[28][0]["output_file"] outputF = "%s/raw_variants.rmhex.rmsk.rmintron.rmhom.rmblat.rmedit.bed" % output_dir input_files = [inputF] output_files = [outputF] cmd = "intersectBed -a %s -b %s -v > %s" % (inputF, rnaedit, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 30 command_meta[step] = [] inputF = command_meta[17][0]["output_file"] outputF = "%s/raw_variants.header.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/filters/grep.py -i %s -o %s -pattern '^#' -v false" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) outputF = "%s/raw_variants.non_header.txt" % output_dir input_files = [inputF] output_files = [outputF] cmd = "python /opt/galaxy/tools/filters/grep.py -i %s -o %s -pattern '^#' -v true" % (inputF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 31 command_meta[step] = [] inputF = command_meta[29][0]["output_file"] inputVCF = command_meta[30][1]["output_file"] outputF = "%s/red_variants.vcf" % output_dir input_files = [inputF, inputVCF] output_files = [outputF] cmd = "Rscript /opt/galaxy/tools/snpir/extractvcf.R %s %s %s" % (inputF, inputVCF, outputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) # step = 32 command_meta[step] = [] inputF = command_meta[31][0]["output_file"] inputHeader = command_meta[30][0]["output_file"] #outputF = "%s/final_variants.vcf" % output_dir outputF = options.output_vcf input_files = [inputF, inputHeader] output_files = [outputF] cmd = "python /opt/galaxy/tools/filters/catWrapper.py %s %s %s" % (outputF, inputHeader, inputF) command_meta[step].append({"cl":cmd, "input_files":input_files, "output_file":outputF, "output_files":output_files}) return command_meta
783bd5e74ed8a8753313d742fc60144191f1f101
[ "Python" ]
2
Python
arodri7/AveraHealth
2223726eaf6dd646a1b5c8ca2da3a7653a978a59
8a7d7e1f16c6f444ecb4bc2cb6a2aeebd1494935
refs/heads/master
<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 dk.webtrade.recipesolution.logik.entity; import java.util.ArrayList; import java.util.List; /** * * @author thomas */ public class Recipe { int id; String name; String description; String todo; int cookingTime; String img; List<RecipeIngredient> ingredients = new ArrayList(); User user; public Recipe(int id, String name, String description, String todo, int cookingTime, String img) { this.id = id; this.name = name; this.description = description; this.todo = todo; this.cookingTime = cookingTime; this.img = img; } public Recipe(String name, String description, String todo, int cookingTime, String img) { this.name = name; this.description = description; this.todo = todo; this.cookingTime = cookingTime; this.img = img; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTodo() { return todo; } public void setTodo(String todo) { this.todo = todo; } public int getCookingTime() { return cookingTime; } public void setCookingTime(int cookingTime) { this.cookingTime = cookingTime; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public List<RecipeIngredient> getIngredients() { return ingredients; } public void addIngredient(RecipeIngredient ingredient) { this.ingredients.add(ingredient); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } } <file_sep>-- MySQL dump 10.13 Distrib 5.7.23, for Linux (x86_64) -- -- Host: localhost Database: recipesDB -- ------------------------------------------------------ -- Server version 5.7.23-0ubuntu0.16.04.1 /*!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 utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `Ingredient` -- DROP TABLE IF EXISTS `Ingredient`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `Ingredient` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `Ingredient` -- LOCK TABLES `Ingredient` WRITE; /*!40000 ALTER TABLE `Ingredient` DISABLE KEYS */; INSERT INTO `Ingredient` VALUES (1,'mel'),(2,'mælk'),(3,'æg'),(4,'salt'); /*!40000 ALTER TABLE `Ingredient` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `Recipe` -- DROP TABLE IF EXISTS `Recipe`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `Recipe` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, `description` varchar(45) DEFAULT NULL, `todo` varchar(200) DEFAULT NULL, `cookingtime` int(11) DEFAULT NULL, `image` varchar(45) DEFAULT NULL, `User_id` int(11) NOT NULL, PRIMARY KEY (`id`,`User_id`), KEY `fk_Recipe_User1_idx` (`User_id`), CONSTRAINT `fk_Recipe_User1` FOREIGN KEY (`User_id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `Recipe` -- LOCK TABLES `Recipe` WRITE; /*!40000 ALTER TABLE `Recipe` DISABLE KEYS */; INSERT INTO `Recipe` VALUES (1,'pandekager','lækre sprøde pandekager','bland alle ingredienser sammen i en skål og rør melet ud. Varm en pande med smør og steg pandekagerne ved mellemhøj varme',20,'pandekager.jpg',1),(2,'snobrød','letbrændt snobrød over bål','bland alle ingredienserne sammen og ælt dejen grundigt i en time',90,'snobread.jpg',1),(3,'Naan brød','Indisk brød bagt på pande','Bland ingredienserne sammen og ælt dejen grundigt. Rul små kugler af dejen. Rul kuglerne til flade brød og steg dem på panden',20,'naan.jpg',1); /*!40000 ALTER TABLE `Recipe` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `Recipe_has_Ingredient` -- DROP TABLE IF EXISTS `Recipe_has_Ingredient`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `Recipe_has_Ingredient` ( `Recipe_id` int(11) NOT NULL, `Ingredient_id` int(11) NOT NULL, `amount` varchar(45) DEFAULT NULL, `measure` varchar(45) DEFAULT NULL, PRIMARY KEY (`Recipe_id`,`Ingredient_id`), KEY `fk_Recipe_has_Ingredient_Ingredient1_idx` (`Ingredient_id`), KEY `fk_Recipe_has_Ingredient_Recipe_idx` (`Recipe_id`), CONSTRAINT `fk_Recipe_has_Ingredient_Ingredient1` FOREIGN KEY (`Ingredient_id`) REFERENCES `Ingredient` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_Recipe_has_Ingredient_Recipe` FOREIGN KEY (`Recipe_id`) REFERENCES `Recipe` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `Recipe_has_Ingredient` -- LOCK TABLES `Recipe_has_Ingredient` WRITE; /*!40000 ALTER TABLE `Recipe_has_Ingredient` DISABLE KEYS */; INSERT INTO `Recipe_has_Ingredient` VALUES (1,1,'500','gram'),(1,2,'500','ml'),(1,3,'2','stk.'),(1,4,'1','knivsspids'),(2,1,'500','gram'),(2,2,'200','ml'),(2,4,'1','tskf'),(3,1,'500','ml'),(3,2,'200','ml'),(3,4,'1','tskf'); /*!40000 ALTER TABLE `Recipe_has_Ingredient` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `User` -- DROP TABLE IF EXISTS `User`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `User` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(45) DEFAULT NULL, `password` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `User` -- LOCK TABLES `User` WRITE; /*!40000 ALTER TABLE `User` DISABLE KEYS */; INSERT INTO `User` VALUES (1,'demouser','<PASSWORD>'),(2,'adminuser','<PASSWORD>'); /*!40000 ALTER TABLE `User` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-09-22 12:16:19 <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 dk.webtrade.recipesolution.data; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * * @author thomas */ public class DBConnector { static final String DRIVER = "com.mysql.jdbc.Driver"; static final String URL = "jdbc:mysql://localhost/recipesDB"; static final String USERNAME = "root"; static final String PASSWORD = "<PASSWORD>"; public static Connection getConnection(){ Connection conn = null; try{ Class.forName(DRIVER); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); } catch(SQLException | ClassNotFoundException se){ se.printStackTrace(); } return conn; } public static void main(String[] args) { try { String sql = "SELECT id, username, password FROM DB.User"; Connection conn = DBConnector.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String username = rs.getString("username"); String password = rs.getString("password"); // User user = new User } } catch (SQLException ex) { System.out.println(ex.getMessage()); } } public static void close(Statement stmt, ResultSet rs, Connection conn){ try{ if(rs != null) rs.close(); stmt.close(); conn.close(); } catch(SQLException se){ se.printStackTrace(); } catch(Exception ex){ ex.printStackTrace(); } finally{ try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ se2.printStackTrace(); }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } } <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 dk.webtrade.recipesolution.logik.entity; /** * * @author thomas */ public class RecipeIngredient { Ingredient ingredient; String amount; String measure; public RecipeIngredient(Ingredient ingredient, String amount, String measure) { this.ingredient = ingredient; this.amount = amount; this.measure = measure; } public Ingredient getIngredient() { return ingredient; } public void setIngredient(Ingredient ingredient) { this.ingredient = ingredient; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getMeasure() { return measure; } public void setMeasure(String measure) { this.measure = measure; } } <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 dk.webtrade.threadex2sem; /** * * @author thomas */ import java.util.concurrent.Executors; public class Executor02 { public static void main( String[] args ) { java.util.concurrent.ExecutorService workingJack = Executors.newSingleThreadExecutor(); for ( int count = 0; count < 25; count++ ) { workingJack.submit( () -> { // Det er en rød opgave at forklare hvad denne fejl skyldes // Fjern udkommenteringen i næste linje // System.out.println( "Hello "+ count + " to us" ); } ); } workingJack.shutdown(); } }
09678d8981cc9cb80ab0882b62487d09e249b24d
[ "Java", "SQL" ]
5
Java
MartinMoller/solutions
4a7921284e8dfe57f2cbeb15d9060140c1d12b86
2e3b4103ba9af0edcab9ef2237363f409224004e
refs/heads/master
<repo_name>TUP-FRC-UTN/lciii-2W2-tareas-semanales-EzeZeta<file_sep>/Semana 3/Antiguedad Flota/src/antiguedad/flota/AntiguedadFlota.java package antiguedad.flota; import java.util.Scanner; import java.util.Calendar; public class AntiguedadFlota { public static void main(String[] args) { Scanner lector = new Scanner(System.in); Calendar fechaActual = Calendar.getInstance(); int anioFab; int antiguedad; int anioActual; int contAutos; int cantPocoUso; int contAutosMuyAnt; int cero; anioActual = fechaActual.get(Calendar.YEAR); contAutos=0; cantPocoUso=0; contAutosMuyAnt=0; //antiguedad = 0; cero=0; System.out.println("Bienvenido al programa de clasificacion vehicular"); System.out.println("Recuerde que para salir debera ingresar 0 en Año de Fabricacion"); do { System.out.println("Ingrese el año de fabricacion: "); anioFab = lector.nextInt(); if (anioFab == 0) { cero = 0; } else { cero=1; antiguedad = anioActual - anioFab; if (antiguedad >= 0 && antiguedad <= 5){ System.out.println("Clasificacion: NUEVO"); contAutos ++; } else { if (antiguedad >= 5 && antiguedad <= 10){ System.out.println("Clasificacion: POCO USO"); contAutos++; cantPocoUso++; } else { if (antiguedad >=10 && antiguedad <= 20){ System.out.println("Clasificacion: MUCHO USO"); contAutos++; } else { if (antiguedad >= 20) { System.out.println("Clasificacion: MUY ANTIGUO"); contAutos++; contAutosMuyAnt++; } } } } } } while (cero !=0); System.out.println("La cantidad de total de autos es: "+ contAutos); System.out.println("La cantidad de autos con clasificacion POCO USO es: " + cantPocoUso); System.out.println("El promedio de antiguedad de los vehiculos (sin incluir MUY ANTIGUOS) es: %" + (contAutos-contAutosMuyAnt)*100/contAutos); } } <file_sep>/Semana 3/Persona mas alta/src/persona/mas/alta/PersonaMasAlta.java package persona.mas.alta; import java.util.Scanner; public class PersonaMasAlta { public static void main(String[] args) { Scanner entrada = new Scanner(System.in); double altura; String nombreMasAlto; int bandera; int contador; String nombrePersona; double acu; entrada = new Scanner(System.in); altura = 0; bandera = 0; contador = 0; acu = 0; nombreMasAlto = ""; nombrePersona = ""; for (int i = 0; i < 2; i++) { System.out.println("Ingrese el nombre: "); nombrePersona = entrada.next(); //entrada.nextLine(); System.out.println("Ingrese altura: "); altura = entrada.nextInt(); if (bandera == 0) { nombreMasAlto = nombrePersona; acu = altura; bandera++; } else { if (acu < altura) { nombreMasAlto = nombrePersona; } } } System.out.println("El nombre de la persona mas alta es: " + nombreMasAlto); } }
109de4c41f363a897baa868f35fabb972840fc87
[ "Java" ]
2
Java
TUP-FRC-UTN/lciii-2W2-tareas-semanales-EzeZeta
120b221eb6dc42cbbd0afd121cceed51811aa3a8
d2ff3858f11c9a7af40132f44fe67501c4a9fda4
refs/heads/master
<repo_name>narendra1695/form-data-crud-REACT<file_sep>/src/Components/Form/Form.js import React, { Component } from 'react'; import './Form.css'; class Form extends Component { constructor(props) { super(props); this.state = { // variable to hold the data at index 0 of the array legend: 0, // variable for actual index of the array index: '', // array to hold all the details such as name, email, gender, message formData: [] } } componentDidMount() { this.refs.name.focus(); } // functionality that submit the form and displays the details to the user submitData = (e) => { e.preventDefault(); let formData = this.state.formData; let name = this.refs.name.value; let email = this.refs.email.value; let gender = this.refs.gender.value; let message = this.refs.message.value; // particularly for index 0 if (this.state.legend === 0) { let data = { name, email, gender, message } // add the data from the form to the formData array formData.push(data); } else { let index = this.state.index; formData[index].name = name; formData[index].email = email; formData[index].gender = gender; formData[index].message = message; } // updating the state based on the data entered by the user this.setState({ formData: formData }); this.refs.myForm.reset(); this.refs.name.focus(); } // functionality to remove the data from the listing removeData = (i) => { let formData = this.state.formData; formData.splice(i, 1); // updating the state after removing the data listing from the formData array this.setState({ formData: formData }); this.refs.myForm.reset(); this.refs.name.focus(); } // functionality for edititing the data, once added in the lisitng editData = (i) => { let data = this.state.formData[i]; this.refs.name.value = data.name; this.refs.email.value = data.email; this.refs.gender.value = data.gender; this.refs.message.value = data.message; // checking for the state index and updating the data for the same lisitng as added this.setState({ legend: 1, index: i }) this.refs.name.focus(); } render() { let formData = this.state.formData; return ( <div> <div className="container"> <form className="border p-4 mt-sm-5" ref="myForm"> <div className="row pr-sm-3"> <div className="col-12 col-sm-12 form-group"> <div className="row"> <label htmlFor="userName" className="col-12 col-sm-4 text-uppercase font-weight-bold pl-1 pl-sm-3">name</label> <input type="text" className="col-12 col-sm-8 form-control" placeholder="Enter name" ref="name" /> </div> </div> <div className="col-12 col-sm-12 form-group"> <div className="row"> <label htmlFor="userEmail" className="col-12 col-sm-4 text-uppercase font-weight-bold pl-1 pl-sm-3">email</label> <input type="email" className="col-12 col-sm-8 form-control" placeholder="Enter email" ref="email" /> </div> </div> <div className="col-12 col-sm-12 form-group"> <div className="row"> <label htmlFor="userGender" className="col-12 col-sm-4 text-uppercase font-weight-bold pl-1 pl-sm-3">gender</label> <select className="col-12 col-sm-8 custom-select" ref="gender"> <option>...</option> <option value="Male">Male</option> <option value="Female">Female</option> </select> </div> </div> <div className="col-12 col-sm-12 form-group"> <div className="row"> <label htmlFor="userMessage" className="col-12 col-sm-4 text-uppercase font-weight-bold pl-1 pl-sm-3">message</label> <textarea type="text" row="4" className="col-12 col-sm-8 form-control" placeholder="Enter message" ref="message" /> </div> </div> <div className="col-12 col-sm-12 pl-0 pl-sm-3 pr-0"> <button type="submit" className="btn btn-primary mt-3 w-100 text-uppercase font-weight-bold" onClick={(e) => this.submitData(e)}>submit</button> </div> </div> </form> <ul className="list-group list-group-flush mt-3"> <pre> {formData.map((data, i) => <li key={i} className="list-group-item mb-2"> {i + 1}. {data.name}, {data.email}, {data.gender}, {data.message} <div className="float-right"> <button onClick={() => this.editData(i)} className="btn btn-info text-uppercase font-weight-bold mr-3">edit</button> <button onClick={() => this.removeData(i)} className="btn btn-danger text-uppercase font-weight-bold">remove</button> </div> </li> )} </pre> </ul> </div> </div> ); } } export default Form; <file_sep>/src/Components/Header/Header.js import React from 'react'; //this component as the name suggests, represents the heading of the app const Header = props => { return ( <header> <div className="container-fluid pl-0 pr-0"> <h4 className="text-center text-white bg-primary py-5">Form Data App | <span className="text-uppercase font-weight-bold">react</span></h4> </div> </header> ); }; export default Header;
c2ac4fb0729fa29488165f4b63f0c2ec8ff0f1b2
[ "JavaScript" ]
2
JavaScript
narendra1695/form-data-crud-REACT
4361bdf1654d9158e3a8bb4dd470233fb4b58132
114cb2c34533b479b26a7f0f851bfb71bb181cee
refs/heads/master
<repo_name>jjyepez/platzi-memes<file_sep>/src/pages/ui/Menu.js import React from 'react' import MenuSVG from '../../img/menu.svg' import './menu.css' const Menu = props => ( <div className = 'Menu'> <button className = 'boton bSubir'>Subir un Meme</button> <button className = 'boton bLogin'>Login</button> <div className = 'bMenu' style = {{ backgroundImage: `url( ${MenuSVG} )` }} /> </div> ) export default Menu<file_sep>/src/pages/ui/Categorias.js import React from 'react' import './categorias.css' import Categoria from './Categoria.js' const Categorias = props => ( <div className = 'Categorias'> <h4>Búsquedas recientes ...</h4> <div className = 'scroller'> {props.categorias.map( (el, i) => ( <Categoria key = {i} categoria = {el} /> ))} </div> </div> ) export default Categorias<file_sep>/src/pages/ui/Logo.js import React from 'react' import './logo.css' import LogoSVG from '../../img/logo.svg' const Logo = props => ( <div className = 'Logo' style = {{ backgroundImage: `url( ${LogoSVG} )` }} /> ) export default Logo<file_sep>/src/pages/containers/App.js // --- React import React, { Component } from 'react' // --- recursos, data y otras fuentes // --- contenedores y UI import AppUI from '../ui/AppUI' class App extends Component { state = { categorias: [], memes: [], app: { version: 'beta 0.1' } } componentDidMount = event => { document.querySelector('head title').textContent = this.state.app.version const categorias = [ {nombre:'reacciones', color: '#128595'}, {nombre:'bailes', color: '#1c78bb'}, {nombre:'caras', color: '#3abd21'}, {nombre:'risas', color: '#e1c004'}, {nombre:'gestos raros', color: '#ee1f8c'}, {nombre:'misc', color: '#ea4d4d'}, ] const memes = [ {uri:'c1.gif',tags:'cvander,live'}, {uri:'c2.gif',tags:'cvander,live'}, {uri:'f1.gif',tags:'freddy,reacciones'}, {uri:'p1.gif',tags:'paula,bloopers'}, {uri:'l1.gif',tags:'leonidas,gestos'}, {uri:'f2.gif',tags:'freddy,reacciones'}, {uri:'f3.gif',tags:'freddy,reacciones'}, {uri:'c3.gif',tags:'cvander,live'}, {uri:'p2.gif',tags:'paula,bloopers'}, {uri:'w1.gif',tags:'winiberto,bloopers'}, {uri:'c1.gif',tags:'cvander,live'}, {uri:'c2.gif',tags:'cvander,live'}, {uri:'f1.gif',tags:'freddy,reacciones'}, {uri:'p1.gif',tags:'paula,bloopers'}, {uri:'l1.gif',tags:'leonidas,gestos'}, {uri:'f2.gif',tags:'freddy,reacciones'}, {uri:'f3.gif',tags:'freddy,reacciones'}, {uri:'c3.gif',tags:'cvander,live'}, {uri:'p2.gif',tags:'paula,bloopers'}, {uri:'w1.gif',tags:'winiberto,bloopers'}, ] this.setState({ memes, categorias }) } handleSetRef = element => { this.App = element } render() { return ( <AppUI memes = {this.state.memes} categorias = {this.state.categorias} handleSetRef = {this.handleSetRef} /> ) } } export default App <file_sep>/src/pages/ui/Contenido.js import React from 'react' import './contenido.css' import Meme from './Meme' const Contenido = props => ( <div> <h4>Tendencias ...</h4> <div className = 'Contenido'> {props.memes.map( (el, i) => ( <Meme key = {i} meme = {el} /> ))} </div> </div> ) export default Contenido<file_sep>/src/pages/ui/Meme.js import React from 'react' import './meme.css' const Meme = props => { const memeDir = 'src/img/memes/' return ( <div className = 'Meme'> <img className = 'memeGIF' width = '100%' src = { memeDir + props.meme.uri} /> </div> ) } export default Meme<file_sep>/src/pages/ui/Buscador.js import React from 'react' import './buscador.css' import LupaSVG from '../../img/buscar.svg' const Buscador = props => ( <div className = 'Buscador'> <input type='search' className = 'qInput' placeholder = 'Buscar memes'/> <button className = 'bBuscar' style = {{ backgroundImage: `url( ${LupaSVG} )` }} /> </div> ) export default Buscador
8d7b07b06ba6a95f407af327e5fab5d23c7dbc2b
[ "JavaScript" ]
7
JavaScript
jjyepez/platzi-memes
1002731b2138e6833a14a110cc1febd3dddd47df
c8c35bc0fbf72e376f45439a052ac3b0a7696773
refs/heads/master
<repo_name>sylwiapytko/Microservices<file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/conferenceroombooing/ValidationService.java package com.bestgroup.conferenceroomservice.conferenceroombooing; import com.bestgroup.conferenceroomservice.ConferenceRoom; import com.bestgroup.conferenceroomservice.ConferenceRoomRepository; import com.bestgroup.conferenceroomservice.ResourceNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class ValidationService { private RoomBookingRepository roomBookingRepository; private ConferenceRoomRepository conferenceRoomRepository; @Autowired public ValidationService(RoomBookingRepository roomBookingRepository, ConferenceRoomRepository conferenceRoomRepository) { this.roomBookingRepository = roomBookingRepository; this.conferenceRoomRepository = conferenceRoomRepository; } public boolean isRoomExist(Integer roomId){ Optional<ConferenceRoom> roomBookings = conferenceRoomRepository.findById(roomId); if(roomBookings.isPresent()){ return true; } else throw new ResourceNotFoundException("No such room."); } public boolean isDurationValid(RoomBooking roomBooking){ if(roomBooking.getStartDateTime().compareTo(roomBooking.getEndDateTime()) < 0){ return true; } else throw new BadRequestExeption("End date before start date"); } public boolean isRoomAvailable(Integer roomId, RoomBooking newRoomBooking){ Optional<ConferenceRoom> conferenceRoom = conferenceRoomRepository.findById(roomId); if(conferenceRoom.isPresent()){ List<RoomBooking> roomBookings = conferenceRoom.get().getRoomBookings(); for(RoomBooking roomBooked: roomBookings){ if(( roomBooked.getStartDateTime().compareTo(newRoomBooking.getStartDateTime()) <= 0 && roomBooked.getEndDateTime().compareTo(newRoomBooking.getStartDateTime()) >= 0) || (roomBooked.getStartDateTime().compareTo(newRoomBooking.getEndDateTime()) <= 0 && roomBooked.getEndDateTime().compareTo(newRoomBooking.getEndDateTime()) >= 0) || (roomBooked.getStartDateTime().compareTo(newRoomBooking.getStartDateTime()) >= 0 && roomBooked.getEndDateTime().compareTo(newRoomBooking.getEndDateTime()) <= 0) || (roomBooked.getStartDateTime().compareTo(newRoomBooking.getStartDateTime()) <= 0 && roomBooked.getEndDateTime().compareTo(newRoomBooking.getEndDateTime()) >= 0)|| (roomBooked.getStartDateTime().compareTo(newRoomBooking.getStartDateTime()) == 0 && roomBooked.getEndDateTime().compareTo(newRoomBooking.getEndDateTime()) == 0)){ throw new BadRequestExeption("This room is occupied at this time"); } } } return true; } } <file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/responseentitystructure/UserBooking.java package com.bestgroup.conferenceroomservice.responseentitystructure; import lombok.Data; @Data public class UserBooking { private int bookingId; private User userId; } <file_sep>/user-service/src/main/resources/data.sql insert into tuser values(8, 'John', 'Doe') insert into tuser values(9, 'Caroline', 'Smith') insert into tuser values(10, 'Robert', 'Apple') insert into tuserbooking values(5,10)<file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/OtherServiceNotRespondingException.java package com.bestgroup.conferenceroomservice; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_GATEWAY) public class OtherServiceNotRespondingException extends RuntimeException { public OtherServiceNotRespondingException(String s) { super(s); } }<file_sep>/user-service/src/test/java/com/bestgroup/userservice/ValidationTest.java package com.bestgroup.userservice; import com.bestgroup.userservice.entities.User; import com.bestgroup.userservice.entities.UserBooking; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(MockitoExtension.class) class ValidationTest { private static Validator validator; private static ValidatorFactory validatorFactory; @BeforeAll public static void init() { validatorFactory = Validation.buildDefaultValidatorFactory(); validator = validatorFactory.getValidator(); } @AfterAll public static void close() { validatorFactory.close(); } @Test public void validUser() { User validUser = new User("John", "Doe"); Set<ConstraintViolation<User>> violations = validator.validate(validUser); assertTrue(violations.isEmpty()); } @Test public void invalidUserShortFirstName() { User inValidUser = new User("J", "Doe"); Set<ConstraintViolation<User>> violations = validator.validate(inValidUser); assertEquals(1, violations.size()); ConstraintViolation<User> violation = violations.iterator().next(); assertEquals("size must be between 2 and 30", violation.getMessage()); } @Test public void invalidUserShortLastName() { User inValidUser = new User("John", "D"); Set<ConstraintViolation<User>> violations = validator.validate(inValidUser); assertEquals(1, violations.size()); ConstraintViolation<User> violation = violations.iterator().next(); assertEquals("size must be between 2 and 30", violation.getMessage()); } @Test public void invalidUserLongFirstName() { User inValidUser = new User("Jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj", "Doe"); Set<ConstraintViolation<User>> violations = validator.validate(inValidUser); assertEquals(1, violations.size()); ConstraintViolation<User> violation = violations.iterator().next(); assertEquals("size must be between 2 and 30", violation.getMessage()); } @Test public void invalidUserLongLastName() { User inValidUser = new User("John", "Ddddddddddddddddddddddddddddddd"); Set<ConstraintViolation<User>> violations = validator.validate(inValidUser); assertEquals(1, violations.size()); ConstraintViolation<User> violation = violations.iterator().next(); assertEquals("size must be between 2 and 30", violation.getMessage()); } @Test public void invalidUserNullNames() { User inValidUser = new User(); Set<ConstraintViolation<User>> violations = validator.validate(inValidUser); assertEquals(2, violations.size()); ConstraintViolation<User> violation = violations.iterator().next(); assertEquals("must not be null", violation.getMessage()); violation = violations.iterator().next(); assertEquals("must not be null", violation.getMessage()); } @Test public void validUserBooking() { UserBooking validUserBooking = new UserBooking(4, new User("John", "Doe")); Set<ConstraintViolation<UserBooking>> violations = validator.validate(validUserBooking); assertTrue(violations.isEmpty()); } @Test public void invalidUserBookingBookingIdNotPositive() { UserBooking validUserBooking = new UserBooking(-1, new User("John", "Doe")); Set<ConstraintViolation<UserBooking>> violations = validator.validate(validUserBooking); assertEquals(1, violations.size()); ConstraintViolation<UserBooking> violation = violations.iterator().next(); assertEquals("must be greater than 0", violation.getMessage()); } @Test public void invalidUserBookingUserNull() { UserBooking validUserBooking = new UserBooking(4, null); Set<ConstraintViolation<UserBooking>> violations = validator.validate(validUserBooking); assertEquals(1, violations.size()); ConstraintViolation<UserBooking> violation = violations.iterator().next(); assertEquals("must not be null", violation.getMessage()); } } <file_sep>/conference-room-service/src/main/resources/data.sql insert into conferenceRooms (roomId,floor,name,size) values(1, 23, 'Bolek',15) insert into conferenceRooms (roomId,floor,name,size) values(2, 20, 'Warszawa', 20) insert into conferenceRooms (roomId,floor,name,size) values(3, 21, 'Syrena', 25)<file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/conferenceroombooing/RoomBookingController.java package com.bestgroup.conferenceroomservice.conferenceroombooing; import com.bestgroup.conferenceroomservice.responseentitystructure.RoomBookingInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController public class RoomBookingController { private RoomBookingService roomBookingService; @Autowired public RoomBookingController(RoomBookingService roomBookingService) { this.roomBookingService = roomBookingService; } @PostMapping("/conference-rooms/{roomId}/bookings") public ResponseEntity<RoomBookingInfo> createRoomBooking(@PathVariable Integer roomId, @RequestParam Integer userId, @Valid @RequestBody RoomBooking roomBooking) { RoomBookingInfo roomBookingInfo = roomBookingService.createRoomBooking(roomId, userId, roomBooking); return new ResponseEntity<RoomBookingInfo>(roomBookingInfo, HttpStatus.CREATED); } @GetMapping("/conference-rooms/{roomId}/bookings") public List<RoomBookingInfo> getRoomBookings(@PathVariable int roomId) { return roomBookingService.getRoomBookingsInfo(roomId); } @GetMapping("conference-rooms/bookings/") public List<RoomBooking> getBookings(@RequestParam List<Integer> bookings){ List<RoomBooking> roomBookings = roomBookingService.getBookingsInfo(bookings); return roomBookings; } } <file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/responseentitystructure/RoomBookingInfo.java package com.bestgroup.conferenceroomservice.responseentitystructure; import com.bestgroup.conferenceroomservice.conferenceroombooing.RoomBooking; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class RoomBookingInfo { private RoomBooking roomBooking; private User userInfo; } <file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/conferenceroombooing/RoomBookingService.java package com.bestgroup.conferenceroomservice.conferenceroombooing; import com.bestgroup.conferenceroomservice.*; import com.bestgroup.conferenceroomservice.responseentitystructure.RoomBookingInfo; import com.bestgroup.conferenceroomservice.responseentitystructure.User; import com.bestgroup.conferenceroomservice.responseentitystructure.UserBooking; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; @Service public class RoomBookingService { private RoomBookingRepository roomBookingRepository; private ConferenceRoomRepository conferenceRoomRepository; private ValidationService validationService; private RestTemplate restTemplate; private HealthCheck healthCheck; @Autowired public RoomBookingService(RoomBookingRepository roomBookingRepository, ConferenceRoomRepository conferenceRoomRepository, ValidationService validationService, RestTemplate restTemplate, HealthCheck healthCheck) { this.roomBookingRepository = roomBookingRepository; this.conferenceRoomRepository = conferenceRoomRepository; this.validationService = validationService; this.restTemplate = restTemplate; this.healthCheck = healthCheck; } public RoomBookingInfo createRoomBooking(Integer roomId, Integer userId, RoomBooking roomBooking) { validateRoomBookingParameters(roomId, roomBooking); saveRoomBooking(roomBooking); saveRoomBookingtoConferenceRoom(roomId, roomBooking); System.out.println(conferenceRoomRepository.findAll()); System.out.println(roomBookingRepository.findAll()); UserBooking userBooking = saveRoomBookingtoUser(userId, roomBooking); return new RoomBookingInfo(roomBooking, userBooking.getUserId()); } public boolean validateRoomBookingParameters(Integer roomId, RoomBooking roomBooking){ validationService.isRoomExist(roomId); validationService.isDurationValid(roomBooking); validationService.isRoomAvailable(roomId, roomBooking); return true; } public RoomBooking saveRoomBooking(RoomBooking roomBooking) { return roomBookingRepository.save(roomBooking); } public ConferenceRoom saveRoomBookingtoConferenceRoom(Integer roomId, RoomBooking roomBooking) { validationService.isRoomExist(roomId);// make sure room exists, when saving a room to repo made at beginning so no booking was saved when no room Optional<ConferenceRoom> conferenceRoom = conferenceRoomRepository.findById(roomId); conferenceRoom.get().getRoomBookings().add(roomBooking);//add room booking to collection in conference room roomBooking.setConferenceRoom(conferenceRoom.get()); conferenceRoomRepository.save(conferenceRoom.get()); return conferenceRoom.get(); } private UserBooking saveRoomBookingtoUser(Integer userId, RoomBooking roomBooking) { if(healthCheck.isStatusUp()) { HttpEntity entity = this.createTokenHeader(); int bookingID = roomBooking.getRoomBookingId(); String uri = new String("http://localhost:8090/users/" + userId + "/bookings?bookingID=" + bookingID); try { ResponseEntity<UserBooking> userBookingResponseEntity = restTemplate.exchange(uri, HttpMethod.POST, entity, UserBooking.class); return userBookingResponseEntity.getBody(); }catch (Exception e) { //if 404 : cant save to user then delete room booking deleteRoomBooking(roomBooking); throw new ResourceNotFoundException("Cant save to user"); } }else throw new OtherServiceNotRespondingException("http://localhost:8090/users/ Bad Response"); } public void deleteRoomBooking(RoomBooking roomBooking) { //first delete roomBooking form conferenceRoom collection deleteRoomBookingfromConferenceRoom(roomBooking); roomBookingRepository.delete(roomBooking); } public void deleteRoomBookingfromConferenceRoom(RoomBooking roomBooking) { Optional<ConferenceRoom> conferenceRoom = conferenceRoomRepository.findById(roomBooking.getConferenceRoom().getRoomId()); conferenceRoom.orElseThrow( () -> new ResourceNotFoundException("No such room.")); conferenceRoom.get().getRoomBookings().remove(roomBooking); } //get info about bookings for a room by room id public List<RoomBookingInfo> getRoomBookingsInfo(int roomId) { Optional<ConferenceRoom> conferenceRoom = conferenceRoomRepository.findById(roomId); conferenceRoom.orElseThrow( () -> new ResourceNotFoundException("No such room.")); List<RoomBooking> roomBookings = conferenceRoom.get().getRoomBookings(); List<UserBooking> userBookings = getUserInfo(roomBookings); List<RoomBookingInfo> roomBookingInfos = retrieveRoomBookingsInfo(roomBookings, userBookings); return roomBookingInfos; } // call User Microservice to get Info about Users who have those Bookings private List<UserBooking> getUserInfo(List<RoomBooking> roomBookings) { if(healthCheck.isStatusUp()) { List<Integer> bookingsIds = retrieveRoomBookingsIds(roomBookings); String uri = createUriCall(bookingsIds); HttpEntity entity = this.createTokenHeader(); ResponseEntity<UserBooking[]> userBookingResponseEntity = restTemplate.exchange(uri, HttpMethod.GET, entity, UserBooking[].class); List<UserBooking> userBookings = Arrays.asList(userBookingResponseEntity.getBody()); return userBookings; } else throw new OtherServiceNotRespondingException("http://localhost:8090/users/bookings/ Bad Response"); } public List<Integer> retrieveRoomBookingsIds(List<RoomBooking> roomBookings) { List<Integer> bookingsIds = new ArrayList<>();// list of bookings Ids roomBookings.forEach(roomBooking -> bookingsIds.add(roomBooking.getRoomBookingId())); return bookingsIds; } private String createUriCall(List<Integer> bookingsIds) { String uri = new String("http://localhost:8090/users/bookings/"); UriComponentsBuilder builder = UriComponentsBuilder .fromUriString(uri) .queryParam("bookings", bookingsIds); return builder.toUriString(); } //retrieve info from room bookings and user bookings and connect them into room bookings info public List<RoomBookingInfo> retrieveRoomBookingsInfo(List<RoomBooking> roomBookings, List<UserBooking> userBookings) { List<RoomBookingInfo> roomBookingInfos = new ArrayList<>(); for(RoomBooking roomBooking: roomBookings){ RoomBookingInfo roomBookingInfo = new RoomBookingInfo(); roomBookingInfo.setRoomBooking(roomBooking); roomBookingInfo.setUserInfo(findUserbyBookingId(roomBooking.getRoomBookingId(), userBookings)); //careful: User can be null! roomBookingInfos.add(roomBookingInfo); } return roomBookingInfos; } //Connect booking id with user id public User findUserbyBookingId(int roomBookingId, List<UserBooking> userBookings) { for(UserBooking userBooking: userBookings){ if (userBooking.getBookingId()== roomBookingId) return userBooking.getUserId(); } return null; } //get info about bookings by their booings ids public List<RoomBooking> getBookingsInfo(List<Integer> bookings) { List<RoomBooking> roomBookings = roomBookingRepository.findAllById(bookings); return roomBookings; } private String getTokenFromRequest(){ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .currentRequestAttributes()) .getRequest(); String value = request.getHeader("Authorization").split(" ")[1]; return value; } private HttpEntity createTokenHeader(){ String token = this.getTokenFromRequest(); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + token); return new HttpEntity(headers); } } <file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/ConferenceRoomService.java package com.bestgroup.conferenceroomservice; import org.springframework.stereotype.Service; import java.util.List; @Service public class ConferenceRoomService { private final ConferenceRoomRepository conferenceRoomRepository; public ConferenceRoomService(ConferenceRoomRepository conferenceRoomRepository) { this.conferenceRoomRepository = conferenceRoomRepository; } public ConferenceRoom createConferenceRoom(ConferenceRoom room) { return conferenceRoomRepository.save(room); } public List<ConferenceRoom> getAllRooms() { return conferenceRoomRepository.findAll(); } public ConferenceRoom getRoomById(Integer roomId) { return conferenceRoomRepository.findById(roomId).orElseThrow( () -> new ResourceNotFoundException("No such room.")); } public void deleteRoomById(Integer roomId) { ConferenceRoom conferenceRoom = conferenceRoomRepository.findById(roomId).orElseThrow( () -> new ResourceNotFoundException("No such room.")); if(conferenceRoom != null) conferenceRoomRepository.deleteById(roomId); } public ConferenceRoom update(Integer roomId, ConferenceRoom room) { ConferenceRoom roomEntityUpdated = conferenceRoomRepository.findById(roomId).orElseThrow(()->new ResourceNotFoundException("No such room.")); roomEntityUpdated.setFloor(room.getFloor()); roomEntityUpdated.setName(room.getName()); roomEntityUpdated.setSize(room.getSize()); return conferenceRoomRepository.save(roomEntityUpdated); } } <file_sep>/user-service/src/main/java/com/bestgroup/userservice/entities/LocalUser.java package com.bestgroup.userservice.entities; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.*; import javax.persistence.Entity; import javax.persistence.Id; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity @AllArgsConstructor @NoArgsConstructor @Data @EqualsAndHashCode(of = "login") @ToString @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class LocalUser { @Id @NotNull @Size(min=2, max=30) private String login; @NotNull private String password; } <file_sep>/conference-room-service/src/main/resources/application.properties management.endpoints.web.exposure.exclude=info management.endpoints.web.base-path=/ management.endpoints.web.path-mapping.health=health spring.h2.console.enabled=true spring.application.name=user-service server.port=8070 spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.security.user.name=admin spring.security.user.password=<PASSWORD><file_sep>/user-service/src/main/java/com/bestgroup/userservice/UserService.java package com.bestgroup.userservice; import com.bestgroup.userservice.Exceptions.OtherServiceNotRespondingException; import com.bestgroup.userservice.Exceptions.UserNotFoundException; import com.bestgroup.userservice.entities.User; import com.bestgroup.userservice.entities.UserBooking; import com.bestgroup.userservice.repository.UserBookingRepository; import com.bestgroup.userservice.repository.UserRepository; import com.bestgroup.userservice.responseentitystructure.RoomBooking; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; @Service public class UserService { private final UserRepository userRepository; private final UserBookingRepository bookingRepository; private RestTemplate restTemplate; @Autowired private HealthCheck healthCheck; @Autowired public UserService(UserRepository userRepository, UserBookingRepository bookingRepository, RestTemplate restTemplate) { this.userRepository = userRepository; this.bookingRepository = bookingRepository; this.restTemplate = restTemplate; } public List<User> retrieveAllUsers() { return userRepository.findAll(); } public ResponseEntity<Object> newUser(User user) { User savedUser = userRepository.save(user); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getUserId()).toUri(); return ResponseEntity.created(location).build(); } public User retrieveUser(int id) { Optional<User> userWrappedInOptional = userRepository.findById(id); userWrappedInOptional.orElseThrow(() -> new UserNotFoundException("id: " + id)); return userWrappedInOptional.get(); } public boolean removeUser(int id) { Optional<User> optionalUser = userRepository.findById(id); if(!optionalUser.isPresent()) { return false; } userRepository.deleteById(id); return true; } public User updateUser(int id, User updatedUser) { Optional<User> userAfterChange = userRepository.findById(id) .map(user -> { user.setFirstName(updatedUser.getFirstName()); user.setLastName((updatedUser.getLastName())); userRepository.save(user); return user; }); if(!userAfterChange.isPresent()) { throw new UserNotFoundException("id: " + id); } return userAfterChange.get(); } public List<RoomBooking> retrieveUserBookings(int userId) { if(healthCheck.isStatusUp()) { Optional<User> user = userRepository.findById(userId); if (!user.isPresent()) throw new UserNotFoundException("id: " + userId);//check if user Exists List<UserBooking> userBookings = user.get().getBookings(); List<RoomBooking> roomBookings = retrieveRoomBookings(userBookings); //delete those UserBookings that were lost in Room Microservice deleteLostUserBookings(userBookings, roomBookings); return roomBookings; // may be empty, if bookingId not found then not shown } else throw new OtherServiceNotRespondingException("http://localhost:8070/conference-rooms/booking/ Bad Response"); } //retrieve room bookings form Room Microservice private List<RoomBooking> retrieveRoomBookings(List<UserBooking> userBookings) { List<Integer> bookingsIds = retrieveUserBookingsIds(userBookings); String uri = createUriCall(bookingsIds); HttpEntity entity = this.createTokenHeader(); ResponseEntity<RoomBooking[]> userBookingsArray; userBookingsArray = restTemplate.exchange(uri, HttpMethod.GET, entity, RoomBooking[].class); List<RoomBooking> roomBookings = Arrays.asList(userBookingsArray.getBody()); return roomBookings; } private List<Integer> retrieveUserBookingsIds(List<UserBooking> userBookings) { List<Integer> bookingsIds = new ArrayList<>();// list of bookings Ids userBookings.forEach(userBooking -> bookingsIds.add(userBooking.getBookingId())); return bookingsIds; } private String createUriCall(List<Integer> bookingsIds) { String uri = new String("http://localhost:8070/conference-rooms/bookings/"); UriComponentsBuilder builder = UriComponentsBuilder .fromUriString(uri) .queryParam("bookings", bookingsIds); return builder.toUriString(); } //delete those userBookings that their id can not be found in roomBookings private List<UserBooking> deleteLostUserBookings(List<UserBooking> userBookings, List<RoomBooking> roomBookings) { List<UserBooking> lostUserBookings = findLostUserBookings(userBookings, roomBookings); userBookings.removeAll(lostUserBookings); //remove lost bookings from collection in user bookingRepository.deleteAll(lostUserBookings); //remove lost bookings from repository return userBookings; } //find those userBookings that their id can not be found in roomBookings private List<UserBooking> findLostUserBookings(List<UserBooking> userBookings, List<RoomBooking> roomBookings) { List<UserBooking> lostUserBookings = new ArrayList<>(); for(UserBooking userBooking: userBookings ){ Boolean bookingIdIsLost = checkIfLostUserBooking(userBooking, roomBookings); if(bookingIdIsLost){ lostUserBookings.add(userBooking); //add userBooking that wasnt fount in roomBookings to lostUserBookings } } return lostUserBookings; } //check if userBooking is present in roomBookings if not then its lost private Boolean checkIfLostUserBooking(UserBooking userBooking, List<RoomBooking> roomBookings) { Boolean bookingIdIsLost = true; for(RoomBooking roomBooking: roomBookings){ if(roomBooking.getRoomBookingId()==userBooking.getBookingId()) { bookingIdIsLost = false; //userBooking found in roomBooking break; } } return bookingIdIsLost; } public UserBooking addUserBooking(int userId, int bookingId ){ Optional<User> optionalUser = userRepository.findById(userId); if(!optionalUser.isPresent()) { throw new UserNotFoundException("id: " + userId); } return bookingRepository.save(new UserBooking(bookingId,optionalUser.get())); } public List<UserBooking> getUserBookings(List<Integer> bookings) { return bookingRepository.findAllById(bookings); } private String getTokenFromRequest(){ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .currentRequestAttributes()) .getRequest(); String value = request.getHeader("Authorization").split(" ")[1]; return value; } private HttpEntity createTokenHeader(){ String token = this.getTokenFromRequest(); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + token); return new HttpEntity(headers); } } <file_sep>/user-service/src/main/java/com/bestgroup/userservice/responseentitystructure/ConferenceRoom.java package com.bestgroup.userservice.responseentitystructure; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ConferenceRoom { private int roomId; private Integer floor; private String name; private Integer size; public ConferenceRoom(int floor, String name, int size){ this.floor = floor; this.name = name; this.size = size; } @Override public String toString() { return "ConferenceRoom{" + "id=" + roomId + ", floor=" + floor + ", name='" + name + '\'' + ", size=" + size + '}'; } } <file_sep>/user-service/src/main/java/com/bestgroup/userservice/repository/UserRepository.java package com.bestgroup.userservice.repository; import com.bestgroup.userservice.entities.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Integer> { } <file_sep>/user-service/src/main/java/com/bestgroup/userservice/entities/User.java package com.bestgroup.userservice.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.*; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; @Entity @Table(name="tuser") @NoArgsConstructor @Getter @EqualsAndHashCode(of = "userId") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int userId; @NotNull @Setter @Size(min=2, max=30) private String firstName; @NotNull @Setter @Size(min=2, max=30) private String lastName; @JsonIgnore @OneToMany( fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userId", orphanRemoval = true) private List<UserBooking> bookings; public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return "User{" + "userId=" + userId + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", bookings=" + bookings + '}'; } } <file_sep>/conference-room-service/src/main/java/com/bestgroup/conferenceroomservice/conferenceroombooing/RoomBooking.java package com.bestgroup.conferenceroomservice.conferenceroombooing; import com.bestgroup.conferenceroomservice.ConferenceRoom; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.Future; import javax.validation.constraints.NotNull; import java.util.Date; @Entity @NoArgsConstructor @Getter public class RoomBooking { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int roomBookingId; @NotNull(message = "Field must not be empty.") @Future(message = "Date should be future") @Setter private Date startDateTime; @NotNull(message = "Field must not be empty.") @Future(message = "Date should be future") @Setter private Date endDateTime; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="roomId") @Setter private ConferenceRoom conferenceRoom; @Override public String toString() { return "RoomBooking{" + "id=" + roomBookingId + "startDateTime=" + startDateTime + "endDateTime=" + endDateTime + "ConferenceRoom{" + "id=" + conferenceRoom.getRoomId() + ", floor=" + conferenceRoom.getFloor() + ", name='" + conferenceRoom.getName() + '\'' + ", size=" + conferenceRoom.getSize() + "}}"; } } <file_sep>/user-service/src/main/resources/application.properties management.endpoints.web.exposure.exclude=info management.endpoints.web.base-path=/ management.endpoints.web.path-mapping.health=health spring.h2.console.enabled=true spring.application.name=user-service server.port=8090 spring.security.user.name=admin spring.security.user.password=<PASSWORD> <file_sep>/user-service/src/test/java/com/bestgroup/userservice/UserServiceTest.java package com.bestgroup.userservice; import com.bestgroup.userservice.Exceptions.UserNotFoundException; import com.bestgroup.userservice.entities.User; import com.bestgroup.userservice.entities.UserBooking; import com.bestgroup.userservice.repository.UserBookingRepository; import com.bestgroup.userservice.repository.UserRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class UserServiceTest { @InjectMocks private UserService userService; @Mock private UserRepository userRepository; @Mock private UserBookingRepository userBookingRepository; @Test void retrieveAllUsers() { List<User> userList = new ArrayList<>(); userList.add(new User("John", "Smith")); userList.add(new User("Terry", "Bogard")); when(userRepository.findAll()).thenReturn(userList); List<User> fetchedList = userService.retrieveAllUsers(); assertNotNull(fetchedList); assertEquals(2, fetchedList.size()); assertEquals("John", fetchedList.get(0).getFirstName()); assertEquals("Smith", fetchedList.get(0).getLastName()); assertEquals("Terry", fetchedList.get(1).getFirstName()); assertEquals("Bogard", fetchedList.get(1).getLastName()); } @Test void retrieveUser() { Optional<User> userOptional = Optional.of(new User("John", "Doe")); when(userRepository.findById(anyInt())).thenReturn(userOptional); User mockedUser = userService.retrieveUser(33); assertNotNull(mockedUser); assertEquals("John", mockedUser.getFirstName()); assertEquals("Doe", mockedUser.getLastName()); } @Test void retrieveUserThrowUserNotFoundException() { Optional<User> userOptional = Optional.ofNullable(null); when(userRepository.findById(anyInt())).thenReturn(userOptional); assertThrows(UserNotFoundException.class, () -> userService.retrieveUser(33)); } @Test void newUser() { MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockHttpServletRequest)); User user = new User("John", "Doe"); when(userRepository.save(any(User.class))).thenReturn(user); ResponseEntity<Object> responseEntity = userService.newUser(user); assertNotNull(responseEntity); assertEquals(201, responseEntity.getStatusCodeValue()); } @Test void removeUserIfUserDoesNotExists() { when(userRepository.findById(anyInt())).thenReturn(Optional.ofNullable(null)); assertFalse(userService.removeUser(54)); } @Test void removeUserIfUserExists() { when(userRepository.findById(anyInt())) .thenReturn(Optional.ofNullable(new User("John", "Doe"))); assertTrue(userService.removeUser(54)); } @Test void updateUser() { User user = new User("John", "Doe"); when(userRepository.findById(anyInt())).thenReturn(Optional.of(user)); User updatedUser = userService.updateUser(5, new User("Miranda", "Hook")); assertNotNull(updatedUser); assertEquals("Miranda", updatedUser.getFirstName()); assertEquals("Hook", updatedUser.getLastName()); } @Test void retrieveUserBookings() { // User user = new User("John", "Doe"); // when(userRepository.findById(anyInt())) // .thenReturn(Optional.of(user)); // // List<UserBooking> userBookingList = new ArrayList<>(); // userBookingList.add(new UserBooking(32, user)); // userBookingList.add(new UserBooking(53, user)); // // when(any(User.class).getBookings()).thenReturn(userBookingList); // // List<UserBooking> mockedList = userService.retrieveUserBookings(123); // // assertNotNull(mockedList); // assertEquals(2, mockedList.size()); // assertEquals(32, mockedList.get(0).getBookingId()); // assertEquals(54, mockedList.get(1).getBookingId()); } @Test void retrieveUserBookingsThrowUserNotFoundException() { when(userRepository.findById(anyInt())) .thenReturn(Optional.ofNullable(null)); assertThrows(UserNotFoundException.class, () -> userService.retrieveUserBookings(32)); } @Test void addUserBooking() { User user = new User("John", "Doe"); when(userRepository.findById(anyInt())) .thenReturn(Optional.ofNullable(user)); when(userBookingRepository.save(any(UserBooking.class))).thenReturn(new UserBooking(3, user)); UserBooking userBooking = userService.addUserBooking(94, 3); assertNotNull(userBooking); assertEquals(3, userBooking.getBookingId()); assertEquals(0, userBooking.getUserId().getUserId()); } @Test void addUserBookingThrowUserNotFoundException() { when(userRepository.findById(anyInt())) .thenReturn(Optional.ofNullable(null)); assertThrows(UserNotFoundException.class, () -> userService.addUserBooking(32, 8)); } @Test void getUserBookings() { List<UserBooking> userBookingsList = new ArrayList<>(); userBookingsList.add(new UserBooking(4, new User("John", "Doe"))); userBookingsList.add(new UserBooking(8, new User("Miranda", "Wall"))); when(userBookingRepository.findAllById(any(List.class))).thenReturn(userBookingsList); List<Integer> bookingList = new ArrayList<>(); List<UserBooking> mockedList = userService.getUserBookings(bookingList); assertNotNull(mockedList); assertEquals(2, mockedList.size()); assertEquals(4, mockedList.get(0).getBookingId()); assertEquals(8, mockedList.get(1).getBookingId()); } }<file_sep>/user-service/src/main/java/com/bestgroup/userservice/LoginController.java package com.bestgroup.userservice; import com.bestgroup.userservice.entities.LocalUser; import com.bestgroup.userservice.repository.LocalUserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @RestController() @RequestMapping(path = "/user", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) public class LoginController { private LocalUserRepository userRepository; private PasswordEncoder passwordEncoder; @Autowired public LoginController(LocalUserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } @PostMapping("/signup") @ResponseStatus(HttpStatus.CREATED) public LocalUser signup(@RequestBody LocalUser user) { user.setPassword(passwordEncoder.encode(user.getPassword())); return this.userRepository.save(user); } }
5e9ff3e8eded81e7f5cff9444d35e44a7f4f80ca
[ "Java", "SQL", "INI" ]
20
Java
sylwiapytko/Microservices
9581c4bab3c589564efc8bd015ab2f7ebc3b12ea
b94636d59e053cbd07198819c200f24d43f7c680
refs/heads/master
<file_sep>module.exports = function registration(pool) { async function regCheck(registration) { var check = await pool.query('select registration from regNumber where reg = $1', [registration]); return check; } async function plateNumber(x) { //const item = await pool.query(`select id from reg where plate = $1`[x]) const code = x.substring(0, 2) const theId = await pool.query(`select id from towns where registration = $1`, [code]) const id = theId.rows[0].id let checking if (id > 0) { checking = await pool.query(`select * from regnumber where reg = $1`, [x]) } else { return false } if (checking.rowCount === 0) { await pool.query(`insert into regnumber (reg, townsid) values ($1, $2)`, [x, id]) } } async function insertReg(reg) { var code = reg.substring(0,2) var theId= await pool.query(`select id from towns where registration = $1`,[code]) var id = theId.rows[0].id var insert = await pool.query('insert into regNumber(reg, townsid) values ($1, $2)', [reg, id]); return insert; } async function getReg() { var inserting = await pool.query(`select reg from regNumber`); return inserting.rows; } async function theReg(theRegistration) { var theRegistration = await regCheck(theReg); if (theRegistration.rowCount > 0) { await PaymentRequestUpdateEvent(theRegistration); } else { await insertReg(theRegistration); } } async function filter(code) { if (code == "all") { const filtering = await pool.query(`select reg from regNumber`) return filtering.rows } else { const theId = await pool.query(`select id from towns where registration = $1`, [code]) const id = theId.rows[0].id const place = await pool.query(`select * from regNumber where townsid = $1`, [id]) return place.rows } } async function reset() { await pool.query('delete from regNumber'); } return { insertReg, plateNumber, getReg, regCheck, theReg, reset, filter } } <file_sep>create table towns( id serial not null primary key, registration text not null, name_of_town text not null ); create table regNumber( id serial not null primary key, reg text not null, townsId int not null, foreign key (townsId) references towns(id) ); INSERT INTO towns (registration, name_of_town) VALUES ('CJ', 'Paarl'); INSERT INTO towns (registration, name_of_town) VALUES ('CK', 'Malmesbury'); INSERT INTO towns (registration, name_of_town) VALUES ('CA', 'Cape Town'); <file_sep>// const mongoose = require('mongoose'); // module.exports = function(mongoUrl) { // mongoose.connect(mongoUrl, function(err, results) { // if(err){ // console.log(err); // } // else{ // console.log("connected to database") // } // }); // var registrationNames = mongoose.model('registrationNames', { // name: String // }); // return { // registrationNames // } // }<file_sep>const express = require("express"); const exphbs = require("express-handlebars"); const bodyParser = require("body-parser"); const reg = require("./registration"); const flash = require("express-flash"); const session = require("express-session") const app = express(); const pg = require("pg"); const Pool = pg.Pool; const connectionString = process.env.DATABASE_URL || 'postgresql://yongama:pg123@localhost:5432/registration'; const pool = new Pool({ connectionString, }); const registration = reg(pool); app.engine('handlebars', exphbs({ defaultLayout: 'main', layoutsDir: 'views/layouts' })); app.set('view engine', 'handlebars'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) app.use(session({ secret: 'keyboard cat', resave: true, saveUninitialized: true })); app.use(flash()); app.use(express.static('public')); app.get("/", async function (req, res) { const plates = await registration.getReg() res.render('index', { plateNum: plates }) }); app.post('/reg_numbers', async function (req, res) { let plate = req.body.regInput if (plate === '') { req.flash('error', 'Enter a registration number') } else if (!(/C[AKJ]\s\d{3}-\d{3}$|C[AKJ]\s\d{3}$|C[AKJ]\s\d{3}\d{3}$/.test(plate))) { // else if (!(/C[AKJ] \d{3,6}$/.test(plate))) { req.flash('error', 'Enter a correct registration number') } else { await registration.plateNumber(plate) req.flash('success', 'You have entered a correct registration number') } const plates = await registration.getReg() res.render('index', { plateNum: plates }) }) app.get("/reg_numbers", async function (req, res) { var indiReg = await registration.getReg() console.log(indiReg) res.render("index", { regDisplay: indiReg }) }); app.post('/reg_number', async function (req, res) { let area = req.body.town if (area === '') { req.flash('error', 'please select a town') } else { const filtering = await registration.filter(area) res.render('index', { plateNum: filtering }) } }) app.get('/reset', async function (req, res) { await registration.reset() res.render('index', { }); }); const PORT = process.env.PORT || 3009; app.listen(PORT, function () { console.log("App started at port", PORT); })
6104cab9e43a8f82ade79c7c8286976727f2b056
[ "JavaScript", "SQL" ]
4
JavaScript
YongamaFayo/reg-webapp
bc38406d033b48a34381ff58d2a644905963350f
d1bbe2ac8bcb91f55455957967a0fa5d491d60d4
refs/heads/master
<file_sep>package com.skywave.callpeon import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import org.json.JSONException import org.json.JSONObject class MainActivity : AppCompatActivity() { var btnSend: Button? = null private val FCM_API = "https://fcm.googleapis.com/fcm/send" private val serverKey = "key=" + "<KEY>" private val contentType = "application/json" val TAG = "NOTIFICATION TAG" private var requestQueue: RequestQueue? = null var NOTIFICATION_TITLE: String? = null var NOTIFICATION_MESSAGE: String? = null var TOPIC: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) requestQueue = getRequestQueue() btnSend = findViewById(R.id.btnSend) // Company LoggedIn btnSend?.visibility = View.GONE btnSend?.setOnClickListener { sendNotification() } } private fun sendNotification() { TOPIC = "/topics/userABC" //topic must match with what the receiver subscribed to NOTIFICATION_TITLE = "Please" NOTIFICATION_MESSAGE = "Come In" val notification = JSONObject() val notifcationBody = JSONObject() try { notifcationBody.put("title", NOTIFICATION_TITLE) notifcationBody.put("message", NOTIFICATION_MESSAGE) notification.put("to", TOPIC) notification.put("data", notifcationBody) } catch (e: JSONException) { Log.e(TAG, "onCreate: " + e.message) } sendNotification1(notification) } private fun sendNotification1(notification: JSONObject) { val jsonObjectRequest: JsonObjectRequest = object : JsonObjectRequest(FCM_API, notification, Response.Listener<JSONObject?> { Log.i(TAG, "onResponse: $it") }, Response.ErrorListener { Toast.makeText(this@MainActivity, "Request error", Toast.LENGTH_LONG).show() Log.i(TAG, "onErrorResponse: Didn't work") }) { override fun getHeaders(): MutableMap<String, String> { val params: MutableMap<String, String> = HashMap() params["Authorization"] = serverKey params["Content-Type"] = contentType return params } } getRequestQueue()!!.add(jsonObjectRequest) } private fun getRequestQueue(): RequestQueue? { if (requestQueue == null) { requestQueue = Volley.newRequestQueue(applicationContext) } return requestQueue } }<file_sep>rootProject.name = "<NAME>" include ':app' <file_sep>package com.skywave.callpeon import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.graphics.Color import android.media.MediaPlayer import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import java.util.* class MyFirebaseMessagingService : FirebaseMessagingService() { private val ADMIN_CHANNEL_ID = "admin_channel" private val TAG = "MyFirebaseMessagingService" private val SUBSCRIBE_TO = "userABC" override fun onMessageReceived(remoteMessage: RemoteMessage) { val intent = Intent(this, MainActivity::class.java) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationID: Int = Random().nextInt(3000) Log.i(TAG, "remoteMessage============>>>>>>: ${remoteMessage.data}") /* Apps targeting SDK 26 or above (Android O) must implement notification channels and add its notifications to at least one of them. Therefore, confirm if version is Oreo or higher, then setup notification channel */if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { setupChannels(notificationManager) } intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_ONE_SHOT ) val largeIcon = BitmapFactory.decodeResource( resources, R.drawable.app_icon ) // val notificationSoundUri: Uri = // Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/" + R.raw.sound) // Settings.System.DEFAULT_RINGTONE_URI val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder(this, ADMIN_CHANNEL_ID) .setSmallIcon(R.drawable.app_icon) .setLargeIcon(largeIcon) .setContentTitle(remoteMessage.data["title"]) .setContentText(remoteMessage.data["message"]) .setAutoCancel(true) // .setSound(notificationSoundUri, AudioManager.STREAM_ALARM) .setContentIntent(pendingIntent) //Set notification color to match your app color template if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { notificationBuilder.color = resources.getColor(R.color.black) } notificationManager.notify(notificationID, notificationBuilder.build()) if (remoteMessage.data["title"]!!.isNotEmpty()) { var mediaPlayer: MediaPlayer? = MediaPlayer.create(this, R.raw.sound) if (!mediaPlayer?.isPlaying!!) { mediaPlayer?.start() } else { // mediaPlayer.stop() } } } @RequiresApi(api = Build.VERSION_CODES.O) private fun setupChannels(notificationManager: NotificationManager?) { val adminChannelName: CharSequence = "New notification" val adminChannelDescription = "Device to device notification" // val sound = // Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/raw/sound.mp3") // val attributes = AudioAttributes.Builder() // .setUsage(AudioAttributes.USAGE_NOTIFICATION) // .build() val adminChannel = NotificationChannel( ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH ) adminChannel.description = adminChannelDescription adminChannel.enableLights(true) adminChannel.lightColor = Color.RED adminChannel.enableVibration(true) // adminChannel.setSound(sound, attributes) notificationManager?.createNotificationChannel(adminChannel) } override fun onNewToken(p0: String) { // Once the token is generated, subscribe to topic with the userId FirebaseMessaging.getInstance().subscribeToTopic(SUBSCRIBE_TO) Log.i(TAG, "onTokenRefresh completed with token============>>>>>> : $p0") } }
83a95b368fa45bbeaaf6ac303ee9c864ea96caba
[ "Kotlin", "Gradle" ]
3
Kotlin
androidroadies/call-peon
bb75a8f0e2388d181d070936825b7291880c141e
4f66621a08a1edc6f7a05dbc32286704cac1c696
refs/heads/master
<file_sep>alembic==1.6.5 click==8.0.1 dominate==2.6.0 Flask==2.0.1 Flask-Bootstrap==3.3.7.1 Flask-Login==0.5.0 Flask-Migrate==2.5.2 Flask-Script==2.0.6 Flask-SQLAlchemy==2.4.1 Flask-WTF==0.15.1 greenlet==1.1.0 gunicorn==20.1.0 itsdangerous==2.0.1 Jinja2==3.0.1 Mako==1.1.4 MarkupSafe==2.0.1 psycopg2==2.8.4 python-dateutil==2.8.1 python-editor==1.0.4 six==1.16.0 SQLAlchemy==1.4.18 visitor==0.1.3 Werkzeug==2.0.1 WTForms==2.3.3 <file_sep>from flask_wtf import FlaskForm from wtforms import StringField, SelectField, TextAreaField, SubmitField,validators from wtforms.validators import Required class CreatePost(FlaskForm): name = StringField(u'Topic', [validators.required(), validators.length(max=200)]) comment = TextAreaField(u'Content', [validators.optional(), validators.length(max=200)]) submit = SubmitField('Post') <file_sep>import urllib.request,json from flask import config from .models import Post, Quote QUOTES_URL = 'http://quotes.stormconsultancy.co.uk/random.json' base_url = QUOTES_URL def get_quotes(): ''' Function that gets responce to request ''' with urllib.request.urlopen(base_url) as url: get_quotes_response = url.read() quote = json.loads(get_quotes_response) return quote #testing post def show_post(): title = "My blog" content = "this is my blog" all_post = [] new_post = Post(title,content) new_post.save_post() return all_post<file_sep>from . import db from werkzeug.security import generate_password_hash,check_password_hash from flask_login import UserMixin from . import login_manager @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class Quote: ''' Defining quotes object ''' def __init__(self,author,quote,permalink): self.author = author self.quote = quote self.permalink = permalink # class User(UserMixin,db.Model): # __tablename__ = 'users' # id = db.Column(db.Integer,primary_key = True) # username = db.Column(db.String(255),index = True) # email = db.Column(db.String(255),unique = True,index = True) # role_id = db.Column(db.Integer,db.ForeignKey('roles.id')) # password_hash = db.Column(db.String(255)) # @property # def password(self): # raise AttributeError('You cannot read the password attribute') # @password.setter # def password(self, password): # self.pass_secure = generate_password_hash(password) # def verify_password(self,password): # return check_password_hash(self.pass_secure,password) # def __repr__(self): # return f'User {self.username}' # class Role(db.Model): # __tablename__ = 'roles' # id = db.Column(db.Integer,primary_key = True) # name = db.Column(db.String(255)) # users = db.relationship('User',backref = 'role',lazy="dynamic") # def __repr__(self): # return f'User {self.name}' class Post: ''' Defining quotes object ''' def __init__(self,title,content): self.topic = title self.content = content all_posts = [] def __init__(self,title,content): self.title = title self.content = content def save_post(self): Post.all_posts.append(self) @classmethod def clear_posts(cls): Post.all_posts.clear() @classmethod def get_posts(cls): response = [] for post in cls.all_posts: response.append(post) return response """Database models.""" from . import db from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash class User(UserMixin, db.Model): """User account model.""" __tablename__ = 'users' id = db.Column( db.Integer, primary_key=True ) name = db.Column( db.String(100), nullable=False, unique=False ) email = db.Column( db.String(40), unique=True, nullable=False ) password = db.Column( db.String(200), primary_key=False, unique=False, nullable=False ) website = db.Column( db.String(60), index=False, unique=False, nullable=True ) created_on = db.Column( db.DateTime, index=False, unique=False, nullable=True ) last_login = db.Column( db.DateTime, index=False, unique=False, nullable=True ) def set_password(self, password): """Create hashed password.""" self.password = generate_password_hash( password, method='sha256' ) def check_password(self, password): """Check hashed password.""" return check_password_hash(self.password, password) def __repr__(self): return '<User {}>'.format(self.username)<file_sep>from flask import Blueprint # Blueprint Configuration auth_bp = Blueprint( 'auth_bp', __name__, template_folder='templates', static_folder='static' ) from . import views<file_sep>from app.auth.forms import LoginForm from flask.helpers import url_for from werkzeug.utils import redirect from app.models import Post from . import main from flask import render_template,request,flash from .forms import CreatePost from ..logic import get_quotes,show_post from flask_login import login_required from ..auth import views from ..models import Quote, db from ..auth import views posts = Post quote = Quote @main.route('/') def index(): quote = get_quotes() show_posts = Post.get_posts return render_template('index.html',quote=quote, show_post = show_posts) @main.route('/create-post', methods = ['GET', 'POST']) @login_required def addpost(): login_form = views.login title = 'post' form = CreatePost() if request.method == 'POST': topic = form.topic.data content = form.content.data post = Post(topic,content) post.save_post() db.session.add(post) db.session.commit() flash('Post was successfully added') return redirect(url_for('index')) return render_template('post.html',form = form,title = title, login_form = login_form) <file_sep>{% extends 'base.html'%} {% block content %} <div class="container d-flex justify-content-center mt-5"> <div class="card" style="width: 50rem;"> <div class="card-body"> <div class="user-div"> <p class="font-style-italic">kazungu@post</p> </div> <h5 class="card-title">Creating flask app</h5> <hr> <p class="card-text"> from flask import Flask <br> app = Flask(__name__) <br> @app.route('/') <br> def hello():<br> return "Hello World!" <br> </p> </div> </div> </div> {% include 'comments.html'%} <hr> <div class="container d-flex justify-content-center"> <div class="card" style="width: 50rem;"> <div class="card-body"> <h5 class="card-title">Quote of the Day</h5> <hr> <h6 class="card-subtitle mb-2 text-muted">Author: {{quote.author}}</h6> <p class="card-text">Quote: {{quote.quote}}</p> <a href="{{quote.permalink}}" class="card-link">follow quote</a> </div> </div> </div> {% endblock %}<file_sep># My blog ## Description Application that allows users to upload their one minute pitch and others to comments on them ## Prerequisites ### Getting the project 1. Git hub account 2. Git installed in your machine ``` $ sudo apt-get install git-all ``` ### Setup To access this project on your local files, you can clone it using these steps 1. Open your terminal 1. Use this command to clone `$ git clone ``` $ git clone https://github.com/changawa-antony/personal-blog ``` This will clone the repositoty into your local folder ### Uses flask * Make sure you know how to use flask( Python framework) ### Technologies Used 1. HTML 2. CSS 3. Bootstrap 4. flask ### View live Site View [live]() *Get to explore* :rocket: ## Author <NAME> Am an upcoming software developer. My interest lies on webdevelopment. Favourite languages includes Html, Css and Javascript. Currently I have developed over 6 sites. ### Contacts :email: <EMAIL> Portfolio [Check](https://changawa-antony.github.io/my-portfolio/) ### Licence This project is under the [MIT](LICENSE) licence *Copyright (c) 2021 (Changawa-antony)*<file_sep># from flask_wtf import FlaskForm # from wtforms import StringField,PasswordField,SubmitField,BooleanField # from wtforms.validators import Required,Email,EqualTo # from ..models import User # from wtforms import ValidationError # class RegistrationForm(FlaskForm): # email = StringField('Your Email Address',validators=[Required(),Email()]) # username = StringField('Enter your username',validators = [Required()]) # password = PasswordField('<PASSWORD>',validators = [Required(), EqualTo('password_confirm',message = 'Passwords must match')]) # password_confirm = PasswordField('Confirm Passwords',validators = [Required()]) # submit = SubmitField('Sign Up') # class LoginForm(FlaskForm): # email = StringField('Your Email Address',validators=[Required(),Email()]) # password = PasswordField('<PASSWORD>',validators =[Required()]) # remember = BooleanField('Remember me') # submit = SubmitField('Sign In') # def validate_email(self,data_field): # if User.query.filter_by(email =data_field.data).first(): # raise ValidationError('There is an account with that email') # def validate_username(self,data_field): # if User.query.filter_by(username = data_field.data).first(): # raise ValidationError('That username is taken') """Sign-up & log-in forms.""" from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import ( DataRequired, Email, EqualTo, Length, Optional ) class SignupForm(FlaskForm): """User Sign-up Form.""" name = StringField( 'Name', validators=[DataRequired()] ) email = StringField( 'Email', validators=[ Length(min=6), Email(message='Enter a valid email.'), DataRequired() ] ) password = PasswordField( '<PASSWORD>', validators=[ DataRequired(), Length(min=6, message='Select a stronger password.') ] ) confirm = PasswordField( 'Confirm Your Password', validators=[ DataRequired(), EqualTo('password', message='Passwords must match.') ] ) submit = SubmitField('Register') class LoginForm(FlaskForm): """User Log-in Form.""" email = StringField( 'Email', validators=[ DataRequired(), Email(message='Enter a valid email.') ] ) password = PasswordField('<PASSWORD>', validators=[DataRequired()]) submit = SubmitField('Log In')
2f5981db2a5a3ef0969fb2f61953cfab6bfacde1
[ "Markdown", "Python", "Text", "HTML" ]
9
Text
changawa-antony/personal-blog
f3df93d6fca61d9ec5eb369d6420bf4b472aa8b3
d122c3b031dcb53258a68f22b7469c513626a876
refs/heads/main
<file_sep>from flask import * import random as rd import string as st special_characters = '!@#$%&*()-=+_.?' characters_lower = st.ascii_lowercase characters_upper = st.ascii_uppercase randomize = rd.SystemRandom() app = Flask(__name__) @app.route("/") def hello_world(): return "<h1>Hello World</h1>" @app.route("/getPass", methods=['POST', 'GET']) def get_pass(): # print(request.form["specialChars"]) password = gen_password(request.form) return password def gen_password(options): has_special_chars = options["specialChars"] has_capital_letters = options["capitalLetters"] has_numbers = options["numbers"] size = options["size"] structure = characters_lower if(has_special_chars == "true"): structure += special_characters if(has_capital_letters == "true"): structure += characters_upper if(has_numbers == "true"): structure += st.digits result = ''.join(randomize.choice(structure) for i in range(int(size))) return result<file_sep># ![Password Generator Banner](https://user-images.githubusercontent.com/57842220/125381780-e43a5a00-e36a-11eb-9143-3f52486fa93c.png) Password generator developed with Python 🔒
b91158ed3d10f98aa087d32b8e5b681d6d09c074
[ "Markdown", "Python" ]
2
Python
Arthur-Matias/password-generator
b6064ba39e56a69caf94029ac32a02c53ef4fefa
896b56f67ea7ea47374c8be40a6e8bb918f4e8bc
refs/heads/master
<repo_name>guxiansheng1991/yangkeduo-spider<file_sep>/app/controller/home.js 'use strict'; const Controller = require('egg').Controller; const Util = require('../common/util'); class HomeController extends Controller { /** * 拼多多相关接口 * 评论: http://apiv3.yangkeduo.com/reviews/6891352110/list?&size=20&page=1 * 热销商品列表: http://apiv3.yangkeduo.com/v5/goods?page=1&size=10 */ async index() { // 参数 const { ctx } = this; const query = ctx.request.query; const resData = { code: 0, msg: '', list: [], reqParams: '' }; if (!query.headers || !query.size || !query.sort || !query.q) { resData.code = 0; resData.msg = '缺少必要参数,请重试!'; resData.list = []; await ctx.render('home/alibaba.tpl', resData); } else { const util = new Util(); const searchUrl = `https://mobile.yangkeduo.com/proxy/api/search?pdduid=6722159943&is_back=1&item_ver=lzqq&source=search&search_met=history&track_data=refer_page_id,10031_1589427740027_ig2nuyna68%3Brefer_search_met_pos,1&list_id=PtEu4L7odq&sort=${query.sort}&filter=&q=${encodeURIComponent(query.q)}&page=1&size=${query.size}&flip=20%3B3%3B0%3B0%3B611052bc-e4b4-412f-b98e-16077537f105&anti_content=0aoAfxvdHOcYY9dMEaDCU94FZo1e4gmOkGJlDeM14qUK9bv7YCVdutvbuZpjHpjl6JSpveHi2<KEY>`; // const searchUrl = `https://mobile.yangkeduo.com/proxy/api/search?pdduid=6722159943&item_ver=lzqq&source=search&search_met=history&track_data=refer_page_id,10015_1589511142464_witajgdave%3Brefer_search_met_pos,4&list_id=OirB0OgvnQ&sort=default&filter=&q=%E6%B4%97%E8%A1%A3%E5%87%9D%E7%8F%A0&page=2&size=50&flip=20%3B5%3B0%3B0%3B06aff68f-d5b0-404d-874d-5411136c86da&anti_content=<KEY>`; console.log(searchUrl); try { let data = await util.httpRequest(ctx, searchUrl, query.headers); let pItems = data.items; // 测试代码 // let pItems = items; const productList = util.getProductList(pItems); resData.code = 200; resData.list = productList; resData.reqParams = `关键词:${query.q}; 爬取条数:${query.size}; 排序规则:${query.sort}`; await ctx.render('home/alibaba.tpl', resData); } catch (e) { resData.code = 0; resData.list = []; resData.msg = JSON.stringify(e); resData.reqParams = `关键词:${query.q}; 爬取条数:${query.size}; 排序规则:${query.sort}`; await ctx.render('home/alibaba.tpl', resData); } } } // 拼多多静态页面 async pinduoduo() { await this.ctx.render('pinduoduo/pinduoduo.tpl'); } } module.exports = HomeController; <file_sep>/app/public/detail.js $(function() { // 监听页面刷新 window.onbeforeunload = function() { return "确认要刷新此页面吗?"; }; // 获取页面复制的数据 function getPageData(id) { let data = document.querySelector('#'+id); if (!data.value) { alert('请复制代码到拼多多相应页面,然后再来你操作'); return; } return JSON.parse(data.value); } // 删除输入框的数据 function clearTextareaValue(id) { document.querySelector('#'+id).value = ''; } // getProduct 获取产品数据 function getProduct(data) { let goods = data.goods; if (!goods) { alert('请复制代码到拼多多相应页面,然后再来你操作'); return; } let productModel = { topGallery0: goods.topGallery[0], // 主图 goodsID: goods.goodsID, goodsName: goods.goodsName, sideSalesTip: goods.sideSalesTip, skus: goods.skus, skusDes: getSkusDes(goods.skus) }; return productModel; } // 获取sku的描述文案字符串 function getSkusDes(skus) { const skusDesArr = []; skus.forEach(function(ele) { let str = '【'; ele.specs.forEach(function(subEle) { str += subEle.spec_value + ' '; }); str += `(${ele.groupPrice})】`; skusDesArr.push(str); }); return skusDesArr.join(','); } // 讲数据展示到表格中 function addCurrentToTable(product) { let table = $('#table'); let trDom = $(`<tr class="row"> <td class="col-md-1"><img class="product_img" src=${product.topGallery0} /></td> <td class="col-md-2">${product.goodsName}</td> <td class="col-md-1">${product.goodsID}</td> <td class="col-md-1">${product.sideSalesTip}</td> <td class="col-md-7">${product.skusDes}</td> </tr>`); table.append(trDom); } // 页面上的产品数据表格JSON let dataList = []; let commentList = []; // 筛选并存储数据 document.querySelector('#saveData').addEventListener('click', function() { const data = getPageData('data'); const product = getProduct(data); dataList.push(product); addCurrentToTable(product); clearTextareaValue('data'); // console.log(dataList); }); /** ---------------------------------------------评论数据收集和整理------------------------------------------------ */ // getProduct 获取产品数据 function getCommentObject(commentObject, currentProductId, data) { if (commentObject[currentProductId]) { commentObject[currentProductId] = commentObject[currentProductId].concat(data); } else { commentObject[currentProductId] = data; } return commentObject; } // 将评论数据量写入表格 function addCurrentToCommentTable(commentObject) { let table = $('#tableComment'); let str = `<tr class="row"> <th class="col-md-2">产品ID</th> <th class="col-md-2">已录入数据量</th> </tr>`; for (const key in commentObject) { if (commentObject.hasOwnProperty(key)) { const element = commentObject[key]; str += `<tr class="row"> <td class="col-md-2">${key}</td> <td class="col-md-2">${element.length}</td> </tr>`; } } table.html(str); } // 更新当前产品id,只有当数据量大于1且存在goodsId function updateCurrentProductId(dataList, currentProductId) { let res = currentProductId; if (dataList.length >= 1 && dataList[0].goodsId) { res = dataList[0].goodsId; } document.querySelector('#currentInputProduct').text = res; return res; } let currentProductId = ''; let commentObject = {}; // 评论模态框弹出 document.querySelector('#commentModel').addEventListener('click', function() { document.querySelector('#model').style.display = 'block'; }); // 评论模态框关闭 document.querySelector('#closeCommentModel').addEventListener('click', function() { document.querySelector('#model').style.display = 'none'; }); // 评论数据暂存 document.querySelector('#saveCommentData').addEventListener('click', function() { let pageData = getPageData('commentData').data; clearTextareaValue('commentData'); currentProductId = updateCurrentProductId(pageData, currentProductId); commentObject = getCommentObject(commentObject, currentProductId, pageData); addCurrentToCommentTable(commentObject); }); /** -------------------------------------评论数据分析------------------------------------------- */ // 组装成echarts需要的数据 function getEchartsData(commentObject) { let arr = []; for (const key in commentObject) { if (commentObject.hasOwnProperty(key)) { const element = commentObject[key]; arr.push(getEchartsOptions(key, element)); } } return arr; } // echarts的配置数据筛选 function getEchartsOptions(productId, commentList) { const obj = {}; commentList.forEach(function(ele) { let specStr = getSkuSpec(ele.specs); if (obj[specStr]) { obj[specStr]++; } else { obj[specStr] = 1; } }); const options = { title: { text: `当前产品ID: ${productId}; 共计数据:${commentList.length}` }, tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, grid: { left: '4%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'value', boundaryGap: [0, 0.1] }, yAxis: { type: 'category', data: Object.keys(obj) }, series: [ { name: '数据量', type: 'bar', data: Object.values(obj) } ] } return options; } // 获取sku描述 function getSkuSpec(specs) { let arr = []; let res = ''; if (specs) { arr = JSON.parse(specs); } arr.forEach(function(element) { res += element.spec_value + ' '; }); return res; } // 初始化echarts表 function initEcharts(echartsOptions) { echartsOptions.forEach(function(element, index) { $('#myEchartsWrapper').append(`<div id="chart${index}" style="width: 2000px;height:400px;"></div>`); // 基于准备好的dom,初始化echarts实例 let myChart = echarts.init(document.getElementById(`chart${index}`)); // 使用刚指定的配置项和数据显示图表。 myChart.setOption(element); }); } let echartsOptions = []; // 评论数据分析 document.querySelector('#analyze').addEventListener('click', function() { if (Object.keys(commentObject).length <= 0) { alert('请先录入评论数据'); return; } echartsOptions = getEchartsData(commentObject); console.log(echartsOptions); initEcharts(echartsOptions); }); /* -----------------------------------导出excel ------------------------------*/ /** * 通用的打开下载对话框方法,没有测试过具体兼容性 * @param url 下载地址,也可以是一个blob对象,必选 * @param saveName 保存文件名,可选 */ function openDownloadDialog(url, saveName) { if(typeof url == 'object' && url instanceof Blob) { url = URL.createObjectURL(url); // 创建blob地址 } var aLink = document.createElement('a'); aLink.href = url; aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效 var event; if(window.MouseEvent) event = new MouseEvent('click'); else { event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); } aLink.dispatchEvent(event); } // 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载 function sheet2blob(sheet, sheetName) { sheetName = sheetName || 'sheet1'; var workbook = { SheetNames: [sheetName], Sheets: {} }; workbook.Sheets[sheetName] = sheet; // 生成excel的配置项 var wopts = { bookType: 'xlsx', // 要生成的文件类型 bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性 type: 'binary' }; var wbout = XLSX.write(workbook, wopts); var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"}); // 字符串转ArrayBuffer function s2ab(s) { var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } return blob; } // 导出excel function exportExcel(data) { var sheet = XLSX.utils.json_to_sheet(data); openDownloadDialog(sheet2blob(sheet), '导出.xlsx'); } // 评论导出数据整理 function commentFileData(commentObject) { let arr = []; const obj = {}; for (const key in commentObject) { if (commentObject.hasOwnProperty(key)) { const eleArr = commentObject[key]; eleArr.forEach(function (subEle) { let specStr = getSkuSpec(subEle.specs); if (obj[specStr]) { obj[specStr]++; } else { obj[specStr] = 1; } }) arr.push([key].concat(Object.keys(obj))); arr.push(['数量'].concat(Object.values(obj))); } } return arr; } // 导出产品列表 document.querySelector('#exportProduct').addEventListener('click', function() { if (dataList.length <= 0) { alert('暂无数据'); return; } exportExcel(dataList); }); // 导出评论列表 document.querySelector('#exportComment').addEventListener('click', function() { if (Object.keys(commentObject).length <= 0) { alert('暂无数据'); return; } exportExcel(commentFileData(commentObject)); }); }); <file_sep>/app/router.js 'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; router.get('/', controller.saveImg.alibaba); router.get('/alibaba', controller.saveImg.alibaba); router.get('/pinduoduo', controller.home.pinduoduo); router.get('/saveImg', controller.saveImg.index); router.get('/material', controller.material.index); router.get('/material/hupu', controller.material.hupu); }; <file_sep>/app/controller/saveImg.js 'use strict'; const Controller = require('egg').Controller; const Util = require('../common/util'); const request = require("request"); const fs = require("fs"); const path = require('path'); const puppeteer = require('puppeteer'); class SaveImgController extends Controller { async alibaba() { await this.ctx.render('alibaba/alibaba.tpl'); } async index() { // 参数 const { ctx } = this; const { inputPath, inputUrl, inputUrlHead } = ctx.request.query; const res = { detailImgList: [], headImgList: [], code: 0, msg: '' }; // 创建sku, 头图, 详情图, 白底图文件夹 const skuImgPath0 = `${inputPath}/sku`; const headImgPath0 = `${inputPath}/头图`; const detailImgPath0 = `${inputPath}/详情图`; const whiteImgPath0 = `${inputPath}/白底图`; this.creatDirMethod(skuImgPath0); this.creatDirMethod(headImgPath0); this.creatDirMethod(detailImgPath0); this.creatDirMethod(whiteImgPath0); // 详情页图片 const detailImgPath = `${inputPath}/1688详情图`; this.creatDirMethod(detailImgPath); const detailImgUrlArray = inputUrl.split(','); let i = 0; const detailInterval = setInterval(async () => { if (i < detailImgUrlArray.length) { const ele = detailImgUrlArray[i]; let saveImg = await this.writeImg(ele, detailImgPath, `${i}.jpg`); res.detailImgList.push(saveImg); i++; } else { clearInterval(detailInterval); } }, Math.random() * 2000 + 1000); // 头页图片 const headImgPath = `${inputPath}/1688头图`; this.creatDirMethod(headImgPath); const headImgUrlArray = inputUrlHead.split(','); let j = 0; const headInterval = setInterval(async () => { if (j < headImgUrlArray.length) { const ele = headImgUrlArray[j]; let saveImg = await this.writeImg(ele, headImgPath, `${j}.jpg`); res.headImgList.push(saveImg); j++; } else { clearInterval(headInterval); } }, Math.random() * 2000 + 1000); res.code = 200; ctx.body = res; } // 创建文件夹 creatDirMethod(myPath) { let flag = false; if (fs.existsSync(myPath)) { flag = true; } else { if (this.creatDirMethod(path.dirname(myPath))) { fs.mkdirSync(myPath); flag = true; } } return flag; } // 将文件写入文件系统 writeImg(imgUrl, myDirPath, filename) { return new Promise((resolve, reject) => { const writeStream = fs.createWriteStream(`${myDirPath}/${filename}`); const readStream = request(imgUrl); readStream.pipe(writeStream); readStream.on('end', function () { console.log('文件下载成功', imgUrl, `${myDirPath}/${filename}`); }); readStream.on('error', function (err) { console.log('错误信息:', err, imgUrl, `${myDirPath}/${filename}`); reject(`文件下载错误,${myDirPath}/${filename}`); }); writeStream.on('finish', function (data) { console.log('文件写入成功', imgUrl, `${myDirPath}/${filename}`); resolve(`保存成功, ${imgUrl}/${myDirPath}/${filename}`); writeStream.end(); }); }); } } module.exports = SaveImgController; <file_sep>/app/common/util.js /** * util 类提供通用方法 */ const https = require('https'); const cheerio = require('cheerio'); const request = require('request'); class Util { constructor() {} // html请求 getHtmlData(url) { return new Promise((resolve, reject) => { https.get(url, function (res) { let str = ''; res.on('data', function (chunk) { str += chunk; }) res.on('end', function () { const $ = cheerio.load(str); if ($) { resolve($); } else { console.error('html内容', str); console.error('html的$内容', $); reject('出现错误'); } }) }) }); } // https请求 httpRequest(ctx, url, headers) { let headersObj = this.getHeaders(headers); return new Promise((resolve, reject) => { ctx.curl(url, { dataType: 'json', method: 'get', headers: headersObj }).then(response => { // console.log('------------response--start--------------------', response); // console.log('------------response--end--------------------'); if (response.status === 200 && !response.data.error_code) { console.log('data.items[0],', response.data.items[0]); resolve(response.data); } else { reject(response.data); } }).catch(e => { console.log('error', e); reject(e); }); }); } // 获取headers getHeaders(headersString) { const headersArray = headersString.split(/\r\n/); const headersObject = {}; headersArray.forEach(ele => { const arr = ele.split(':'); const key = arr.length >= 0 ? arr[0] : ''; let value = arr.length >= 1 ? arr[1] : ''; // value = value.replace(' ', ''); headersObject[key] = value; }); return headersObject; } // 获取产品list表格, 需要属性为: 产品主图, 产品id,产品url,产品名称,产品销量 getProductList(list) { let resList = []; list.forEach(ele => { const product = ele.item_data.goods_model; resList.push({ hd_thumb_url: product.hd_thumb_url, goods_id: product.goods_id, link_url: `https://mobile.yangkeduo.com/${product.link_url}`, goods_name: product.goods_name, sku_price: 0, sales: product.sales, comment_number: 0 }); }); // console.log('产品list,', resList); return resList.reverse(); } } module.exports = Util; <file_sep>/app/public/common.js function copy(value) { const input = document.createElement('input'); input.setAttribute('readonly', 'readonly'); input.setAttribute('value', value); document.body.appendChild(input); input.select(); input.setSelectionRange(0, 9999); if (document.execCommand('copy')) { document.execCommand('copy'); alert('复制成功!'); } document.body.removeChild(input); }
b572424d6f9b6df8456773d8b72734319fe220e6
[ "JavaScript" ]
6
JavaScript
guxiansheng1991/yangkeduo-spider
b926d9b38e129c6a66c2da869d9c812e7c2708b6
11224f5fb8b8056f141148eb0dfcebcffa0e372a
refs/heads/master
<repo_name>adampickeral/router<file_sep>/README.md router ====== Simple JavaScript router based on location hash changes <file_sep>/router.js var Router = function (globals) { this.globals_ = globals; this.routes_ = {}; }; Router.prototype.init = function () { window.onhashchange = this.route.bind(this); this.route(); }; Router.prototype.addRoute = function (route, callback, defaultRoute, optionalScope) { var scope; scope = optionalScope || this; this.routes_[route] = { cback: callback, context: scope }; if (defaultRoute) { this.routes_['_default'] = { cback: callback, context: scope }; } }; Router.prototype.route = function () { var hash, routeCallback, scope; hash = this.getLocationHash_(); route = this.routes_[hash]; if (!route) { route = this.routes_['_default']; } routeCallback = route.cback; scope = route.context; routeCallback.apply(scope); }; Router.prototype.getLocationHash_ = function () { return this.globals_.location.hash.substr(this.globals_.location.hash.indexOf('#') + 1); }; Router.prototype.globals_ = null; Router.prototype.routes_ = null; <file_sep>/spec/router_spec.js describe('Router', function () { var router, location, globals, defaultRoute, otherRoute; beforeEach(function () { location = {}; globals = { location: { hash: '' } }; defaultRoute = jasmine.createSpy('defaultRoute'); otherRoute = jasmine.createSpy('otherRoute'); router = new Router(globals); router.addRoute('routeDefault', defaultRoute, true); router.addRoute('otherRoute', otherRoute); }); describe('route', function () { it('invokes the callback for the specified route', function () { globals.location.hash = '#routeDefault'; router.route(); expect(defaultRoute).toHaveBeenCalled(); }); it('invokes the default route if a route for the hash cannot be found', function () { globals.location.hash = '#sldjf'; router.route(); expect(defaultRoute).toHaveBeenCalled(); }); it('invokes the default route if the hash is empty', function () { globals.location.hash = ''; router.route(); expect(defaultRoute).toHaveBeenCalled(); }); it('invokes the callback for the specified route that is not the default route', function () { globals.location.hash = '#otherRoute'; router.route(); expect(otherRoute).toHaveBeenCalled(); }); it('invokes the callback with the scope of the router if no scope is specified', function () { globals.location.hash = '#otherRoute'; spyOn(otherRoute, 'apply'); router.route(); expect(otherRoute.apply).toHaveBeenCalledWith(router); }); it('invokes the callback with the provided scope if one is given', function () { var otherScope; otherScope = { scope: 'other scope' }; router.addRoute('otherRoute', otherRoute, false, otherScope); spyOn(otherRoute, 'apply'); globals.location.hash = '#otherRoute'; router.route(); expect(otherRoute.apply).toHaveBeenCalledWith(otherScope); }); }); describe('init', function () { it('routes to the default route when initialized', function () { router.init(); expect(defaultRoute).toHaveBeenCalled(); }); it('routes when the location hash changes', function () { router.init(); globals.location.hash = '#otherRoute'; $(window).trigger('hashchange'); expect(otherRoute).toHaveBeenCalled(); }); }); });
54eb09f43785746101b534cd14f0feb71d1e41ba
[ "Markdown", "JavaScript" ]
3
Markdown
adampickeral/router
ec8931409fd9bbaec1b217c85db26cbc7b7aff28
0890104b4430d802fdddcb9514d993fdc41c3674
refs/heads/master
<repo_name>joonaskilpela/3D-Platformer<file_sep>/Assets/_Scripts/Camera/PlayerFollower.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerFollower : MonoBehaviour { public bool following = true; Renderer rnd; Shader ogShader; private void Start() { rnd = GetComponent<Renderer>(); rnd.enabled = false; } } <file_sep>/Assets/_Scripts/Camera/AngleChanger.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AngleChanger : MonoBehaviour { Transform player; Renderer rnd; private void Start() { player = FindObjectOfType<PlayerMovement>().transform; rnd = GetComponent<Renderer>(); rnd.enabled = false; } void Update() { transform.position = player.position; } } <file_sep>/Assets/_Scripts/Level/Winning.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Winning : MonoBehaviour { Text winText; public Image bg; int curLevel = 0; private void Awake() { winText = GetComponent<Text>(); winText.enabled = false; bg.enabled = false; curLevel = SceneManager.GetActiveScene().buildIndex; winText.text = "You Win!" + "\nPress Enter/Start to" + "\nGo to Next Level!"; } private void Update() { if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.Joystick1Button7)) { if (winText.enabled && curLevel < SceneManager.sceneCountInBuildSettings - 1) { SceneManager.LoadScene(curLevel + 1); } } if (Input.GetKeyDown(KeyCode.Escape) ||Input.GetKeyDown(KeyCode.Joystick1Button6)){ if (winText.enabled && curLevel == SceneManager.sceneCountInBuildSettings - 1) { Application.Quit(); } } } public void Victory() { if (curLevel == SceneManager.sceneCountInBuildSettings - 1) { FindObjectOfType<PauseMenu>().won = false; winText.text = "You Beat the Game!" + "\nPress Esc/Back to" + "\nto Quit!"; } bg.enabled = true; winText.enabled = true; } } <file_sep>/Assets/_Scripts/Level/MinPosition.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MinPosition : MonoBehaviour { public float minPosition = -100; void Start () { FindObjectOfType<PlayerMovement>().minPosition = minPosition; gameObject.SetActive(false); } } <file_sep>/Assets/_Scripts/Camera/CameraFollow.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { PlayerMovement plyMovement; Transform plyTransform; Transform plyFollower; public float speed = 2; Transform parent; float waitTime; bool turning = false; Quaternion targetRotation; [HideInInspector] public bool following = true; [HideInInspector] public bool respawning = false; private void Start() { plyMovement = Transform.FindObjectOfType<PlayerMovement>(); plyTransform = plyMovement.transform; plyFollower = Transform.FindObjectOfType<PlayerFollower>().transform; parent = transform.parent.GetComponent<Transform>(); } private void FixedUpdate() { if (respawning) { Vector3 velocity = Vector3.zero; parent.transform.position = Vector3.Lerp(parent.transform.position, plyFollower.position, speed * 3 * Time.smoothDeltaTime); if (turning) { parent.transform.rotation = Quaternion.Lerp(parent.transform.rotation, targetRotation, speed * 3 * Time.smoothDeltaTime); if (Quaternion.Angle(parent.transform.rotation, targetRotation) < 0.01f) { parent.transform.rotation = plyFollower.rotation; turning = false; } } if(Vector3.Distance(parent.transform.position, plyFollower.position) < 0.1f) { respawning = false; plyMovement.StartGame(); } } transform.LookAt(plyTransform); } public void SetWaitTime() { targetRotation = plyFollower.rotation; turning = true; } } <file_sep>/Assets/_Scripts/Camera/CameraController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { CameraFollow camFollow; Transform plyFollower; Transform player; Vector3 mStartingPos; Vector3 mCurPos; Transform parent; bool moving = false; Transform ang; float turnAngle; [HideInInspector] public bool respawning = false; private float xCamMove { get { if (Mathf.Abs(Input.GetAxis("hRightStick")) > 0.3f) return Input.GetAxis("hRightStick") * 2; else return Input.GetAxis("Mouse X"); } } private float yCamMove { get { if (Mathf.Abs(Input.GetAxis("vRightStick")) > 0.3f) return Input.GetAxis("vRightStick") * 2; else return Input.GetAxis("Mouse Y"); } } private void Start() { camFollow = GetComponent<CameraFollow>(); plyFollower = FindObjectOfType<PlayerFollower>().transform; player = FindObjectOfType<PlayerMovement>().transform; parent = transform.parent.GetComponent<Transform>(); ang = FindObjectOfType<AngleChanger>().transform; } private void Update() { if (respawning) return; if (Mathf.Abs(Input.GetAxis("hRightStick")) > 0.5f || Mathf.Abs(Input.GetAxis("vRightStick")) > 0.5f) { if (!moving) { camFollow.following = false; moving = true; } } else { ang.rotation = player.rotation; camFollow.following = true; moving = false; } } private void FixedUpdate() { if (respawning) return; parent.position = Vector3.Lerp(parent.position, plyFollower.position, 8 * Time.smoothDeltaTime); parent.transform.Rotate(parent.up, xCamMove * 2f); } } <file_sep>/Assets/_Scripts/Level/FruitCounter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FruitCounter : MonoBehaviour { int curCount = 0; //public List<Collectible> fruits = new List<Collectible>(); [HideInInspector] public int maxCount; Text text; private void Start() { text = GetComponent<Text>(); } public void CountFruits(int addition = 0) { curCount += addition; if (text == null) text = GetComponent<Text>(); text.text = "Fruits: " + curCount + " / " + maxCount; if(curCount == maxCount) { FindObjectOfType<Winning>().Victory(); } } } <file_sep>/Assets/_Scripts/Camera/ChangeVisibility.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeVisibility : MonoBehaviour { Renderer rnd; Shader ogShader; Shader transparent; private void Start() { rnd = GetComponent<Renderer>(); ogShader = rnd.material.shader; transparent = Shader.Find("Transparent/Diffuse"); Color col = rnd.material.color; col.a = 0.3f; rnd.material.color = col; } public void MakeVisible() { rnd.material.shader = ogShader; } public void FadeAway() { rnd.material.shader = transparent; } } <file_sep>/Assets/_Scripts/Camera/MusicPlayer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; // Play music at camera's position // This exists because changing and applying the camera prefab also changes the song for every level public class MusicPlayer : MonoBehaviour { void Start() { GetComponent<Renderer>().enabled = false; transform.parent = FindObjectOfType<CameraFollow>().transform; transform.position = transform.parent.position; } } <file_sep>/Assets/_Scripts/Camera/BoxCaster.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoxCaster : MonoBehaviour { List<ChangeVisibility> visibilities = new List<ChangeVisibility>(); private void OnTriggerEnter(Collider other) { if (other.GetComponent<ChangeVisibility>()) { visibilities.Add(other.GetComponent<ChangeVisibility>()); other.GetComponent<ChangeVisibility>().FadeAway(); //if (Vector3.Distance(other.transform.position, transform.position) < (Vector3.Distance(player.position, transform.position))) //{ //} } } private void OnTriggerExit(Collider other) { if (visibilities.Contains(other.GetComponent<ChangeVisibility>())) { other.GetComponent<ChangeVisibility>().MakeVisible(); visibilities.Remove(other.GetComponent<ChangeVisibility>()); } } } <file_sep>/Assets/_Scripts/Level/Enemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public enum EnemyType { blob, spiky }; public EnemyType myType; Animator anim; float knockBack = 1f; PlayerMovement player; Transform plyTransform; float distance; public List<AudioClip> idleSounds = new List<AudioClip>(); public List<AudioClip> alertSounds = new List<AudioClip>(); public List<AudioClip> hitSounds = new List<AudioClip>(); public AudioClip deathSound; AudioSource auSource; AudioClip tempClip; bool alert = false; float soundTimer; private void Start() { anim = GetComponent<Animator>(); player = FindObjectOfType<PlayerMovement>(); plyTransform = player.transform; auSource = GetComponent<AudioSource>(); NextSound(); } private void Update() { if (anim.GetCurrentAnimatorStateInfo(0).IsName("Die")) transform.rotation = Quaternion.identity; else { if (alert) { transform.LookAt(plyTransform); } else if(soundTimer < Time.time) { tempClip = idleSounds[Random.Range(0, idleSounds.Count - 1)]; auSource.clip = tempClip; auSource.Play(); NextSound(); } } } private void OnTriggerEnter(Collider other) { if (!anim.GetCurrentAnimatorStateInfo(0).IsName("Die")) { if (other.GetComponent<PlayerMovement>()) { if (myType == EnemyType.blob) { if (other.transform.position.y > transform.position.y) { anim.SetBool("Dying", true); auSource.PlayOneShot(deathSound); GetComponent<BoxCollider>().enabled = false; GetComponent<SphereCollider>().enabled = true; other.GetComponent<PlayerMovement>().yVelocity = other.GetComponent<PlayerMovement>().jumpForce; } else { //Vector3 dir = other.transform.position - transform.position; //other.GetComponent<CharacterController>().Move(dir * knockBack); tempClip = hitSounds[Random.Range(0, hitSounds.Count - 1)]; auSource.PlayOneShot(tempClip); other.GetComponent<PlayerMovement>().knockBackForce = knockBack; other.GetComponent<PlayerMovement>().pushingBack = true; } } else if (myType == EnemyType.spiky) { other.GetComponent<PlayerMovement>().knockBackForce = knockBack; other.GetComponent<PlayerMovement>().pushingBack = true; } } } } public void GoAlert() { alert = true; anim.SetBool("SeeingSomething", true); tempClip = alertSounds[Random.Range(0, alertSounds.Count - 1)]; auSource.clip = tempClip; auSource.Play(); transform.LookAt(plyTransform.position); } public void CalmDown() { alert = false; anim.SetBool("SeeingSomething", false); } void NextSound() { soundTimer = Time.time + Random.Range(2f, 8f); } } <file_sep>/Assets/_Scripts/Player/PlayerMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed = 10; public float rotSpeed = 5; [HideInInspector] public bool moving; [HideInInspector] public bool rotating; Transform cam; bool grounded; public float gravity = 2; Vector3 velocity; Vector3 eulerAngleVelocity; CharacterController cc; [HideInInspector] public float yVelocity = 0; public float jumpForce = 2; float multiplier = 0; public float accelerationSpeed = 2; Animator anim; [HideInInspector] public bool pushingBack = false; [HideInInspector] public float knockBackForce = 1; [HideInInspector] public float minPosition = -1000; Vector3 startPosition; bool mouseUsed = false; float inputTimer; float nextInputTime = 1; bool respawning = false; CameraController camControl; private void Start() { cam = Transform.FindObjectOfType<CameraFollow>().transform; cc = GetComponent<CharacterController>(); velocity = Vector3.zero; anim = GetComponentInChildren<Animator>(); startPosition = transform.position; camControl = FindObjectOfType<CameraController>(); } private void Update() { if (respawning) { return; } if(inputTimer < Time.time) { cam.GetComponent<CameraFollow>().SetWaitTime(); inputTimer = Time.time + nextInputTime; } if(Input.GetAxis("Horizontal") > 0 || Input.GetAxis("Vertical") > 0) { if (multiplier < 1) multiplier += Time.smoothDeltaTime; if (multiplier >= 1) multiplier = 1; } else { if (multiplier > 0) multiplier -= Time.smoothDeltaTime; if (multiplier <= 0) multiplier = 0; } Vector3 targetVelocity = Vector3.zero; targetVelocity += cam.forward * Input.GetAxis("Vertical"); targetVelocity += cam.right * Input.GetAxis("Horizontal"); //movement.Normalize(); targetVelocity *= speed; velocity = Vector3.Lerp(velocity, targetVelocity, accelerationSpeed * Time.smoothDeltaTime); Vector3 aVel = velocity; aVel.y = 0; anim.SetFloat("MoveSpeed", aVel.magnitude * 5); anim.SetBool("Grounded", cc.isGrounded); if (!cc.isGrounded) { yVelocity -= gravity * Time.smoothDeltaTime; } else { if (Input.GetButtonDown("Jump") || Input.GetAxis("TriggerJump") > 0) { yVelocity = jumpForce; } } velocity.y = yVelocity; if(transform.position.y < minPosition) { Respawn(); } } private void FixedUpdate() { if (respawning) return; MoveCharacter(velocity); if (pushingBack) { PushBack(knockBackForce); } } void MoveCharacter(Vector3 direction) { cc.Move(direction); Vector3 vel = cc.velocity; vel.y = 0; if (vel.magnitude > 0) { transform.rotation = Quaternion.LookRotation(vel); } } public void PushBack(float force) { Vector3 dir = transform.forward * -force * Time.smoothDeltaTime; dir.z = -1; dir.y += 0.1f; cc.Move(dir); if(force > 0.5f) { knockBackForce *= 0.8f; } else { pushingBack = false; } } void Respawn() { respawning = true; cam.GetComponent<CameraFollow>().respawning = true; camControl.respawning = true; transform.position = startPosition; } public void StartGame() { respawning = false; camControl.respawning = false; } } <file_sep>/Assets/_Scripts/UI/PauseMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Audio; using UnityEngine.SceneManagement; public class PauseMenu : MonoBehaviour { public GameObject pausePanel; public GameObject instructionsPanel; public Button resumeButton; public Button instructionsButton; public Button[] levelButtons; public Slider musicSlider; public Button quitButton; public Button returnButton; public AudioMixer mixer; [HideInInspector] public bool won = false; bool paused = false; void Start () { Resume(); musicSlider.value = musicSlider.maxValue; } void Update () { if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(KeyCode.Joystick1Button7)) { if(paused) { Resume(); } else { Pause(); } } } public void Pause() { Time.timeScale = 0f; pausePanel.SetActive(true); paused = true; Cursor.visible = true; } public void Resume() { pausePanel.SetActive(false); instructionsPanel.SetActive(false); Time.timeScale = 1; paused = false; Cursor.visible = false; } public void Instruct() { pausePanel.SetActive(false); instructionsPanel.SetActive(true); } public void TimeToQuit() { Application.Quit(); } public void ReturnToPausePanel() { instructionsPanel.SetActive(false); pausePanel.SetActive(true); } public void GoToLevel(int level) { SceneManager.LoadScene(level); } public void MusicVolume(float volume) { mixer.SetFloat("musicVolume", Mathf.Log10(volume) * 20); } } <file_sep>/Assets/_Scripts/Level/EnemyRadius.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyRadius : MonoBehaviour { Enemy parent; private void Start() { parent = GetComponentInParent<Enemy>(); } private void OnTriggerEnter(Collider other) { if (other.GetComponent<PlayerMovement>()) { if (parent == null) parent = GetComponentInParent<Enemy>(); parent.GoAlert(); } } private void OnTriggerExit(Collider other) { if (other.GetComponent<PlayerMovement>()) { if (parent == null) parent = GetComponentInParent<Enemy>(); parent.CalmDown(); } } } <file_sep>/Assets/_Scripts/Level/Collectible.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Collectible : MonoBehaviour { float rotSpeed = 100; float hoverSpeed = 5; float height = 0.3f; FruitCounter counter; public List<AudioClip> chomps = new List<AudioClip>(); Vector3 origPos; float offsetTime; private void Start() { origPos = transform.position; offsetTime = Random.Range(0, 100); counter = FindObjectOfType<FruitCounter>(); //counter.fruits.Add(this); counter.maxCount++; counter.CountFruits(0); } private void Update() { transform.RotateAround(transform.position, Vector3.up, rotSpeed * Time.smoothDeltaTime); //Vector3 vel = transform.position; //vel.y = yOrigPos; //vel.y = Mathf.Sin(Time.time * hoverSpeed) * height + transform.position.y; //transform.position = vel; transform.position = origPos + Vector3.up * Mathf.Sin((Time.time + offsetTime) * hoverSpeed) * height; } private void OnTriggerEnter(Collider other) { if (other.GetComponent<PlayerMovement>()) { counter.CountFruits(1); /*int au = Random.Range(1, chomps.Count - 1); //AudioSource.PlayClipAtPoint(chomps[au], transform.position, 100f); AudioSource.PlayClipAtPoint(chomps[au], FindObjectOfType<AudioListener>().transform.position, 0.9f);*/ AudioSource.PlayClipAtPoint(chomps[0], FindObjectOfType<AudioListener>().transform.position, 0.9f); GameObject.Destroy(gameObject); } } }
20eb79e58dafe62ac1b70e638a0090dc2652c10e
[ "C#" ]
15
C#
joonaskilpela/3D-Platformer
0783cfd51a73794d47302443d20c9e2cee0fda44
31d5baaf63afb9569c72763724adca8d7a670276
refs/heads/master
<repo_name>kstamatov/DevOps-Pragmatic<file_sep>/README.md # DevOps-Pragmatic DevOps scripts and programs <file_sep>/helm/pipeline.sh #!/bin/bash vars=($@) env=${vars[0]} label=${vars[1]} name=${vars[2]} if [[ $env == "dev" ]] #in case of chartmuseum, chartmuseum/test-app then helm upgrade --install test-app test-app/ --install --wait --set Deployment.Name=$env-$name,Deployment.label=$env-$label elif [[ $env == "stage" ]] then helm upgrade test-app test-app/ --install --wait --set Deployment.Name=$env-$name,Deployment.label=$env-$label else echo "Invalid paramemters" fi
34e6835e8829f63ee7f15164fe0922b144ac4d3a
[ "Markdown", "Shell" ]
2
Markdown
kstamatov/DevOps-Pragmatic
1f60863e4e2d82dc2320b80108527241fc3e6b66
771b9f0f9d1305b2a4fc1cb0294b0ce2d9273d91
refs/heads/master
<file_sep>/* gohack $module... fetch module if needed into $GOHACK/$module checkout correct commit "is not clean" failure if it's been changed but at right commit "is not clean; will not update" failure if changed and at wrong commit add replace statement to go.mod gohack -u $module remove replace statement from go.mod */ package main import ( "flag" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "golang.org/x/tools/go/vcs" "gopkg.in/errgo.v2/fmt/errors" "github.com/rogpeppe/gohack/internal/dirhash" ) var ( printCommands = flag.Bool("x", false, "show executed commands") dryRun = flag.Bool("n", false, "print but do not execute update commands") forceClean = flag.Bool("force-clean", false, "force cleaning of modified-but-not-committed repositories. Do not use this flag unless you really need to!") undo = flag.Bool("u", false, "undo gohack replace") quick = flag.Bool("q", false, "quick mode; copy only source only without VCS information") ) var ( exitCode = 0 cwd = "." ) func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "usage: gohack module...\n") flag.PrintDefaults() fmt.Print(` The gohack command checks out Go module dependencies into a directory where they can be edited. By default it extracts module source code into $HOME/gohack/<module>. By default, it also tries to check out the version control information into that directory and update it to the expected version. If the directory already exists, it will be updated in place. With no arguments, gohack prints all modules that are currently replaced by local directories. The -u flag can be used to revert to the non-gohacked module versions. It only removes the relevant replace statements from the go.mod file - it does not change any of the directories referred to. With the -u flag and no arguments, all replace statements that refer to directories will be removed. `) os.Exit(2) } flag.Parse() if err := main1(); err != nil { errorf("%v", err) } os.Exit(exitCode) } func main1() error { if dir, err := os.Getwd(); err == nil { cwd = dir } else { errorf("cannot get current working directory: %v", err) } if *undo { return undoReplace(flag.Args()) } if len(flag.Args()) == 0 { return printReplacementInfo() } var repls []*modReplace mods, err := allModules() if err != nil { // TODO this happens when a replacement directory has been removed. // Perhaps we should be more resilient in that case? return errors.Notef(err, nil, "cannot get module info") } for _, mpath := range flag.Args() { m := mods[mpath] if m == nil { errorf("module %q does not appear to be in use", mpath) continue } if m.Replace != nil { if m.Replace.Path == m.Replace.Dir { // TODO update to the current version instead of printing an error? // That would allow us to (for example) upgrade from quick mode to VCS mode // for a given module. errorf("%q is already replaced by %q - are you already gohacking it?", mpath, m.Replace.Dir) } else { errorf("%q is already replaced; will not override replace statement in go.mod", mpath) } continue } var repl *modReplace if *quick { repl1, err := updateFromLocalDir(m) if err != nil { errorf("cannot update %s from local cache: %v", m.Path, err) continue } repl = repl1 } else { repl1, err := updateVCSDir(m) if err != nil { errorf("cannot update VCS dir for %s: %v", m.Path, err) continue } repl = repl1 } // Automatically generate a go.mod file if one doesn't // already exist, because otherwise the directory cannot be // used as a module. if err := ensureGoModFile(repl.modulePath, repl.dir); err != nil { errorf("%v", err) } repls = append(repls, repl) } if len(repls) == 0 { return errors.New("all modules failed; not replacing anything") } if err := replace(repls); err != nil { errorf("cannot replace: %v", err) } for _, info := range repls { fmt.Printf("%s => %s\n", info.modulePath, info.dir) } return nil } func updateFromLocalDir(m *listModule) (*modReplace, error) { if m.Dir == "" { return nil, errors.Newf("no local source code found") } srcHash, err := hashDir(m.Dir) if err != nil { return nil, errors.Notef(err, nil, "cannot hash %q", m.Dir) } destDir := moduleDir(m.Path) _, err = os.Stat(destDir) if err != nil && !os.IsNotExist(err) { return nil, errors.Wrap(err) } repl := &modReplace{ modulePath: m.Path, dir: destDir, } if err != nil { // Destination doesn't exist. Copy the entire directory. if err := copyAll(destDir, m.Dir); err != nil { return nil, errors.Wrap(err) } } else { if !*forceClean { // Destination already exists; try to update it. isEmpty, err := isEmptyDir(destDir) if err != nil { return nil, errors.Wrap(err) } if !isEmpty { // The destination directory already exists and has something in. destHash, err := checkCleanWithoutVCS(destDir) if err != nil { return nil, errors.Wrap(err) } if destHash == srcHash { // Everything is exactly as we want it already. return repl, nil } } } // As it's empty, clean or we're forcing clean, we can safely replace its // contents with the current version. if err := updateDirWithoutVCS(destDir, m.Dir); err != nil { return nil, errors.Notef(err, nil, "cannot update %q from %q", destDir, m.Dir) } } // Write a hash file so we can tell if someone has changed the // directory later, so we avoid overwriting their changes. if err := writeHashFile(destDir, srcHash); err != nil { return nil, errors.Wrap(err) } return repl, nil } func checkCleanWithoutVCS(dir string) (hash string, err error) { wantHash, err := readHashFile(dir) if err != nil { if !os.IsNotExist(errors.Cause(err)) { return "", errors.Wrap(err) } return "", errors.Newf("%q already exists; not overwriting", dir) } gotHash, err := hashDir(dir) if err != nil { return "", errors.Notef(err, nil, "cannot hash %q", dir) } if gotHash != wantHash { return "", errors.Newf("%q is not clean; not overwriting", dir) } return wantHash, nil } func updateDirWithoutVCS(destDir, srcDir string) error { if err := os.RemoveAll(destDir); err != nil { return errors.Wrap(err) } if err := copyAll(destDir, srcDir); err != nil { return errors.Wrap(err) } return nil } // hashDir is like dirhash.HashDir except that it ignores the // gohack hash file in the top level directory. func hashDir(dir string) (string, error) { files, err := dirhash.DirFiles(dir, "") if err != nil { return "", err } j := 0 for _, f := range files { if f != hashFile { files[j] = f j++ } } files = files[:j] return dirhash.Hash1(files, func(name string) (io.ReadCloser, error) { return os.Open(filepath.Join(dir, name)) }) } // TODO decide on a good name for this. const hashFile = ".gohack-modhash" func readHashFile(dir string) (string, error) { data, err := ioutil.ReadFile(filepath.Join(dir, hashFile)) if err != nil { return "", errors.Note(err, os.IsNotExist, "") } return strings.TrimSpace(string(data)), nil } func writeHashFile(dir string, hash string) error { if err := ioutil.WriteFile(filepath.Join(dir, hashFile), []byte(hash), 0666); err != nil { return errors.Wrap(err) } return nil } func updateVCSDir(m *listModule) (*modReplace, error) { info, err := getVCSInfoForModule(m) if err != nil { return nil, errors.Notef(err, nil, "cannot get info") } if err := updateModule(info); err != nil { return nil, errors.Wrap(err) } return &modReplace{ modulePath: m.Path, dir: info.dir, }, nil } func undoReplace(modules []string) error { if len(modules) == 0 { // With no modules specified, we un-gohack all modules // we can find with local directory info in the go.mod file. m, err := goModInfo() if err != nil { return errors.Wrap(err) } for _, r := range m.Replace { if r.Old.Version == "" && r.New.Version == "" { modules = append(modules, r.Old.Path) } } } // TODO get information from go.mod to make sure we're // dropping a directory replace, not some other kind of replacement. args := []string{"mod", "edit"} for _, m := range modules { args = append(args, "-dropreplace="+m) } if _, err := runCmd(cwd, "go", args...); err != nil { return errors.Notef(err, nil, "failed to remove go.mod replacements") } for _, m := range modules { fmt.Printf("dropped %s\n", m) } return nil } func printReplacementInfo() error { m, err := goModInfo() if err != nil { return errors.Wrap(err) } for _, r := range m.Replace { if r.Old.Version == "" && r.New.Version == "" { fmt.Printf("%s => %s\n", r.Old.Path, r.New.Path) } } return nil } type modReplace struct { modulePath string dir string } func replace(repls []*modReplace) error { args := []string{ "mod", "edit", } for _, info := range repls { // TODO should we use relative path here? args = append(args, fmt.Sprintf("-replace=%s=%s", info.modulePath, info.dir)) } if _, err := runUpdateCmd(cwd, "go", args...); err != nil { return errors.Wrap(err) } return nil } func updateModule(info *moduleVCSInfo) error { // Remove an auto-generated go.mod file if there is one // to avoid confusing VCS logic. if _, err := removeAutoGoMod(info); err != nil { return errors.Wrap(err) } if info.alreadyExists && !info.clean && *forceClean { if err := info.vcs.Clean(info.dir); err != nil { return fmt.Errorf("cannot clean: %v", err) } } isTag := true updateTo := info.module.Version if IsPseudoVersion(updateTo) { revID, err := PseudoVersionRev(updateTo) if err != nil { return errors.Wrap(err) } isTag = false updateTo = revID } if err := info.vcs.Update(info.dir, isTag, updateTo); err == nil { fmt.Printf("updated hack version of %s to %s\n", info.module.Path, info.module.Version) return nil } if !info.alreadyExists { fmt.Printf("creating %s@%s\n", info.module.Path, info.module.Version) if err := createRepo(info); err != nil { return fmt.Errorf("cannot create repo: %v", err) } } else { fmt.Printf("fetching %s@%s\n", info.module.Path, info.module.Version) if err := info.vcs.Fetch(info.dir); err != nil { return err } } return info.vcs.Update(info.dir, isTag, updateTo) } func createRepo(info *moduleVCSInfo) error { // Some version control tools require the parent of the target to exist. parent, _ := filepath.Split(info.dir) if err := os.MkdirAll(parent, 0777); err != nil { return err } if err := info.vcs.Create(info.root.Repo, info.dir); err != nil { return errors.Wrap(err) } return nil } type moduleVCSInfo struct { // module holds the module information as printed by go list. module *listModule // alreadyExists holds whether the replacement directory already exists. alreadyExists bool // dir holds the path to the replacement directory. dir string // root holds information on the VCS root of the module. root *vcs.RepoRoot // vcs holds the implementation of the VCS used by the module. vcs VCS // VCSInfo holds information on the VCS tree in the replacement // directory. It is only filled in when alreadyExists is true. VCSInfo } // getVCSInfoForModule returns VCS information about the module // by inspecting the module path and the module's checked out // directory. func getVCSInfoForModule(m *listModule) (*moduleVCSInfo, error) { // TODO if module directory already exists, could look in it to see if there's // a single VCS directory and use that if so, to avoid hitting the network // for vanity imports. root, err := vcs.RepoRootForImportPath(m.Path, *printCommands) if err != nil { return nil, errors.Note(err, nil, "cannot find module root") } v, ok := kindToVCS[root.VCS.Cmd] if !ok { return nil, errors.Newf("unknown VCS kind %q", root.VCS.Cmd) } dir := moduleDir(m.Path) dirInfo, err := os.Stat(dir) if err != nil && !os.IsNotExist(err) { return nil, errors.Wrap(err) } if err == nil && !dirInfo.IsDir() { return nil, errors.Newf("%q is not a directory", dir) } info := &moduleVCSInfo{ module: m, root: root, alreadyExists: err == nil, dir: dir, vcs: v, } if !info.alreadyExists { return info, nil } // Remove the go.mod file if it was autogenerated so that the // normal VCS cleanliness detection works OK. removedGoMod, err := removeAutoGoMod(info) if err != nil { return nil, errors.Wrap(err) } info.VCSInfo, err = info.vcs.Info(dir) if err != nil { return nil, errors.Notef(err, nil, "cannot get VCS info from %q", dir) } if removedGoMod { // We removed the autogenerated go.mod file so add it back again. if err := ensureGoModFile(info.module.Path, info.dir); err != nil { return nil, errors.Wrap(err) } } return info, nil } // moduleDir returns the path to the directory to be // used for storing the module with the given path. func moduleDir(module string) string { // TODO decide what color this bikeshed should be. d := os.Getenv("GOHACK") if d == "" { d = filepath.Join(os.Getenv("HOME"), "gohack") } return filepath.Join(d, filepath.FromSlash(module)) } const debug = false func errorf(f string, a ...interface{}) { fmt.Fprintln(os.Stderr, fmt.Sprintf(f, a...)) if debug { for _, arg := range a { if err, ok := arg.(error); ok { fmt.Fprintf(os.Stderr, "error: %s\n", errors.Details(err)) } } } exitCode = 1 } func ensureGoModFile(modPath, dir string) error { modFile := filepath.Join(dir, "go.mod") if _, err := os.Stat(modFile); err == nil { return nil } if err := ioutil.WriteFile(modFile, []byte(autoGoMod(modPath)), 0666); err != nil { return errors.Wrap(err) } return nil } // removeAutoGoMod removes the module directory's go.mod // file if it looks like it's been autogenerated by us. // It reports whether the file was removed. func removeAutoGoMod(m *moduleVCSInfo) (bool, error) { modFile := filepath.Join(m.dir, "go.mod") data, err := ioutil.ReadFile(modFile) if err != nil { if !os.IsNotExist(err) { return false, errors.Wrap(err) } return false, nil } if string(data) != autoGoMod(m.module.Path) { return false, nil } if err := os.Remove(modFile); err != nil { return false, errors.Wrap(err) } return true, nil } // autoGoMod returns the contents of the go.mod file that // would be auto-generated for the module with the given // path. func autoGoMod(mpath string) string { return "// Generated by gohack; DO NOT EDIT.\nmodule " + mpath + "\n" } func isEmptyDir(dir string) (bool, error) { f, err := os.Open(dir) if err != nil { return false, errors.Wrap(err) } defer f.Close() _, err = f.Readdir(1) if err != nil && err != io.EOF { return false, errors.Wrap(err) } return err == io.EOF, nil } func copyAll(dst, src string) error { srcInfo, srcErr := os.Lstat(src) if srcErr != nil { return errors.Wrap(srcErr) } _, dstErr := os.Lstat(dst) if dstErr == nil { return errors.Newf("will not overwrite %q", dst) } if !os.IsNotExist(dstErr) { return errors.Wrap(dstErr) } switch mode := srcInfo.Mode(); mode & os.ModeType { case os.ModeSymlink: return errors.Newf("will not copy symbolic link") case os.ModeDir: return copyDir(dst, src) case 0: return copyFile(dst, src) default: return fmt.Errorf("cannot copy file with mode %v", mode) } } func copyFile(dst, src string) error { srcf, err := os.Open(src) if err != nil { return errors.Wrap(err) } defer srcf.Close() dstf, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return errors.Wrap(err) } defer dstf.Close() if _, err := io.Copy(dstf, srcf); err != nil { return fmt.Errorf("cannot copy %q to %q: %v", src, dst, err) } return nil } func copyDir(dst, src string) error { srcf, err := os.Open(src) if err != nil { return errors.Wrap(err) } defer srcf.Close() if err := os.Mkdir(dst, 0777); err != nil { return errors.Wrap(err) } for { names, err := srcf.Readdirnames(100) for _, name := range names { if err := copyAll(filepath.Join(dst, name), filepath.Join(src, name)); err != nil { return errors.Wrap(err) } } if err == io.EOF { break } if err != nil { return errors.Newf("error reading directory %q: %v", src, err) } } return nil } <file_sep>module github.com/rogpeppe/gohack require ( golang.org/x/tools v0.0.0-20180803180156-3c07937fe18c gopkg.in/errgo.v2 v2.0.1 )
31fe8a5773ef56a189cfc69285a5961c03a2ecbe
[ "Go Module", "Go" ]
2
Go
ebfe/gohack
102d9ffcbb7ff65427f32a994a16efacc461c76b
34323d1b65edad81654c6e6ee691b89481c1eb0a
refs/heads/master
<file_sep>//========NPM & Module Packages=========================== //imported twitter keys module var keys = require("./keys.js"); var request = require("request"); var Spotify = require("node-spotify-api"); var Twitter = require("twitter"); var fs = require("fs"); var twitterClient = new Twitter(keys.twitterKeys); var spotifyClient = new Spotify({ id: keys.spotifyKeys.client_ID, secret: keys.spotifyKeys.client_Secret, }); //==========Global Functions========================== function getTweets() { var params = { screen_name: 'UGA_FB_Thoughts', count: 20 }; twitterClient.get('statuses/user_timeline', params, function (error, tweets, response) { if (!error) { console.log("HERE ARE YOUR TWEETS:"); //console.log(tweets); for (var i = 0; i < tweets.length; i++) { //numbers each tweet. Adds 1 so numbering starts at 1 instead of 0--more human. console.log("Here is tweet " + [i + 1] + ":"); console.log(' "' + tweets[i].text + '" '); console.log("This tweet was sent at:"); console.log(tweets[i].created_at); console.log("=============================="); } } else { console.log(error); } }); } function getSpotifySongInfo() { var defaultSpotifySong = 'Ace of Base'; //4th node argument reserved for the song user wants to select var query = (process.argv[3] || defaultSpotifySong); spotifyClient.search({ type: 'track', query: query, limit: 1 }, function (err, data) { if (!err) { console.log("=============Artist==Track==Album==PreviewURL============================="); console.log("Artist: " + data.tracks.items[0].artists[0].name); console.log("Track: " + data.tracks.items[0].name); console.log("Album: " + data.tracks.items[0].name); console.log("Preview URL: " + data.tracks.items[0].preview_url); } else { console.log(err); } }); } function getMovieInfo() { var defaultMovie = 'Mr. Nobody'; //if there is a user provided argument that will be the movie searched for, otherwise uses default movie var userMovieSearch = (process.argv[3] || defaultMovie); // Request to the OMDB API with userMovieSearch specified var queryUrl = "http://www.omdbapi.com/?t=" + userMovieSearch + "&y=&plot=short&apikey=40e9cece"; // This line is just to help us debug against the actual URL. console.log(queryUrl); request(queryUrl, function (error, response, body) { // If the request is successful if (!error && response.statusCode === 200) { console.log("Title: " + JSON.parse(body).Title); console.log("Release Year: " + JSON.parse(body).Year); console.log("IMDB Rating: " + JSON.parse(body).Ratings[0].Value); console.log("Rotten Tomatoes Rating: " + JSON.parse(body).Ratings[1].Value); console.log("Country: " + JSON.parse(body).Country); console.log("Language: " + JSON.parse(body).Language); console.log("Plot: " + JSON.parse(body).Plot); console.log("Actors: " + JSON.parse(body).Actors); //uncomment JSON.parse(body) below to get other information from the API //console.log(JSON.parse(body)); } else { console.log(error); } }); } // reads txt file to get command to run function readTxtFileForCommand() { fs.readFile("random.txt", "utf8", function (error, data) { if (!error) { console.log(data); // takes the text file and splits the info from comma to comma into different positions in array var fileTextSplitIntoArr = data.split(","); console.log(fileTextSplitIntoArr); // converts the text file into format for query. var textFileArg1 = fileTextSplitIntoArr[0]; var textFileArg2 = fileTextSplitIntoArr[1]; // Grabs the 2nd index (fileTextSplitIntoArr[1]) position to use for query search var query = textFileArg2; //changed code to fix default issue which means I had to repeat this code here: BAD, I know! spotifyClient.search({ type: 'track', query: query, limit: 1 }, function (err, data) { if (!err) { console.log("=============Artist==Track==Album==PreviewURL============================="); console.log("Artist: " + data.tracks.items[0].artists[0].name); console.log("Track: " + data.tracks.items[0].name); console.log("Album: " + data.tracks.items[0].name); console.log("Preview URL: " + data.tracks.items[0].preview_url); } else { console.log(err); } }); } else { console.log(error); } }); } function startApp() { // takes users command which tells app which API to use var userSelectsAPI = process.argv[2]; //====conditional statements to select which API to use===== if (userSelectsAPI === "my-tweets") { getTweets(); } else if (userSelectsAPI === "spotify-this-song") { getSpotifySongInfo(); } else if (userSelectsAPI === "movie-this") { getMovieInfo(); } else if (userSelectsAPI === "do-what-it-says") { readTxtFileForCommand(); } else { console.log("You've entered an incorrect command. Please enter a correct command to proceed."); } } //=========App=Logistics===================================== startApp();
cbf5a2b55a4d3f37a3582c6225466206a4a61574
[ "JavaScript" ]
1
JavaScript
phiniezyc/liri-node-app
815716c85841a78cd898e8854fce21c7d810c713
24986b955a8646a56fba5e50260039f3b46d6cba
refs/heads/master
<repo_name>pkane/the-big-bet<file_sep>/scripts/main.js makeRequest = function (method, url) { return new Promise(function (resolve, reject) { let xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = function () { if (this.status >= 200 && this.status < 300) { resolve(xhr.response); } else { reject({ status: this.status, statusText: xhr.statusText }); } }; xhr.onerror = function () { reject({ status: this.status, statusText: xhr.statusText }); }; xhr.send(); }); } define(function (require) { const model = require('./model'); const gamesFeed = 'https://s3-eu-west-1.amazonaws.com/fa-ads/frontend/matches.json'; // Our App const App = function() { this.appContainer = '#app'; this.loaderPage = model.loaderPage; this.betPage = model.betPage; this.matchPage = model.matchPage; this.winPage = model.winPage; this.resultsPage = model.resultsPage; this.betModel = model.betModel; this.matches = model.matchesArray; this.importPageData(this.loaderPage, this.appContainer); this.getGameFeeds(gamesFeed); // this.getMatchupData(gamesFeed); // After 3 sec, hide the loader screen window.setTimeout(()=>{ this.unloadPageData(this.activePage, this.appContainer).then(()=>{ this.importPageData(this.betPage, this.appContainer); this.initEventHandlers(); }); }, 3000); } // GET request App.prototype.openAjaxCall = function(template) { let xhttp = new XMLHttpRequest(); xhttp.open("GET", template, false); xhttp.send(); let responseText = xhttp.responseText; return responseText; } // GET request with callback App.prototype.openAjaxCallWithCallback = function(template, callback) { let func = callback; makeRequest('GET', template) .then(function (datums) { func(datums); }) } // Load next view, create DOM for new controller App.prototype.importPageData = function(page, container) { // Initialize a new document element and set it's contents to the content of #app let template = page.template; let getTemplateContent = this.openAjaxCall(template); let newEle = document.createElement('template'); newEle.innerHTML = getTemplateContent; let clone = document.importNode(newEle.content, true); Expand(clone, page); document.querySelector(container).appendChild(clone); this.activePage = page; } // Clear current view App.prototype.unloadPageData = function(page, container) { var activeEle = document.querySelector('#'+this.activePage.id); activeEle.classList.add('fade-out'); return new Promise(function(resolve, reject){ window.setTimeout(()=> { activeEle.style.display = 'none'; activeEle.parentNode.removeChild(activeEle); resolve(); }, 300); }) } // Set up event listeners App.prototype.initEventHandlers = function(e) { let submitLink = document.getElementsByClassName('submit-link')[0]; let pickLinks = document.querySelectorAll('.pick-link'); if (pickLinks.length > 0) { for (let i = pickLinks.length - 1; i >= 0; i--) { pickLinks[i].addEventListener("click", (e)=> { pickLinks.forEach((ele)=> { ele.classList.remove('active'); }); this.storePick(e); }); } } if (submitLink) { submitLink.addEventListener("click", this.formSequence.bind(this)); // submitLink.addEventListener("click", getTargetValue); } } // Allows the insertion of text into a container/tag ele App.prototype.insertText = function(tag, text, container) { let para = document.createElement(tag); let pickText = document.createTextNode(text); para.appendChild(pickText); container.insertBefore(para, container.childNodes[container.childNodes.length-1]); } // Get the game JSON and then set up the match pages model App.prototype.getGameFeeds = function(data) { this.openAjaxCallWithCallback(data, (data)=> { this.matches = JSON.parse(data).matches; console.log(this.matches); this.currentMatchIndex = 0; this.setUpMatchPages(this.currentMatchIndex); }); } // Set our current match from the data App.prototype.setUpMatchPages = function(index) { this.currentMatch = this.matchPage.form.match = this.matches[index]; } // The Main App function to handle View logic App.prototype.formSequence = function(event) { event.preventDefault(); let form = event.target.parentElement; let formName = form.classList[0]; let curValue = form.getElementsByClassName('text-input-value')[0].value; if (curValue == '' || curValue <= 0) { return false; } let nextPage = this.matchPage; // Risk Form if (formName === 'risk-form') { this.betModel.userRisk = this.winPage.bet.value = eval(curValue); this.unloadPageData(this.activePage, this.appContainer).then(()=> { this.importPageData(this.matchPage, this.appContainer); this.initEventHandlers(); }); } // Matches Form if (formName === 'match-form') { this.currentMatchIndex++; if (this.currentMatchIndex <= this.matches.length-1) { this.setUpMatchPages(this.currentMatchIndex); } else { // We've gone through all matches // Go to Payout screen this.resultsPage.bet.value = ('$' + this.betModel.userRisk.toFixed(2)); this.resultsPage.win.value = this.betModel.userPayout = ('$' + this.calcParlay(this.betModel.picksArray)); nextPage = this.resultsPage; } this.unloadPageData(this.activePage, this.appContainer).then(()=> { this.importPageData(nextPage, this.appContainer); this.initEventHandlers(); }); } } App.prototype.storePick = function(event) { event.preventDefault(); let target = event.target; let pick = target.getAttribute('value') ? target.getAttribute('value') : '0'; let valStore = document.querySelector('.text-input-value'); if (pick) { if (this.betModel.picksArray.length === this.currentMatchIndex + 1) { this.betModel.picksArray[this.currentMatchIndex] = pick; } else { this.betModel.picksArray.push(pick); } } target.classList.add('active'); valStore.value = pick; } // This is our humble evaluator // for just taking in a odds, win, and outputting the multiplier // e.g. Giants -150 : 250/150 = 1.6666 // e.g. Dolphins +170 : 270/100 = 2.7 // App.prototype.evalPick = function(odds) { // var absOdds = Math.abs(odds); // var payout = (absOdds + 100); // var multiplier = Math.abs(absOdds === odds ? (payout / 100) : (payout / absOdds)); // return multiplier; // } App.prototype.calcParlay = function(array) { let total = 1; for (let i = array.length - 1; i >= 0; i--) { total = total * eval(array[i]); } return (total * this.betModel.userRisk).toFixed(2); } var app = new App(); }); <file_sep>/scripts/model.js define(function () { var Model = function() { // Our data set this.loaderPage = { id: 'loaderPage', template: 'templates/loader-page-controller.html', intro: 'Bet today\'s big matches and win big!', logo: { src: 'logo.svg', url: '' }, text_logo: { src: 'text-logo.svg', url: '' }, headline_text: 'Welcome to', headline_span: 'The Big Bet', text_soon: '(coming soon)' }; this.betPage = { id: 'betPage', template: 'templates/bet-page-controller.html', logo: { src: 'logo.svg', url: '' }, text: 'We\'ll be picking from a few of today\'s biggest matches.', form: { risk: { text: 'How much do you want to bet?', value : 0 } } }; this.matchPage = { id: 'matchPage', template: 'templates/match-page-controller.html', logo: { src: 'logo.svg', url: '' }, gameId: 0, text: 'Game ', form: { match : { id: 123456, kickoff: "Thursday 20:45", homeTeam: "Manchester United", awayTeam: "Liverpool", odds: { 1: "2.10", 2: "2.62", x: "3.30" } }, } }; this.winPage = { id: 'winPage', template: 'templates/win-page-controller.html', intro: 'We got you covered', logo: { src: 'logo.svg', url: '' }, bet: { text: 'bet', value: this.betPage.form.risk.value }, form: { win: { text: 'How much do you want to win?', value : 0, } } }; this.resultsPage = { id: 'resultsPage', template: 'templates/results-page-controller.html', logo: { src: 'logo.svg', url: '' }, bet: { text: 'bet', value: this.betPage.form.risk.value }, win: { text: 'win', value: this.winPage.form.win.value }, form: { risk: { text: 'Blah', value : 0 } } }; this.matchesArray = []; this.betModel = { conservativeArray : [], aggressiveArray : [], picksArray : [], picksMultiplier : 0, userRisk : 0, userPayout : 0 } this.activePage = { }; } return new Model; }); <file_sep>/README.md # the-big-bet Pick from three of the day's biggest soccer matches for a big payout! To run, simply use http-server: - npm install http-server -g Then: - http-server Next load the local URL and port in a browser: `http://127.0.0.1:8080/` <file_sep>/scripts/games.js // Onboarding data define(function (require) { var gamesFeed = { id: 'gamesFeed', matchups: [ { "DATE": "2/27/2016", "TIME": "8:35 PM", "VISITOR_CITY": "Golden State", "VISITOR_MASCOT": "Warriors", "HOME_CITY": "Oklahoma City", "HOME_MASCOT": "Thunder", "VISITOR_ML": -165, "HOME_ML": 145, "VISITOR_SPREAD": -3, "HOME_SPREAD": 3, "VISITOR_VIG": -110, "HOME_VIG": -110, "OU": 235, "VISITOR_OU_VIG": -110, "HOME_OU_VIG": -110, "VISITOR_SCORE": 121, "HOME_SCORE": 118 }, { "DATE": "3/1/2016", "TIME": "10:35 PM", "VISITOR_CITY": "Atlanta", "VISITOR_MASCOT": "Hawks", "HOME_CITY": "Golden State", "HOME_MASCOT": "Warriors", "VISITOR_ML": 195, "HOME_ML": -235, "VISITOR_SPREAD": 5.5, "HOME_SPREAD": -5.5, "VISITOR_VIG": -110, "HOME_VIG": -110, "OU": 213.5, "VISITOR_OU_VIG": -110, "HOME_OU_VIG": -110, "VISITOR_SCORE": 105, "HOME_SCORE": 109 }, { "DATE": "3/3/2016", "TIME": "10:40 PM", "VISITOR_CITY": "Oklahoma City", "VISITOR_MASCOT": "Thunder", "HOME_CITY": "Golden State", "HOME_MASCOT": "Warriors", "VISITOR_ML": 260, "HOME_ML": -325, "VISITOR_SPREAD": 7.5, "HOME_SPREAD": -7.5, "VISITOR_VIG": -110, "HOME_VIG": -110, "OU": 229.5, "VISITOR_OU_VIG": -110, "HOME_OU_VIG": -110, "VISITOR_SCORE": 106, "HOME_SCORE": 121 }, { "DATE": "3/4/2016", "TIME": "8:35 PM", "VISITOR_CITY": "Houston", "VISITOR_MASCOT": "Rockets", "HOME_CITY": "Chicago", "HOME_MASCOT": "Bulls", "VISITOR_ML": -120, "HOME_ML": 100, "VISITOR_SPREAD": -1.5, "HOME_SPREAD": 1.5, "VISITOR_VIG": -110, "HOME_VIG": -110, "OU": 216.5, "VISITOR_OU_VIG": -110, "HOME_OU_VIG": -110, "VISITOR_SCORE": 0, "HOME_SCORE": 0 } ] }; return gamesFeed; });
c93caab76f9bc36d031a897ff37639ad00c9dce2
[ "JavaScript", "Markdown" ]
4
JavaScript
pkane/the-big-bet
c3208b22bd37f0b6a14c59078a23d5779219f51b
77bae4b3085b9ac174f55255387b54bf1a92aca4
refs/heads/master
<repo_name>lizdenhup/js-tictactoe-rails-api-v-000<file_sep>/app/assets/javascripts/tictactoe.js //starting conditions var turn = 0; var currentGame = undefined; //collection of winning indices var combos = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [6, 4, 2], [0, 3, 6], [1, 4, 7], [2, 5, 8] ]; $(document).ready(function() { attachListeners(); }) function attachListeners() { $("td").click(function(event) { cell = event.target doTurn(cell) }); $('#previous').click(function(event) { previous(); }); $('#save').click(function(event) { save(); }); }; function player() { if (turn % 2 == 0) { return 'X' } else { return 'O' }; }; var message = function(input) { $('#message').html(input); } function state() { var board = [] $("td").each(function(i) { board.push($(this).text()) }) return board; }; var updateState = function(cell) { if ($(cell).html() === "") { $(cell).html(player()); } else { message("That space is taken. Please choose another.") } }; function doTurn(cell) { updateState(cell); if(checkWinner()) { save(true) resetBoard(); } else if(fullBoard()) { save(true) resetBoard(); message('Tie game') } else { turn += 1; } }; //functions related to checking if the game is over or has been won//// function fullBoard() { var full = true $('td').each(function() { if (this.innerHTML === "") { return full = false; } }) return full } function checkState(combo, board){ if (board[combo[0]] !== "" && board[combo[0]] === board[combo[1]] && board[combo[1]] === board[combo[2]]) { return true; } }; function checkWinner() { for(i = 0; i < combos.length; i++){ if (checkState(combos[i], state())){ message('Player ' + player() + ' Won!') return true; } } return false; }; /////++++++++++++++++++++++++++++++++////////// //methods related to making the AJAX calls var resetBoard = function() { turn = 0; currentGame = undefined; $('td').empty(); } function previous() { $.getJSON("/games", function(data) { index(data.games) }) } function index(games) { var doc = $() games.forEach(function(game) { doc = doc.add(show(game)); }) $("#games").html(doc); } function show(game) { return $('<li>', {'data-state': game.state, 'data-gameid': game.id, text: game.id}); } function save(reset) { var url, method; if(currentGame) { url = "/games/" + currentGame method = "PATCH" } else { url = "/games" method = "POST" } $.ajax({ url: url, method: method, dataType: "json", data: { game: { state: state() } }, success: function(data) { if(reset) { currentGame = undefined; } else { currentGame = data.game.id; } } }) };
178f5f9857604d793387ae7901e55d8e37a1336c
[ "JavaScript" ]
1
JavaScript
lizdenhup/js-tictactoe-rails-api-v-000
c7477dabad37d0ca40f763c35a6a603ba7c8489d
a7dd066f8e8f01c3d0e9873506b05aa8e4c02cae
refs/heads/master
<file_sep>/* * * Module dependencies * */ var config = require('./config/config'); var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var app = express(); // sets up the server mongoose.connect(config.db); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // setting up passport authentication require('./routes/routes')(app); app.use(express.static(__dirname + '/public')); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); console.log("example is now running"); app.listen(3000); <file_sep> var mongoose = require('mongoose'); var assert = require('chai').assert; var should = require('chai').should(); var expect = require('chai').expect; var config = require('../config/config'); var Todo = require('../models/todo'); mongoose.connect(config.db); function makeTitle(len){ var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < len; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } describe("tests update feature", function(){ before(function(done) { mongoose.createConnection(config.db, function(error) { (error ? console.error('Error while connecting:\n%\n', error) : console.log('connected')); done(error); }); randTitle = makeTitle(5); }); it("should insert an update object", function(){ var todo = new Todo({ text: "test", author: randTitle }); todo.save(function(err){ if(err){ console.log(err); } console.log("success"); }); }); it("finds inserted object", function(){ Todo.findOne(randTitle, function(err,todo){ if(err){ console.log(err); } should.exist(todo); console.log(todo); }); }); }); <file_sep># "Introduction to NodeJS" presentation by <NAME> on February 25, 2015 at SSEUG meeting Meeting agenda: http://srqsoftware.github.io/02-25-2015_Introduction_to_NodeJS/ Presentation slides: https://docs.google.com/presentation/d/1dA4Y9PFDdE7lB_v-UzP1ZoVcHWvcs8sFtobjtKRKXss/edit?pli=1#slide=id.p # Tools Used [Mongoose to connect with MongoDB](http://mongoosejs.com/docs/index.html) [Express for rapid server development](http://expressjs.com/) [Mocha for testing](http://mochajs.org/) [Chaijs for assertions](http://chaijs.com/) [NPM for managing packages and the node project](https://www.npmjs.com/) # Self Learning [socket.io](http://socket.io/) [DigitalOcean for deployment](https://www.digitalocean.com/)
5e0d89dd19267c8538350918e5054a8492ac3f87
[ "JavaScript", "Markdown" ]
3
JavaScript
srqsoftware/02-25-2015_Introduction_to_NodeJS
d72c104c4dfbb29ee1ecc6e9215efa75512284bb
3324e71409965af5a2eb0d38f64216ab42008b8c
refs/heads/master
<file_sep>x = int(input()) y = int(input()) _sum = 0 if x > y: for i in range(y, x+1): if i % 13 == 0: continue else: _sum += i if x < y: for i in range(x, y+1): if i % 13 == 0: continue else: _sum += i print(_sum)<file_sep>n = int(input()) tot_cobaias, tot_c, tot_r, tot_s = 0, 0, 0, 0 for i in range(n): qnt, tip = map(str, input().split()) qnt = int(qnt) tot_cobaias += qnt if tip == 'C': tot_c += qnt if tip == 'R': tot_r += qnt if tip == 'S': tot_s += qnt pc_c = (tot_c * 100) / tot_cobaias pc_r = (tot_r * 100) / tot_cobaias pc_s = (tot_s * 100) / tot_cobaias print(f"Total: {tot_cobaias} cobaias\n" f"Total de coelhos: {tot_c}\n" f"Total de ratos: {tot_r}\n" f"Total de sapos: {tot_s}\n" f"Percentual de coelhos: {pc_c:.2f} %\n" f"Percentual de ratos: {pc_r:.2f} %\n" f"Percentual de sapos: {pc_s:.2f} %") <file_sep>list1 = [] for i in range(2, 101): list1.append(i) S = 1 for j in list1: S += 1 / j print("{:.2f}".format(S)) <file_sep>salary = float(input()) readj_index = 0 if (salary <= 400): readj_index = 0.15 elif (salary >= 400.01 and salary <= 800): readj_index = 0.12 elif (salary >= 800.01 and salary <= 1200): readj_index = 0.1 elif (salary >= 1200.01 and salary <= 2000): readj_index = 0.07 elif (salary > 2000): readj_index = 0.04 new_salary = (salary*readj_index) + salary diff = new_salary - salary percentage = int(readj_index * 100) print(f"Novo salario: {new_salary:.2f}") print(f"Reajuste ganho: {diff:.2f}") print(f"Em percentual: {percentage} %") <file_sep>{\rtf1\ansi\ansicpg1252\cocoartf2580 \cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} {\*\expandedcolortbl;;} \paperw11900\paperh16840\margl1440\margr1440\vieww11520\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 \f0\fs24 \cf0 SELECT id, name\ FROM products\ WHERE price < 10 OR price > 100;}<file_sep>n = int(input()) x = 1 for i in range(n): print(f"{x} {pow(x, 2)} {pow(x, 3)}") x += 1 <file_sep>def checks_continue(): x = int(input("Novo grenal (1-sim 2-nao)\n")) return x _continue = 1 gr_wins, in_wins, ties = 0, 0, 0 total_grenais = 0 while _continue == 1: in_goals, gr_goals = map(int, input().split()) if gr_goals > in_goals: gr_wins += 1 elif gr_goals < in_goals: in_wins += 1 else: ties += 1 total_grenais += 1 _continue = checks_continue() print(f"{total_grenais} grenais\n" f"Inter:{in_wins}\n" f"Gremio:{gr_wins}\n" f"Empates:{ties}") if gr_wins > in_wins: print("Gremio venceu mais") elif gr_wins < in_wins: print("Inter venceu mais") else: print("Nao houve vencedor") <file_sep>n = int(input()) p1, p2, p3, = 2, 3, 5 for i in range(n): v1, v2, v3 = map(float, input().split()) avg = ((v1*p1)+(v2*p2)+(v3*p3)) / (p1+p2+p3) print("{:.1f}".format(avg)) <file_sep>from datetime import datetime hs, he, ms, me = map(int, input().split()) s1 = f'{hs}:{ms}' s2 = f'{he}:{me}' FMT = '%H:%M' tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT) print(tdelta)<file_sep>def pass_check(): inpt = int(input()) if inpt != 2002: print("Senha Invalida") return pass_check() else: print("Acesso Permitido") passw = pass_check()<file_sep>a = [] for i in range(0, 100): x = float(input()) a.append(x) pos = 0 for j in a: if j <= 10: print(f"A[{pos}] = {j}") pos += 1 <file_sep>x = int(input()) n = [x] for i in range(0, 9): x *= 2 n.append(x) pos = 0 for j in n: print(f"N[{pos}] = {j}") pos += 1 <file_sep>x = int(input()) while x != 0: _sum = 0 aux = x + 10 if x % 2 == 0: for i in range(x, aux, 2): _sum += i else: for i in range(x+1, aux, 2): _sum += i print(_sum) x = int(input()) <file_sep>ent = float(input()) if ((ent >= 0) and (ent <= 25)): print("Intervalo [0,25]") elif ((ent > 25) and (ent <= 50)): print("Intervalo (25,50]") elif ((ent > 50) and (ent <= 75)): print("Intervalo (50,75]") elif ((ent > 75) and (ent <= 100)): print("Intervalo (75,100]") else: print("Fora de intervalo") <file_sep>a, b, c = map(float, input().split()) sides = [a, b, c] sorted_sides = sorted(sides) is_triangle = (sorted_sides[0] + sorted_sides[1]) > sorted_sides[2] if is_triangle: perimeter = a + b + c print(f"Perimetro = {perimeter:.1f}") else: area = ((a+b)*c) / 2 print(f"Area = {area:.1f}") <file_sep>number_list = [] for number in range(0, 6): number = float(input()) number_list.append(number) pos_values = 0 for number in number_list: if number > 0: pos_values += 1 print(f"{pos_values} valores positivos") <file_sep>x = int(input()) lis = [] for i in range(1, x+1): if x % i == 0: lis.append(i) for i in lis: print(i)<file_sep>a, b, c = map(float, input().split()) _list = [a, b, c] dec = sorted(_list, reverse=True) not_a_triangle = dec[0] >= dec[1] + dec[2] rectangle_triangle = pow(dec[0], 2) == pow(dec[1], 2) + pow(dec[2], 2) obtuse_triangle = pow(dec[0], 2) > pow(dec[1], 2) + pow(dec[2], 2) and not not_a_triangle acute_triangle = pow(dec[0], 2) < pow(dec[1], 2) + pow(dec[2], 2) equilateral_triangle = (a == b) and (b == c) and (c == a) isosceles_triangle = (a == b) or (b == c) or (c == a) if not_a_triangle: print("NAO FORMA TRIANGULO") if rectangle_triangle: print("TRIANGULO RETANGULO") if obtuse_triangle: print("TRIANGULO OBTUSANGULO") if acute_triangle: print("TRIANGULO ACUTANGULO") if equilateral_triangle: print("TRIANGULO EQUILATERO") if isosceles_triangle and not equilateral_triangle: print("TRIANGULO ISOSCELES") <file_sep>n = int(input()) # if n is even: if n % 2 == 0: for num in range(2, n+1, 2): print(f"{num}^2 =", pow(num, 2)) # if in is odd: else: for num in range(2, n, 2): print(f"{num}^2 =", pow(num, 2)) <file_sep>lis1 = [] for i in range(3, 40, 2): lis1.append(i) lis2 = [] aux = 1 for i in range(len(lis1)): aux *= 2 lis2.append(aux) S = 1 for a, b in zip(lis1, lis2): S += (a / b) print("{:.2f}".format(S)) <file_sep># URI Challenges The purpose of this repository is to save my challenges from urionlinejudge.com and also to practice git and github commands.<file_sep>x = int(input()) _sum = 0 counter = 0 while x >= 0: _sum += x counter += 1 x = int(input()) _avg = _sum / counter print(f"{_avg:.2f}") <file_sep>x, y = map(int, input().split()) i = 1 while i != y+1: counter = 0 for a in range(0, x): if counter == x - 1: print(i) else: print(i, end=' ') i += 1 counter += 1 <file_sep>i, j = -1, 7 while i != 11 and j != 17: i += 2 for a in range(0, 3): print(f"I={i} J={j}") j -= 1 j += 5 <file_sep>vet = [] for i in range(0, 10): x = int(input()) if x <= 0: x = 1 vet.append(x) pos = 0 for j in vet: print(f"X[{pos}] = {j}") pos += 1 <file_sep>def checks_grade(): x = float(input()) if 0 <= x <= 10: return x else: print("nota invalida") return checks_grade() n1 = checks_grade() n2 = checks_grade() _avg = (n1 + n2) / 2 print(f"media = {_avg:.2f}") <file_sep>t = int(input()) counter = 0 # while counter < t: pa, pb, g1, g2 = map(float, input().split()) pa = int(pa) pb = int(pb) <file_sep>x = int(input()) y = int(input()) _sum = 0 # if the first one is lesser than the second if x < y: for i in range(x+1, y): if i % 2 != 0: _sum += i # if the first one is greater than the second elif x > y: for i in range(y+1, x): if i % 2 != 0: _sum += i print(_sum)<file_sep>qnt = int(input()) _in = 0 _out = 0 for i in range(qnt): num = int(input()) if 10 <= num <= 20: _in += 1 else: _out += 1 print(f"{_in} in\n" f"{_out} out") <file_sep># storing values _list = [] for num in range(5): num = int(input()) _list.append(num) # counting evens and odds evens, odds = 0, 0 for num in _list: if num % 2 == 0: evens += 1 else: odds += 1 # counting positives and negatives pos, neg = 0, 0 for num in _list: if num > 0: pos += 1 elif num < 0: neg += 1 print(f"{evens} valor(es) par(es)\n" f"{odds} valor(es) impar(es)\n" f"{pos} valor(es) positivo(s)\n" f"{neg} valor(es) negativo(s)")<file_sep>codigo, quantidade = input().split() codigo = int(codigo) quantidade = int(quantidade) if (codigo == 1): valor = 4.0 if (codigo == 2): valor = 4.5 if (codigo == 3): valor = 5.0 if (codigo == 4): valor = 2.0 if (codigo == 5): valor = 1.5 total = valor * quantidade print(f"Total: R$ {total:.2f}") <file_sep>n = int(input()) x = 1 for i in range(0, n*2): print(f"{x} {pow(x,2)} {pow(x,3)}") x += 1 <file_sep>n = int(input()) x = 0 i = 0 while i < n: x = int(input()) if x == 2 or x == 3: print(f"{x} eh primo") else: for i += 1<file_sep>num = int(input()) counter = 0 for i in range(num, num+12): if i % 2 != 0: print(i) <file_sep>start, end = map(int, input().split()) total = 0 if (start > end): total = (24 - start) + end elif (start < end): total = end - start else: total = 24 print(f"O JOGO DUROU {total} HORA(S)") <file_sep>n = [] for i in range(0, 20): x = int(input()) n.append(x) <file_sep>qnt = int(input()) for i in range(qnt): x, y = map(int, input().split()) try: div = x / y print(div) except ZeroDivisionError: print("divisao impossivel")<file_sep>n = int(input()) fib = [0, 1, 1] for i in range(0, n-3): x = fib[-1] + fib[-2] fib.append(x) print(*fib)<file_sep>a, b, c = map(int, input().split()) _list = [a, b, c] sorted_list = sorted(_list) for number in sorted_list: print(number) print() for number in _list: print(number) <file_sep># i = -0.2 # j = 0 # # conv = i == 0.0 # # counter = 0 # while counter < 12:# i != 2.2: # i += 0.2 # j = 0 # j += i # for a in range(3): # j += 1 # if conv: # print(f"I={int(i)} J={int(j)}") # else: # print(f"I={i} J={j}") # counter += 1 i = 0 j = 1 while i != 2.2: for a in range(3): print(f"I={i} J={j}") j += 1 + i i += 0.2 <file_sep>for number in range(2, 101, 2): print(number) <file_sep>n = int(input()) n += 1 lis = [] for i in range(1, n): lis.append(i) fat = 1 for i in lis: fat *= i print(fat)<file_sep>{\rtf1\ansi\ansicpg1252\cocoartf2580 \cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} {\*\expandedcolortbl;;} \paperw11900\paperh16840\margl1440\margr1440\vieww11520\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 \f0\fs24 \cf0 SELECT name\ FROM customers\ WHERE state = 'RS';}<file_sep>def checks_cod(): x = int(input()) if 1 <= x <= 4: return x else: return checks_cod() cod = int(input()) alc, gas, die = 0, 0, 0 while cod != 4: if cod == 1: alc += 1 if cod == 2: gas += 1 if cod == 3: die += 1 cod = checks_cod() print("MUITO OBRIGADO\n" f"Alcool: {alc}\n" f"Gasolina: {gas}\n" f"Diesel: {die}") <file_sep>m, n = map(int, input().split()) while m > 0 and n > 0: menor, maior = 0, 0 if m > n: maior = m menor = n else: maior = n menor = m _list = [] for num in range(menor, maior+1): _list.append(num) _sum = sum(_list) sorted_list = sorted(_list) print(*sorted_list, f"Sum={_sum}") m, n = map(int, input().split())<file_sep>x, y = map(float, input().split()) if ((x == 0) and (y == 0)): print("Origem") if ((x == 0) and (y != 0)): print("Eixo Y") if ((y == 0) and (x != 0)): print("Eixo X") if ((x > 0) and (y > 0)): print("Q1") if ((x < 0) and (y > 0)): print("Q2") if ((x < 0) and (y < 0)): print("Q3") if ((x > 0) and (y < 0)): print("Q4") <file_sep>n = int(input()) i = 0 while i < n: fatores = [] x = int(input()) for j in range(x-1, 0, -1): if x % j == 0: fatores.append(j) summ = sum(fatores) if summ == x: print(f"{x} eh perfeito") else: print(f"{x} nao eh perfeito") i += 1 <file_sep>n = int(input()) counter = 0 while counter < n: x, y = map(int, input().split()) aux = y _sum = 0 if x % 2 == 0: y = x + (aux*2) for i in range(x+1, y, 2): if i % 2 != 0: _sum += i else: y = x + (aux*2) for i in range(x, y, 2): if i % 2 != 0: _sum += i print(_sum) counter += 1 <file_sep>a, b = map(int, input().split()) values = [a, b] sorted_values = sorted(values) if (sorted_values[1] % sorted_values[0] == 0): print("Sao Multiplos") else: print("Nao sao Multiplos") <file_sep>N1, N2, N3, N4 = map(float, input().split()) N5 = 0 media = ((N1*2) + (N2*3) + (N3*4) + N4) / 10 print(f"Media: {media:.1f}") if (media >= 7): print("Aluno aprovado.") elif (media < 5): print("Aluno reprovado.") elif ((media >= 5) and (media < 7)): print("Aluno em exame.") N5 = float(input()) print(f"Nota do exame: {N5}") media = (media + N5) / 2 if (media >= 5): print("Aluno aprovado.") else: print("Aluno reprovado.") print(f"Media final: {media:.1f}") <file_sep>def checks_grade(): x = float(input()) if 0 <= x <= 10: return x else: print("nota invalida") return checks_grade() def checks_cont(): x = input("novo calculo (1-sim 2-nao)\n") if x != '1' and x != '2': return checks_cont() else: return x cont = '1' while cont != '2': n1 = checks_grade() n2 = checks_grade() _avg = (n1+n2) / 2 print(f"media = {_avg:.2f}") cont = checks_cont() <file_sep>n = int(input()) x = 1 for i in range(n): print(f"{x} {x+1} {x+2} PUM") x += 4
e43b1fa4583706cdc1f8c1e0c9d81426c61949e0
[ "Markdown", "SQL", "Python" ]
52
Python
kaiocp/uri-challenges
63434662946848f3d90a10d7ffbcd4158377140b
2634279a795e56e5a14cfbbb561db6b4432553cc
refs/heads/master
<file_sep>bluetooth.onBluetoothConnected(() => { basic.showLeds(` . # # . . . # . # . . # # . . . # . # . . # # . . `) }) bluetooth.onBluetoothDisconnected(() => { basic.showLeds(` . # . # . . # . # . . . . . . # . . . # . # # # . `) }) sbrick.onMeasurement(() => { if (sbrick.measuredPort() == 0) { led.plotBarGraph( sbrick.measuredValue() - 200, 250 ) } }) sbrick.onConnected(() => { basic.showLeds(` . # # # . . # . . . . . # . . . . . # . . # # # . `) sbrick.startMeasurement(0) }) basic.showLeds(` . # . # . . # . # . . . . . . # . . . # . # # # . `) sbrick.connect("SBrick")
c60a83f06357eaa49d874b5693a0c9adeb6dc9c8
[ "JavaScript" ]
1
JavaScript
arionlos/new
6597013a88f255770a9637e9014ed340b13d1fd9
ed18d162bd8365cd44eef54c9adaabb1f35e7120
refs/heads/master
<file_sep>'use strict'; (function () { /** * Реализует возможность перетаскивания окна настроек персонажа * @param {Object} evt - объект события 'mousedown' */ var onMouseDown = function (evt) { var moving = false; var start = { x: evt.clientX, y: evt.clientY }; /** * Задает окну настроек персонажа новые координаты * @param {Object} moveEvt - объект события 'mousemove' */ var onMouseMove = function (moveEvt) { moving = true; var shift = { x: start.x - moveEvt.clientX, y: start.y - moveEvt.clientY }; start = { x: moveEvt.clientX, y: moveEvt.clientY }; playerSettings.style.top = (playerSettings.offsetTop - shift.y) + 'px'; playerSettings.style.left = (playerSettings.offsetLeft - shift.x) + 'px'; }; /** * Удаляет обработчики событий 'mousemove' и 'mouseup' */ var onMouseUp = function () { /** * Отменяет действие по умолчанию * @param {Object} clickEvt - объект события 'click' */ var onSettingsMoverClick = function (clickEvt) { clickEvt.preventDefault(); settingsMover.removeEventListener('click', onSettingsMoverClick); }; if (moving) { settingsMover.addEventListener('click', onSettingsMoverClick); } document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); }; document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp); }; var playerSettings = document.querySelector('.setup'); var settingsMover = playerSettings.querySelector('.upload'); window.movePopup = { playerSettings: playerSettings, settingsMover: settingsMover, onMouseDown: onMouseDown }; })(); <file_sep>'use strict'; (function () { var ESC_KEYCODE = 27; var ENTER_KEYCODE = 13; var PLAYER_SETTINGS_LEFT = '50%'; var PLAYER_SETTINGS_TOP = '80px'; /** * Добавляет открытие окна по клику */ var onOpenSettingsClick = function () { openPopup(); }; /** * Открывает окно настроек по нажатию на Enter * @param {Object} evt - объект события 'keydown' */ var onOpenSettingsEnterPress = function (evt) { if (evt.keyCode === ENTER_KEYCODE) { openPopup(); } }; /** * Закрывает окно настроек по клику */ var onCloseSettingsClick = function () { closePopup(); }; /** * Закрывает окно настроек по нажатию на Enter * @param {Object} evt - объект события 'keydown' */ var onCloseSettingsEnterPress = function (evt) { if (evt.keyCode === ENTER_KEYCODE) { closePopup(); } }; /** * Закрывает окно настроек по нажатию на ESC * @param {Object} evt - объект события 'keydown' */ var onPopupEscPress = function (evt) { if (evt.keyCode === ESC_KEYCODE && document.activeElement !== userNameField) { closePopup(); } }; /** * Добавляет обработчики открытия окна настроек персонажа */ var openPopupListeners = function () { openSettings.addEventListener('click', onOpenSettingsClick); openSettingsIcon.addEventListener('keydown', onOpenSettingsEnterPress); }; /** * Удаляет обработчики открытия окна настроек персонажа */ var closePopupListeners = function () { openSettings.removeEventListener('click', onOpenSettingsClick); openSettingsIcon.removeEventListener('keydown', onOpenSettingsEnterPress); }; /** * Открывает окно настроек персонажа, добавляет обработчики событий внутри него, удаляет обработчики открытия окна */ var openPopup = function () { window.movePopup.playerSettings.style.top = PLAYER_SETTINGS_TOP; window.movePopup.playerSettings.style.left = PLAYER_SETTINGS_LEFT; window.movePopup.playerSettings.classList.remove('hidden'); window.wizards.submitButton.disabled = false; window.wizards.form.addEventListener('submit', window.wizards.onFormSubmit); window.avatar.fileChooser.addEventListener('change', window.avatar.onFileChooserChange); window.color.wizardCoat.addEventListener('click', window.color.onWizardCoatClick); window.color.wizardEyes.addEventListener('click', window.color.onWizardEyesClick); window.color.wizardFireball.addEventListener('click', window.color.onWizardFireballClick); document.addEventListener('keydown', onPopupEscPress); closeSettings.addEventListener('click', onCloseSettingsClick); closeSettings.addEventListener('keydown', onCloseSettingsEnterPress); window.movePopup.settingsMover.addEventListener('mousedown', window.movePopup.onMouseDown); window.drag(artifacts, backpackPockets); closePopupListeners(); }; /** * Закрывает окно настроек персонажа, удаляет обработчики событий внутри него, добавляет обработчики открытия окна */ var closePopup = function () { window.movePopup.playerSettings.classList.add('hidden'); window.wizards.form.removeEventListener('submit', window.wizards.onFormSubmit); window.avatar.fileChooser.removeEventListener('change', window.avatar.onFileChooserChange); window.color.wizardCoat.removeEventListener('click', window.color.onWizardCoatClick); window.color.wizardEyes.removeEventListener('click', window.color.onWizardEyesClick); window.color.wizardFireball.removeEventListener('click', window.color.onWizardFireballClick); document.removeEventListener('keydown', onPopupEscPress); closeSettings.removeEventListener('click', onCloseSettingsClick); closeSettings.removeEventListener('keydown', onCloseSettingsEnterPress); window.movePopup.settingsMover.removeEventListener('mousedown', window.movePopup.onMouseDown); openPopupListeners(); }; var openSettings = document.querySelector('.setup-open'); var closeSettings = window.movePopup.playerSettings.querySelector('.setup-close'); var openSettingsIcon = openSettings.querySelector('.setup-open-icon'); var userNameField = window.movePopup.playerSettings.querySelector('.setup-user-name'); var artifacts = document.querySelectorAll('.setup-artifacts-cell img'); var backpackPockets = document.querySelectorAll('.setup-artifacts .setup-artifacts-cell'); openPopupListeners(); window.setup = { closePopup: closePopup }; })();
8252a4cb9e4a38a7e940d8be5c4b6fee7a1ef699
[ "JavaScript" ]
2
JavaScript
nstgorbenko/code-and-magic
b116e3a23e6f4de14a60d8b5c53e4acd1a38f863
9c37b4774a64336400726cca0e801a26664b71ca
refs/heads/master
<file_sep>import config from "../config"; import { defaultInstance as http } from "../utils/axios"; const _API_ROOT = config.apiRoot; export const AuthApi = { login: (email, password) => http.post("/auth", { email, password }), }; <file_sep>export const uuidv4 = () => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; const v = c == "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); }; // compose any numbers of functions is kind of using f andThen g ==== compose(f, g) export const composes = (...fns) => (x) => fns.reduceRight((y, f) => f(y), x); export const head = ([x]) => x; export const tail = ([x, ...tail]) => tail; export const def = (x) => typeof x !== "undefined"; const isAFun = (f) => typeof f === "function"; export const undef = (x) => !def(x); export const copy = (array) => [...array]; export const length = ([x, ...xs], len = 0) => def(x) ? length(xs, len + 1) : len; export const reverse = ([x, ...xs]) => (def(x) ? [...reverse(xs), x] : []); export const first = ([x, ...xs], n = 1) => def(x) && n ? [x, ...first(xs, n - 1)] : []; export const last = (xs, n = 1) => reverse(first(reverse(xs), n)); export const slice = ([x, ...xs], i, y, curr = 0) => def(x) ? curr === i ? [y, x, ...slice(xs, i, y, curr + 1)] : [x, ...slice(xs, i, y, curr + 1)] : []; export const isArray = (x) => Array.isArray(x); export const flatten = ([x, ...xs]) => def(x) ? isArray(x) ? [...flatten(x), ...flatten(xs)] : [x, ...flatten(xs)] : []; //const array = [1,2,3,4,5] //swap(array, 0, 4) // [5,2,3,4,1] export const swap = (a, i, j) => map(a, (x, y) => { if (y === i) return a[j]; if (y === j) return a[i]; return x; }); // const double = x => x * 2 // map([1,2,3], double) // [2,4,6] export const map = ([x, ...xs], fn) => { if (undef(x)) return []; return [fn(x), ...map(xs, fn)]; }; export const filter = ([x, ...xs], fn) => def(x) ? (fn(x) ? [x, ...filter(xs, fn)] : [...filter(xs, fn)]) : []; export const reject = ([x, ...xs], fn) => { if (undef(x)) return []; if (!fn(x)) { return [x, ...reject(xs, fn)]; } else { return [...reject(xs, fn)]; } }; export const partition = (xs, fn) => [filter(xs, fn), reject(xs, fn)]; // const sum = (memo, x) => memo + x // reduce([1,2,3], sum, 0) // 6 // const flatten = (memo, x) => memo.concat(x) // reduce([4,5,6], flatten, [1,2,3]) // [1,2,3,4,5,6] export const reduce = ([x, ...xs], fn, memo, i = 0) => def(x) ? reduce(xs, fn, fn(memo, x, i), i + 1) : memo; export const reduceRight = (xs, fn, memo) => reduce(reverse(xs), fn, memo); // const flatten = (memo, x) => memo.concat(x) // reduceRight([[0,1], [2,3], [4,5]], flatten, []) // [4, 5, 2, 3, 0, 1] export const partial = (fn, ...args) => (...newArgs) => fn(...args, ...newArgs); // const add = ([x, ...xs]) => def(x) ? parseInt(x + add(xs)) : [] // add([1,2,3,4,5]) // 15 // const spreadAdd = spreadArg(add) // spreadAdd(1,2,3,4,5) // 15 export const spreadArg = (fn) => (...args) => fn(args); // Extract property value from array. Useful when combined with the map function. // const product = {price: 15} // pluck('price', product) // 15 // const getPrices = partial(pluck, 'price') // const products = [ // {price: 10}, // {price: 5}, // {price: 1} // ] // map(products, getPrices) // [10,5,1] export const pluck = (key, object) => object[key]; // Flow =>Each function consumes the return value of the function that came before. export const flow = (...args) => (init) => reduce(args, (memo, fn) => fn(memo), init); // const getPrice = partial(pluck, 'price') // const discount = x => x * 0.9 // const tax = x => x + (x * 0.075) // const getFinalPrice = flow(getPrice, discount, tax) // // looks like: tax(discount(getPrice(x))) // // -> get price // // -> apply discount // // -> apply taxes to discounted price // const products = [ // {price: 10}, // {price: 5}, // {price: 1} // ] // map(products, getFinalPrice) // [9.675, 4.8375, 0.9675] // The same as flow, but arguments are applied in the reverse order. // Compose matches up more naturally with how functions are written. // Using the same data as defined for the flow function: export const compose = (...args) => flow(...reverse(args)); // const getFinalPrice = compose(tax, discount, getPrice) // // looks like: tax(discount(getPrice(x))) // map(products, getFinalPrice) // [9.675, 4.8375, 0.9675] const minOrMax = (arr, predicateFun) => { predicateFun = isAFun(predicateFun) ? predicateFun : (a, b) => a < b; return arr.reduce((acc, v) => (predicateFun(acc, v) ? acc : v)); }; // intersection in js intersect (arr1, arr2) => arr contain commun element btw arr1 and arr2 export const intersect = (arr1, arr2) => arr1.filter((item) => arr2.includes(item)); //zip fiunction export const zip = (arr1, arr2) => arr1.map((item, i) => [item, arr2[i]]); // read from obj nested path export const read = (obj, path) => path.split(".").reduce((acc, val) => (!acc ? undefined : acc[val]), obj); /* * Creates an array without any duplicate item. * If a key function is passed, items will be compared based on the result of that function; * if not, their string representation will be used. */ export function distinct(arr, keyFunction) { keyFunction = keyFunction || ((x) => x); let set = {}; let result = []; arr.forEach((item) => { let key = keyFunction(item); if (!set[key]) { set[key] = 1; result.push(item); } }); return result; } /* * function check if two object are equals * ps : note that's function dont work with nested object * its should add recursive call im limited by time :) */ export function objectEquals(obj, obj2) { if (Object.keys(obj).length === Object.keys(obj2).length) { for (const key of Object.keys(obj)) { if (obj[key] !== obj2[key]) return false; } return true; } return false; } const log = (value) => console.log(value); //functors to avoid null and undefined //Maybe(empty).map(log); // does not log //Maybe('Maybe Foo').map(log); // logs "Maybe Foo" const Just = (value) => ({ map: (f) => Just(f(value)), }); const Nothing = () => ({ map: () => Nothing(), }); <file_sep>import { createBrowserHistory } from "history"; import { routerMiddleware } from "react-router-redux"; import { applyMiddleware, compose, createStore } from "redux"; import reduxImmutableStateInvariant from "redux-immutable-state-invariant"; import thunk from "redux-thunk"; import config from "./config"; import rootReducer from "./ducks"; export const history = createBrowserHistory(); function configureStoreProd(initialState) { const reactRouterMiddleware = routerMiddleware(history); const middlewares = [thunk, reactRouterMiddleware]; const store = createStore( rootReducer, initialState, compose(applyMiddleware(...middlewares)) ); return store; } function configureStoreDev(initialState) { const reactRouterMiddleware = routerMiddleware(history); const middlewares = [ thunk, reactRouterMiddleware, // Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches. reduxImmutableStateInvariant(), ]; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools const store = createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(...middlewares)) ); return store; } export const configureStore = config.isDevelopment ? configureStoreDev : configureStoreProd; export const store = configureStore(); <file_sep>import axios from "axios"; import config from "../config"; import { authHeader, cleanToken } from "./auth_header"; export const defaultInstance = axios.create({ baseURL: config.apiRoot, timeout: config.timeOut, }); /** * Builds error object 🥁 * @param {number} code - error code * @param {string} message - error text */ export const buildErrObject = (code, message) => ({ code, message, }); /** * Checks if a network request came back fine, or not * @param {number} status - http status req */ export const isValidRequest = ({ status }) => status >= 200 && status < 300; const ejectJWTInterpetor = defaultInstance.interceptors.request.use((value) => { if (value.url !== "login" && value.url !== "/") { const auth = authHeader(); const prevHeaders = value.headers; value.headers = { ...auth, ...prevHeaders, }; return value; } return value; }); const ejectRequestID = defaultInstance.interceptors.response.use((value) => { if (isValidRequest(value)) { return value; } if (value.status === 401) { cleanToken(); return value; } return Promise.reject(buildErrObject(value.status, "code")); }); export { ejectRequestID, ejectJWTInterpetor }; <file_sep>const TOKEN = "token"; export function getToken() { return localStorage.getItem(TOKEN); } export function authHeader() { // return authorization header with jwt token 'Bearer ' + localToken const localToken = getToken(); return localToken ? { Authorization: localToken } : {}; } export function save(token) { if (token) localStorage.setItem(TOKEN, token); } export function cleanToken() { localStorage.removeItem(TOKEN); } <file_sep>package com.ahoubouby.brs.exception; /* * ahoubouby created on 6/30/20 * E-MAIL: <EMAIL> */ import com.ahoubouby.brs.dto.response.Response; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; @ControllerAdvice @RestController public class CustomizedResponseEntityExceptionHandler { @ExceptionHandler(BRSException.EntityNotFoundException.class) public final ResponseEntity handleNotFountExceptions(Exception ex, WebRequest request) { Response response = Response.notFound(); response.addErrorMsgToResponse(ex.getMessage(), ex); return new ResponseEntity(response, HttpStatus.NOT_FOUND); } @ExceptionHandler(BRSException.DuplicateEntityException.class) public final ResponseEntity handleNotFountExceptions1(Exception ex, WebRequest request) { Response response = Response.duplicateEntity(); response.addErrorMsgToResponse(ex.getMessage(), ex); return new ResponseEntity(response, HttpStatus.CONFLICT); } } <file_sep>package com.ahoubouby.brs.service; /* * ahoubouby created on 6/30/20 * E-MAIL: <EMAIL> */ import com.ahoubouby.brs.dto.mapper.UserMapper; import com.ahoubouby.brs.dto.model.UserDto; import com.ahoubouby.brs.exception.EntityType; import com.ahoubouby.brs.exception.ExceptionType; import com.ahoubouby.brs.model.Role; import com.ahoubouby.brs.model.User; import com.ahoubouby.brs.model.UserRoles; import com.ahoubouby.brs.repository.RoleRepository; import com.ahoubouby.brs.repository.UserRepository; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import static com.ahoubouby.brs.exception.BRSException.*; import static com.ahoubouby.brs.exception.EntityType.*; import static com.ahoubouby.brs.exception.ExceptionType.*; import java.util.Collections; import java.util.HashSet; import java.util.Optional; @Service public class UserServiceImpl implements UserService { @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private RoleRepository roleRepository; @Autowired private UserRepository userRepository; @Autowired private BusReservationService busReservationService; @Autowired private ModelMapper modelMapper; @Override public UserDto signup(UserDto userDto) { Role userRole; User user = userRepository.findByEmail(userDto.getEmail()); if (user == null) { if (userDto.isAdmin()) { userRole = roleRepository.findByRole(UserRoles.ADMIN.name()); } else { userRole = roleRepository.findByRole(UserRoles.PASSENGER.name()); } user = new User() .setEmail(userDto.getEmail()) .setPassword(bCryptPasswordEncoder.encode(userDto.getPassword())) .setRoles(new HashSet<>(Collections.singletonList(userRole))) .setFirstName(userDto.getFirstName()) .setLastName(userDto.getLastName()) .setMobileNumber(userDto.getMobileNumber()); return UserMapper.toUserDto(userRepository.save(user)); } throw exception(USER, DUPLICATE_ENTITY, userDto.getEmail()); } @Override public UserDto findUserByEmail(String email) { Optional<User> user = Optional.ofNullable(userRepository.findByEmail(email)); if (user.isPresent()) { return modelMapper.map(user.get(), UserDto.class); } throw exception(USER, ENTITY_NOT_FOUND, email); } @Override public UserDto updateProfile(UserDto userDto) { Optional<User> user = Optional.ofNullable(userRepository.findByEmail(userDto.getEmail())); if (user.isPresent()) { User userModel = user.get(); userModel.setFirstName(userDto.getFirstName()) .setLastName(userDto.getLastName()) .setMobileNumber(userDto.getMobileNumber()); return UserMapper.toUserDto(userRepository.save(userModel)); } throw exception(USER, ENTITY_NOT_FOUND, userDto.getEmail()); } @Override public UserDto changePassword(UserDto userDto, String newPassword) { Optional<User> user = Optional.ofNullable(userRepository.findByEmail(userDto.getEmail())); if (user.isPresent()) { User userModel = user.get(); userModel.setPassword(bCryptPasswordEncoder.encode(newPassword)); return UserMapper.toUserDto(userRepository.save(userModel)); } throw exception(USER, ENTITY_NOT_FOUND, userDto.getEmail()); } private RuntimeException exception(EntityType entityType, ExceptionType exceptionType, String... args) { return throwException(entityType, exceptionType, args); } } <file_sep>import React, { memo, useState } from "react"; import { useDispatch } from "react-redux"; import { login } from "../../ducks/login"; import "./style.css"; const Login = () => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const dispatch = useDispatch(); const handleEmailChange = (e) => { const { value } = e.target; setEmail(value); }; const handlePasswordChange = (e) => { const { value } = e.target; setPassword(value); }; const submit = (e) => { dispatch(login(email, password)); e.preventDefault(); }; return ( <div className="ui middle aligned center aligned grid"> <div className="column"> <form className="ui large form"> <div className="ui stacked segment"> <div className="field"> <div className="ui left icon input"> <i className="user icon"></i> <input type="text" name="email" placeholder="E-mail address" onChange={handleEmailChange} /> </div> </div> <div className="field"> <div className="ui left icon input"> <i className="lock icon"></i> <input type="password" name="password" placeholder="<PASSWORD>" onChange={handlePasswordChange} /> </div> </div> <div className="ui fluid large teal submit button" onClick={submit}> Login </div> </div> <div className="ui error message"></div> </form> </div> </div> ); }; export default { path: "/login", component: memo(Login), name: "login", }; <file_sep>package com.ahoubouby.brs.repository; /* * ahoubouby created on 6/30/20 * E-MAIL: <EMAIL> */ import com.ahoubouby.brs.model.Agency; import com.ahoubouby.brs.model.User; import org.springframework.data.mongodb.repository.MongoRepository; public interface AgencyRepository extends MongoRepository<Agency, String> { Agency findByCode(String agencyCode); Agency findByOwner(User owner); Agency findByName(String name); } <file_sep>package com.ahoubouby.brs.dto.mapper; import com.ahoubouby.brs.dto.model.TripScheduleDto; import com.ahoubouby.brs.model.Trip; import com.ahoubouby.brs.model.TripSchedule; /* * ahoubouby created on 6/30/20 * E-MAIL: <EMAIL> */ public class TripScheduleMapper { public static TripScheduleDto toTripScheduleDto(TripSchedule tripSchedule) { Trip tripDetails = tripSchedule.getTripDetail(); return new TripScheduleDto() .setId(tripSchedule.getId()) .setTripId(tripDetails.getId()) .setBusCode(tripDetails.getBus().getCode()) .setAvailableSeats(tripSchedule.getAvailableSeats()) .setFare(tripDetails.getFare()) .setJourneyTime(tripDetails.getJourneyTime()) .setSourceStop(tripDetails.getSourceStop().getName()) .setDestinationStop(tripDetails.getDestStop().getName()); } } <file_sep>package com.ahoubouby.brs.dto.mapper; /* * ahoubouby created on 6/30/20 * E-MAIL: <EMAIL> */ import com.ahoubouby.brs.dto.model.RoleDto; import com.ahoubouby.brs.dto.model.UserDto; import com.ahoubouby.brs.model.User; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.stream.Collectors; @Component public class UserMapper { public static UserDto toUserDto(User user) { return new UserDto() .setEmail(user.getEmail()) .setFirstName(user.getFirstName()) .setLastName(user.getLastName()) .setMobileNumber(user.getMobileNumber()) .setRoles(new HashSet<RoleDto>(user .getRoles() .stream() .map(role -> new ModelMapper().map(role, RoleDto.class)) .collect(Collectors.toSet()))); } } <file_sep>spring.application.name=brs spring.data.mongodb.database=${MONGODB_SCHEMA:springmongodb} spring.data.mongodb.host=${MONGODB_HOST:localhost} spring.data.mongodb.port=${MONGODB_PORT:27017} logging.level.web=${LOG_LEVEL:DEBUG} management.endpoints.web.exposure.include=* server.error.whitelabel.enabled=false spring.jpa.hibernate.ddl-auto=create-drop api.version=0.0.1 <file_sep>package com.ahoubouby.brs.dto.response; /* * ahoubouby created on 6/30/20 * E-MAIL: <EMAIL> */ public enum Status { OK, BAD_REQUEST, UNAUTHORIZED, VALIDATION_EXCEPTION, EXCEPTION, WRONG_CREDENTIALS, ACCESS_DENIED, NOT_FOUND, DUPLICATE_ENTITY } <file_sep>package com.ahoubouby.brs.repository; import com.ahoubouby.brs.model.Ticket; import org.springframework.data.mongodb.repository.MongoRepository; public interface TicketRepository extends MongoRepository<Ticket, Long> { } <file_sep>import { AuthApi } from "../../api"; import { buildErrObject, isValidRequest } from "../../utils/axios"; import { LOGGED_IN_SUCCESS, LOGGIN_IN_FAILED } from "./actions"; const login = (email, password) => async (dispatch) => { try { const result = await AuthApi.login(email, password); isValidRequest(result) ? dispatch({ type: LOGGED_IN_SUCCESS, payload: result }) : dispatch({ type: LOGGIN_IN_FAILED, payload: buildErrObject(result.status, "err"), }); } catch (err) { dispatch({ type: LOGGIN_IN_FAILED, payload: buildErrObject(500, err), }); } }; export { login }; <file_sep>import { routerReducer } from "react-router-redux"; import { combineReducers } from "redux"; import authReducer from "../ducks/login"; export default combineReducers({ router: routerReducer, // our reducers auth: authReducer, }); <file_sep>import login from "../component/login"; const routees = [login]; /* routeProps: { path: '/todo', component: memo(TodoApp), }, name: 'todo App simple', } */ export { routees };
13cde5410dd6e6de09aae981f5d88ab98a18c97c
[ "JavaScript", "Java", "INI" ]
17
JavaScript
fzfathi/brs
1552d732f220f1ab883a74e196ca30b3e3adbff7
5d978799e3c62e88569360909078ff900c864d3b
refs/heads/master
<repo_name>Bheem6005/MongoDB-Guessing-Game-6005<file_sep>/app/sample.py from flask import Flask, request, jsonify, render_template from pymongo import MongoClient import os, json, redis # App application: Flask = Flask(__name__) # connect to MongoDB mongoClient = MongoClient( 'mongodb://' + os.environ['MONGODB_USERNAME'] + ':' + os.environ['MONGODB_PASSWORD'] + '@' + os.environ[ 'MONGODB_HOSTNAME'] + ':27017/' + os.environ['MONGODB_AUTHDB']) db = mongoClient[os.environ['MONGODB_DATABASE']] # connect to Redis redisClient = redis.Redis(host=os.environ.get("REDIS_HOST", "localhost"), port=os.environ.get("REDIS_PORT", 6379), db=os.environ.get("REDIS_DB", 0)) game_col = db.Guessing_Game @application.route('/') def index(): game_col.delete_many({}) return render_template('index.html') @application.route('/game') def game(): game_col.insert_one({ "answer": [], "end": False, "wrong_count": 0, "state_count": 0, }) current_game = game_col.find_one({"end": False}) return render_template('game.html', game=current_game) @application.route('/a-button/') def a_button(): current_game = game_col.find_one({"end": False}) answer = current_game["answer"] state = current_game["state_count"] wrong_count = current_game["wrong_count"] if 0 <= state <= 3: answer.append('A') state += 1 game_col.update_one({"end": False}, {"$set": {"answer": answer, "state_count": state}}) elif 4 <= state <= 7: if answer[state - 4] == 'A': if state != 7: state += 1 game_col.update_one({"end": False}, {"$set": {"state_count": state}}) else: game_col.update_one({"end": False}, {"$set": {"end": True}}) return render_template('end.html', game=current_game) else: wrong_count += 1 game_col.update_one({"end": False}, {"$set": {"wrong_count": wrong_count}}) current_game = game_col.find_one({"end": False}) return render_template('game.html', game=current_game) @application.route('/b-button/') def b_button(): current_game = game_col.find_one({"end": False}) answer = current_game["answer"] state = current_game["state_count"] wrong_count = current_game["wrong_count"] if 0 <= state <= 3: answer.append('B') state += 1 game_col.update_one({"end": False}, {"$set": {"answer": answer, "state_count": state}}) elif 4 <= state <= 7: if answer[state - 4] == 'B': if state != 7: state += 1 game_col.update_one({"end": False}, {"$set": {"state_count": state}}) else: game_col.update_one({"end": False}, {"$set": {"end": True}}) return render_template('end.html', game=current_game) else: wrong_count += 1 game_col.update_one({"end": False}, {"$set": {"wrong_count": wrong_count}}) current_game = game_col.find_one({"end": False}) return render_template('game.html', game=current_game) @application.route('/c-button/') def c_button(): current_game = game_col.find_one({"end": False}) answer = current_game["answer"] state = current_game["state_count"] wrong_count = current_game["wrong_count"] if 0 <= state <= 3: answer.append('C') state += 1 game_col.update_one({"end": False}, {"$set": {"answer": answer, "state_count": state}}) elif 4 <= state <= 7: if answer[state - 4] == 'C': if state != 7: state += 1 game_col.update_one({"end": False}, {"$set": {"state_count": state}}) else: game_col.update_one({"end": False}, {"$set": {"end": True}}) return render_template('end.html', game=current_game) else: wrong_count += 1 game_col.update_one({"end": False}, {"$set": {"wrong_count": wrong_count}}) current_game = game_col.find_one({"end": False}) return render_template('game.html', game=current_game) @application.route('/d-button/') def d_button(): current_game = game_col.find_one({"end": False}) answer = current_game["answer"] state = current_game["state_count"] wrong_count = current_game["wrong_count"] if 0 <= state <= 3: answer.append('D') state += 1 game_col.update_one({"end": False}, {"$set": {"answer": answer, "state_count": state}}) elif 4 <= state <= 7: if answer[state - 4] == 'D': if state != 7: state += 1 game_col.update_one({"end": False}, {"$set": {"state_count": state}}) else: game_col.update_one({"end": False}, {"$set": {"end": True}}) return render_template('end.html', game=current_game) else: wrong_count += 1 game_col.update_one({"end": False}, {"$set": {"wrong_count": wrong_count}}) current_game = game_col.find_one({"end": False}) return render_template('game.html', game=current_game) if __name__ == "__main__": ENVIRONMENT_DEBUG = os.environ.get("FLASK_DEBUG", True) ENVIRONMENT_PORT = os.environ.get("FLASK_PORT", 5000) application.run(host='0.0.0.0', port=ENVIRONMENT_PORT, debug=ENVIRONMENT_DEBUG)
caf8f21bb4ab42811678d140a26a0b615ccf0bf3
[ "Python" ]
1
Python
Bheem6005/MongoDB-Guessing-Game-6005
7afdd9e62ca65a72c75b9ad618d8cf5887b43b6e
d81b27ed661f3248f044e5eda4709f7cdeefc069
refs/heads/master
<file_sep>import yaml class Args(type): def __repr__(self): args = { k: v for k, v in vars(self).items() if not k.startswith('_') } if self.__doc__: args = {'Description': yaml.load(self.__doc__), 'Data':args} s = yaml.dump({self.__name__: args}, default_flow_style=False) return s class autoencoder(metaclass=Args): optim = 'Adam' optim_args = dict( lr = 3e-3 ) batch_size = 30 max_epoch = 10000 endure = 20 loss_cate = 'CrossEntropyLoss' loss_val = 'MSELoss' class translator(metaclass=Args): name = 'test' optim = 'RMSprop' optim_args = dict( lr = 3e-3 ) batch_size = 30 max_epoch = 10000 endure = 1000 loss_cate = 'CrossEntropyLoss' loss_val = 'MSELoss' class music(metaclass=Args): ''' T: time period of a music sneppet (in beat) L: max music length E: note feature number K: kernel size dp: dropout rate ''' id2feat = 'pitch time duration volume'.split() feat2id = {feat: id for id, feat in enumerate(id2feat)} L = 30 E = len(feat2id) K = 3 Co = 500 dp = 0.5 T = 32 class note(metaclass=Args): ''' dim: embedding dimension size: number of embeddings ''' from itertools import product pitch = list(range(36,90)) duration = [x/2 for x in range(1, 4)] time = [x/16 for x in range(8)] time += [x/8 for x in range(4, 8)] time += [x/2 for x in range(2, 4)] volume = [80, 100] divs = [pitch, time, duration, volume] note2id = {k: i for i, k in enumerate(product(*divs), 1)} note2id[0,0,0,0] = 0 id2note = {v: k for k, v in note2id.items()} size = len(note2id) dim = 30 class tempo(metaclass=Args): default = 500000 # mus/beat class lyrics(metaclass=Args): ''' L: max lyrics length E: word embedding size K: kernel size (n-gram) Co: output channel (n-gram vector dim) dp: dropout rate lex: word2vec file ''' L = 10 #500 E = 200 K = 1 Co = 200 dp = 0.05 lex = 'data/word-vectors.txt' # encoded vector size M = 200 <file_sep>#!/usr/bin/env python3 from jseg.jieba import Jieba import glob, os import word2vec import numpy as np jieba = None UNK = '<UNK>' def cut(s): global jieba if jieba is None: jieba = Jieba() return sum([list(jieba.seg(_s, pos=False).raw) for _s in s.split()], []) def genSegment(files='data/raw/*.txt', save_in='data/seg'): if not os.path.exists(save_in): print('Make directory '+save_in) os.makedirs(save_in) files = list(glob.glob(files)) print('Segmentalizing {} files ...'.format(len(files))) for path in files: with open(path) as f: seged = ' '.join(cut(f.read())) save_path = os.path.join(save_in, os.path.basename(path)) with open(save_path, 'w') as f: f.write(seged) print('Segmentalize finished') def genWordEmbedding(files='data/seg/*.txt', save_as='data/word-vectors.txt'): corpus_path = 'word2vec-corpus.tmp' with open(corpus_path, 'w') as corpus: for path in glob.glob(files): with open(path) as f: corpus.write(f.read()+'\n') corpus.write((" "+UNK)*10) word2vec.word2vec(corpus_path, save_as, size=100, verbose=True, binary=0) w2v = word2vec.load(save_as) # set UNK's vector to mean of all vectors w2v.vectors[w2v.vocab_hash[UNK]] = np.mean(w2v.vectors, axis=0) with open(save_as, "w") as corpus: # w2v.save corpus.write("%d %d\n" % w2v.vectors.shape) for i in range(w2v.vectors.shape[0]): print(w2v.vocab[i], *(str(v)[:9] for v in w2v.vectors[i]), file=corpus) os.remove(corpus_path) w2v = None def convert(lyrics, usingW2V="data/word-vectors.txt", is_file=False): """Convert lyrics to word id list. input: lyrics: input str or file name """ global w2v if is_file: # file with open(lyrics) as f: lyrics = f.read() lyrics = lyrics.split() else: terms = cut(lyrics) if w2v is None: w2v = word2vec.load(usingW2V) unk_id = w2v.vocab_hash[UNK] return [w2v.vocab_hash.get(t, unk_id) for t in lyrics] if __name__=='__main__': print('Will segmentalize/make word embedding for files in data/raw/*.txt') genSegment() genWordEmbedding() print('Done') <file_sep>beautifulsoup4==4.6.0 bs4==0.0.1 Cython==0.25.2 jseg3==0.0.1 MIDIUtil==1.1.3 nltk==3.0.3 numpy==1.12.1 pandas==0.20.1 python-dateutil==2.6.0 pytz==2017.2 PyYAML==3.12 requests==2.14.2 six==1.10.0 torch==0.1.12.post2 websockets==3.3 word2vec==0.9.1 Flask==0.12.2 <file_sep>#!/usr/bin/env python from copy import deepcopy from collections import defaultdict import functools import yaml import torch import config import model import dataset history = None def record(batchLoss): @functools.wraps(batchLoss) def decorated(model, dataset, criterion, train=True): epoch_loss = [0, 0] for loss, out, tar in batchLoss(model, dataset, criterion, train): epoch_loss[0] += loss[0].data[0] epoch_loss[1] += loss[1].data[0] if train: yield loss, False _, out_idx = out[0].max(1) acc = (out_idx == tar[0]).sum() acc = acc.data[0] acc /= tar[0].size(0) loss = [ (loss/len(dataset)) for loss in epoch_loss ] loss[1] = loss[1]**0.5 state = ['Validate', 'Train'][train] print('%-9s- ' % state, end='') print('loss: ({:7.4f}, {:7.4f}) , acc: {:.4f}'.format( loss[0], loss[1], acc)) history['Loss of Note', state].append(loss[0]) history['Loss of Tempo', state].append(loss[1]) history['Accuracy', state].append(acc) yield -acc, True return decorated @record def batchLoss(model, dataset, criterion, train): loss = [0, 0] for batch in dataset: inp, tar = batch tar = model.wrapTar(tar) out = model(inp) loss[0] = criterion[0](out[0], tar[0]) loss[1] = criterion[1](out[1], tar[1]) yield loss, out, tar def validate(model, valset, criterion): return next(batchLoss(model, valset, criterion, train=False))[0] def earlyStop(fin): def train(model, trainset, valset, args): global history history = defaultdict(list) fmt = 'Epoch {:3} - Endure {:3}/{:3}\n' def printfmt(i, endure): print(fmt.format(i, endure, args.endure)) trainer = fin(model, trainset, valset, args) endure, min_loss = 0, float('inf') for i, loss in enumerate(trainer, 1): printfmt(i, endure) if loss < min_loss: min_loss = loss endure = 0 sd = deepcopy(model.state_dict()) else: endure += 1 if endure > args.endure: model.load_state_dict(sd) print('\n Max Validate Acc: {:.4f}'.format(-min_loss)) break return history return train @earlyStop def train(model, trainset, valset, args): optim = getattr(torch.optim, args.optim) optim = optim(model.parameters(), **args.optim_args) optim.zero_grad() criterion = (getattr(torch.nn, args.loss_cate)(), getattr(torch.nn, args.loss_val)()) for epoch in range(1, args.max_epoch+1): trainset.shuffle() model.train(True) for loss, end in batchLoss(model, trainset, criterion): if end: break loss[1].backward(retain_variables=True) loss[0].backward() optim.step() optim.zero_grad() model.train(False) valloss = validate(model, valset, criterion) yield valloss if __name__ == '__main__': AEtrainset, TRtrainset = dataset.load('data/train.jsonl') AEvalset, TRvalset = dataset.load('data/valid.jsonl') vs = dataset.vs le = model.LyricsEncoder(vs) me = model.MusicEncoder() md = model.MusicDecoder() ae = model.Translator([me, md]) tr = model.Translator([le, md]) hist = {} args = config.autoencoder print(args) print(ae) hist['Autoencoder'] = train(ae, AEtrainset, AEvalset, args=args) args = config.translator print(args) print(tr) hist['Translator'] = train(tr, TRtrainset, TRvalset, args=args) with open('model/%s.hist'%args.name, 'w') as f: yaml.dump(hist, f) filename = 'model/%s.para'%args.name print('Saved as %s' % filename) torch.save(tr.state_dict(), filename) sd = model.load(filename) for name, para in tr.named_parameters(): assert all(sd[name].view(-1) == para.data.view(-1)) <file_sep># 把你心情哼成歌 「把你心情哼成歌」(Sing Your Feelings, SYF)是一個結合文字辨識和音樂生成的系統,把一段有意義的句子、詩詞或文章轉換成一段好聽的音樂,並能體現出這段文字的意涵。 ## Files ``` - data/ - raw/ - *.mid - *.txt - csv/ - *.csv - train.jsonl - test.jsonl - word-vectors.txt - model/ - {model name}.para - crawler/ - gui/ - index.html - ... ``` ## Requirement ### Python3.5 - PyTorch should be installed manually from the [website](http://pytorch.org/). - [Jseg3](https://github.com/amigcamel/Jseg/tree/jseg3) should be installed by ```bash pip install https://github.com/amigcamel/Jseg/archive/jseg3.zip ``` Other packages are listed in `requirement.txt`, so: ```bash pip install -r requirement.txt ``` ### [midicsv](http://www.fourmilab.ch/webtools/midicsv/) ```bash wget http://www.fourmilab.ch/webtools/midicsv/midicsv-1.1.tar.gz tar zxvf midicsv-1.1.tar.gz cd midicsv-1.1 make make install INSTALL_DEST=path_to_install ``` ## Usage ### Prepare Data ```bash make ``` This will generate in the `data/` folder: - the word vectors `word-vectors.txt` - the dataset `train.jsonl` and `valid.jsonl` ### Train Model ```bash python3 train.py ``` The trained parameters will be saved in `model/test.para`. ### Server ``` python3 server.py ``` ## Modification ### Train The arguments are stored in `config.py`. One can find detailed descriptions about the arguments in it. ### Server - You can choose your own model, port and cuda usage in `server.py`. ```python para = 'model/test.para' # path to your trained model model.use_cuda = False port = 80 ``` <file_sep>#!/usr/bin/env python import dataset import config from config import * import torch from torch.autograd import Variable import torch.nn as nn import word2vec #use_cuda = False use_cuda = torch.cuda.is_available() class param: def __init__(self, **args): self.args = args def __call__(self, fin): params = self.args def __init__(self, *args, **kwargs): fin(self, *args, **kwargs) if use_cuda: self.cuda() for k, (t, v) in params.items(): setattr(self, k, getattr(torch,t)(*v).cuda()) else: for k, (t, v) in params.items(): setattr(self, k, getattr(torch,t)(*v)) return __init__ def load(filename): if use_cuda: sd = torch.load(filename) else: sd = torch.load(filename, map_location = lambda storage, loc: storage) return sd class MusicEncoder(nn.Module): # K, Co = config.music.K, config.music.Co L, M = config.music.L, config.M Emb, Siz = config.note.dim, config.note.size dp = config.music.dp # assert L >= K, 'MusicEncoder: Seq length should >= kernel size' @param( note = ['LongTensor', (300, L)], tempo = ['Tensor', (300,)], ) def __init__(self): super().__init__() self.emb = nn.Embedding(self.Siz, self.Emb) ''' self.conv = nn.Conv2d(1, self.Co, (self.K, self.Emb)) self.pool = nn.MaxPool1d(self.L, ceil_mode=True) self.linear = nn.Linear(1+self.Co, self.M) self.dropout = nn.Dropout(self.dp, inplace=True) ''' self.activate = nn.Sigmoid() self.QAQ = nn.Linear(1+self.L*self.Emb, self.M) def forward(self, inp): note, tempo = inp # note: torch tensor, N x L # tempo: torch tensor, N # out: torch tensor variable, N x M assert type(note).__name__.endswith('Tensor') note = self.note.resize_(note.size()).copy_(note) note = Variable(note) assert type(tempo).__name__.endswith('Tensor') tempo = self.tempo.resize_(tempo.size()).copy_(tempo) tempo = Variable(tempo) note = self.emb(note).view(-1, self.L*self.Emb) hid = torch.cat([tempo.view(-1,1), note], 1) out = self.QAQ(hid) out = self.activate(out) return out ''' note = self.emb(note.view(-1,self.Ci*self.L)).view(-1, self.self.L, self.Emb) # N x Ci x L x Emb hid = self.conv(note).squeeze(-1) # N x Co x L- hid = self.pool(hid).squeeze(-1) # N x Co self.dropout(hid) hid = torch.cat([tempo.view(-1,1), hid], 1) # N x 1+Co out = self.linear(hid) # N x M self.dropout(out) self.activate(out) return out ''' class MusicDecoder(nn.Module): L, K, Co, M = \ config.music.L, config.music.K, config.music.Co, config.M Emb, Siz = config.note.dim, config.note.size dp = config.music.dp assert L >= K, 'MusicDecoder: Seq length should >= kernel size' @param() def __init__(self): super().__init__() self.linear = nn.Linear(self.M, 1+self.Co) self.unpool = nn.Linear(1, self.L+self.K-1) self.unconv = nn.Conv1d(self.Co, self.Emb, self.K) self.unemb = nn.Linear(self.Emb, self.Siz) self.dropout = nn.Dropout(self.dp, inplace=True) self.activate = nn.ReLU() ''' self.soft = nn.Softmax() self.QAQ = nn.Linear(self.M, 1+self.L*self.Siz) ''' def forward(self, inp): # inp: torch tensor variable, N x M # note: torch tensor variable, N*L x Siz # tempo: torch tensor variable, N assert type(inp).__name__ == 'Variable' hid = self.linear(inp) # N x 1+Co tempo, hid = hid[:,0], hid[:,1:] # N x Co hid = hid.contiguous() hid = self.unpool(hid.view(-1,1)) # N*Co x L+K-1 hid = hid.view(-1, self.Co, self.L+self.K-1) # N x Co x L+K-1 hid = self.activate(hid) note = self.unconv(hid) # N x Emb x L self.dropout(note) note = note.transpose(1, 2).contiguous() # N x L x Emb note = self.unemb(note.view(-1,self.Emb)) # N*L x Siz self.dropout(note) # tempo = self.activate(tempo) # note = self.activate(note) return note, tempo class LyricsEncoder(nn.Module): L, E, K, Co, M = \ config.lyrics.L, config.lyrics.E, config.lyrics.K, config.lyrics.Co, config.M dp = config.lyrics.dp assert L >= K, 'LyricsEncoder: Seq length should >= kernel size' @param(inp = ['LongTensor', (300, L)]) def __init__(self, vs): # vs: vocabulary size super().__init__() self.embed = nn.Embedding(vs, self.E) self.dropout = nn.Dropout(self.dp, inplace=True) self.conv = nn.Conv2d(1, self.Co, (self.K, self.E)) self.pool = nn.MaxPool1d(self.L, ceil_mode=True) self.linear = nn.Linear(self.Co, self.M) self.activate = nn.Sigmoid() def forward(self, inp): # inp: torch tensor, N x L # out: torch tensor variable, N x M assert type(inp).__name__.endswith('Tensor') inp = self.inp.resize_(inp.size()).copy_(inp) inp = Variable(inp) emb = self.embed(inp).unsqueeze(1) # N x 1 x L x E self.dropout(emb) hid = self.conv(emb).squeeze(-1) # N x Co x L- hid = self.pool(hid).squeeze(-1) # N x Co self.dropout(hid) out = self.linear(hid) # N x M self.dropout(out) #out = self.activate(out) return out def translateWrap(translator): import lyrics2vec as l2v def translate(s): inp = l2v.convert(s)[:config.lyrics.L] inp = torch.Tensor(inp).unsqueeze(0) note, tempo = translator(inp) _, note = note.max(1) vec = note.data.squeeze().tolist(), tempo.data[0] out = dataset.vec2midi(vec) return out return translate class Translator(nn.Module): L, E = config.music.L, config.music.E @param( note = ['LongTensor', (300, L)], tempo = ['Tensor', (300, )], ) def __init__(self, init = None): # encoder: lyrics encoder / music encoder # decoder: music decoder super().__init__() if init: encoder, decoder = init self.encoder = encoder self.decoder = decoder else: vs = len(dataset.lex.vocab) self.encoder = LyricsEncoder(vs) self.decoder = MusicDecoder() self.translate = translateWrap(self) self.train(False) def forward(self, inp): enc = self.encoder(inp) out = self.decoder(enc) return out def wrapTar(self, tar): note, tempo = tar self.note.resize_(note.size()).copy_(note) self.tempo.resize_(tempo.size()).copy_(tempo) return Variable(self.note).view(-1), Variable(self.tempo) if __name__ == '__main__': vsL, vsM = len(dataset.lex.vocab), config.note.size n = 3 M = config.M lyr = torch.floor( torch.rand(n, config.lyrics.L) * vsL ) note = torch.floor( torch.rand(n, config.music.L) * vsM ) tempo = torch.floor( torch.rand(n) * vsM ) mus = (note, tempo) le = LyricsEncoder(vsL) print(le) outLe = le(lyr) assert outLe.size(0) == n assert outLe.size(1) == M me = MusicEncoder() print(me) outMe = me(mus) assert outMe.size(0) == n assert outMe.size(1) == M md = MusicDecoder() print(md) outMd = md(outMe) assert outMd[0].size(0) == n * config.music.L assert outMd[0].size(1) == vsM assert outMd[1].size() == tempo.size() ae = Translator([me, md]) print('Autoencoder: ', ae) outAe = ae(mus) assert outAe[0].size(0) == n * config.music.L assert outAe[0].size(1) == vsM assert outAe[1].size() == tempo.size() tr = Translator([le, md]) print('Translator: ', tr) outTr = tr(lyr) assert outTr[0].size(0) == n * config.music.L assert outTr[0].size(1) == vsM assert outTr[1].size() == tempo.size() <file_sep>#!/usr/bin/env python import random import yaml from midiutil import MIDIFile import pandas as pd import torch import word2vec as w2v import config import lyrics2vec as l2v import midi2vec as m2v lex = w2v.load(config.lyrics.lex) vs = len(lex.vocab) def vec2midi(vec): ''' vec: (note, tempo) note: list note sequence L tempo: float ''' notes, tempo = vec print(notes) midi = MIDIFile(1, adjust_origin=False) tempo *= config.tempo.default # mus/beat tempo = int(1e6 * 60 / tempo) # beat/minute (BPM) midi.addTempo(0, 0, tempo) feat2id = config.music.feat2id.items() time = 0 for note_emb in notes: if note_emb: note = config.note.id2note[note_emb] note = {feat: note[id] for feat, id in feat2id} note['time'] = time = note['time'] + time midi.addNote(track=0, channel=0, **note) return midi class Dataset: def __init__(self, inp, tar, batch_size): ''' inp, tar: dict of (lyrics, note, tempo) lyrics: list, lyrics vector note: list, note matrix of the music snippet tempo: int, tempo of the music snippet ''' self.bs = batch_size self.inp = inp self.tar = tar for data in filter(None, [self.inp, self.tar]): for name, c_type in [('lyrics', config.lyrics), ('note', config.music)]: if name in data: data[name] = self.pad(data[name], c_type) self.size = len(data[name]) def pad(self, data, config_obj): L = config_obj.L def pad(data): return data[:L] + [ 0 for _ in range(L-len(data)) ] return [ pad(d) for d in data ] def __getitem__(self, i): if i >= len(self): raise IndexError('Index %d out of range (%d)' % (i, len(self)-1)) begin = self.bs * i end = begin + self.bs if end >= self.size: end = None pair = [None, None] # [inp, tar] for n, data in [(0,self.inp), (1,self.tar)]: if 'lyrics' in data: pair[n] = torch.Tensor(data['lyrics'][begin:end]) if 'note' in data: note = torch.Tensor(data['note'][begin:end]) tempo = torch.Tensor(data['tempo'][begin:end]) pair[n] = (note, tempo) return tuple(pair) def shuffle(self): data = list(self.inp.values())+list(self.tar.values()) data = list(zip(*data)) random.shuffle(data) data = [ list(d) for d in zip(*data) ] for k, v in zip(self.inp, data[:len(self.inp)]): self.inp[k] = v for k, v in zip(self.tar, data[len(self.inp):]): self.tar[k] = v def __len__(self): return (self.size+self.bs-1) // self.bs def __repr__(self): return yaml.dump({'Dataset': dict( data = dict( inp = ', '.join(list(self.inp)), tar = ', '.join(list(self.tar)), ), size = self.size, batch_size = self.bs, )}, default_flow_style=False) ''' def split(self, ratio=0.2): n = int(self.size*(1-ratio)) def div(d, is_f): r = {} for k, v in d.items(): r[k] = v[:n] if is_f==0 else v[n:] return r d1, d2 = [Dataset(div(self.inp,i), div(self.tar,i), self.bs) for i in [0, 1]] return d1, d2 ''' def loadPath(n=None, lyr_path="data/seg/*.txt", midi_path="data/csv/*.csv"): from glob import glob import os name = lambda x: os.path.splitext(os.path.basename(x))[0] ''' lyr_path, midi_path = glob(lyr_path), glob(midi_path) both = set(map(name, lyr_path)) & set(map(name, midi_path)) lyr_path = list(filter(lambda n: name(n) in both, lyr_path)) midi_path = list(filter(lambda n: name(n) in both, midi_path)) lyr_path.sort(key=os.path.basename) midi_path.sort(key=os.path.basename) if n==0: n = len(lyr_path) ''' names = set(map(name, glob(lyr_path))) & set(map(name, glob(midi_path))) names = sorted(list(names))[:n] return [(id, name, lyr_path.replace('*', name), midi_path.replace('*', name)) for id, name in enumerate(names)] ''' for lyr, midi in list(zip(lyr_path, midi_path))[:n]: yield lyr, midi ''' def load(filename): ''' from collections import defaultdict lyrics, note, tempo = [], [], [] for lyrics_path, midi_path in loadData(n): lyr = l2v.convert(lyrics_path) for n, t in m2v.convert(midi_path): lyrics.append(lyr) note.append(n) tempo.append(t) ''' print("Load data from %s" % filename) data = pd.read_json(filename, lines=True) inp = {'lyrics': data.lyrics.tolist()} tar = {'note': data.note.tolist(), 'tempo': data.tempo.tolist()} dataset_tr = Dataset(inp, tar, config.translator.batch_size) dataset_ae = Dataset(tar, tar, config.autoencoder.batch_size) return dataset_ae, dataset_tr def save(args): import json paths = loadPath(args.n) random.seed(301) random.shuffle(paths) n = len(paths) split = args.split train, valid = paths[n//split:], paths[:n//split] i = 0 for f, paths in [(args.train, train), (args.valid, valid)]: for fid, name, lyr_path, midi_path in paths: lyrics = l2v.convert(lyr_path, is_file=True) for j, snippet in enumerate(m2v.convert(midi_path)): id = '%d-%d' % (fid, j) start = j*config.lyrics.L end = start + config.lyrics.L if start >= len(lyrics): break data = dict(id=id, name=name, lyrics=lyrics[start:end], **snippet) print(json.dumps(data, ensure_ascii=False, sort_keys=True), file=f) i += 1 print('{:>5d}/{:>5d}'.format(i, n), end='\r') if __name__ == '__main__': import argparse import time ap = argparse.ArgumentParser() ap.add_argument('-train', '-t', type=argparse.FileType('w'), default='data/train.jsonl') ap.add_argument('-valid', '-v', type=argparse.FileType('w'), default='data/valid.jsonl') ap.add_argument('-split', '-s', type=int, default=4) ap.add_argument('-n', '-number', type=int) start = time.time() args = ap.parse_args() save(args) print('\nElapsed: ', int(time.time()-start), 's', sep='') <file_sep>from collections import namedtuple import csv from bisect import bisect_right as bs import config Tempo = namedtuple('Tempo', ['time', 'value']) id = config.music.feat2id min_pitch, max_pitch = config.note.pitch[0], config.note.pitch[-1] def noteEmb(snippet): return list(filter(None, map(note2Id, snippet))) def note2Id(note): ''' input: ONE note with features output: note id ''' if (0 < note[id['duration']] <= config.note.duration[-1] and min_pitch <= note[id['pitch']] <= max_pitch and not 0 < note[id['time']] < config.note.time[1]): note = tuple(d[bs(d, n)-1] for n, d in zip(note, config.note.divs)) return config.note.note2id[note] else: return None def chunk(midi2vec): def chunk(note, tempo): ''' input: note: note sequence in a midi file tempo: tempo sequence in a midi file output: (snippet, tempo) snippet: a snippet of notes whose feature time is diffTime. tempo: the tempo at which the snippet start ''' T = config.music.T snippet, time, tid = [], 0, 0 for feat in note: if feat[id['time']] > time: while time > tempo[tid].time and tid < len(tempo)-1: tid += 1 if len(snippet) > T/2: yield diffTime(snippet), tempo[tid-1].value time += T snippet = [] snippet.append(feat) ''' if snippet: yield diffTime(snippet), tempo[tid-1].value ''' def convert(filename): '''Convert a midi-csv file to music snippets. input: midi-csv file name output: snippet (note, tempo) list note: list of track track: list of note features tempo: int ''' notes, tempos = midi2vec(filename) notes = sorted(notes, key=lambda feat: feat[id['time']]) for chunk_notes, chunk_tempos in chunk(notes, tempos): snippet = { 'note': noteEmb(chunk_notes), 'tempo': chunk_tempos, 'feature': dict(zip(config.music.id2feat, zip(*chunk_notes))) } yield snippet return convert def diffTime(note): ''' input: notes with absolute time output: as input but time is counted from the start of the last note ''' if note: time = config.music.feat2id['time'] n = config.music.E times = [feat[time] for feat in note] diffs = [0] + [t2-t1 for t1,t2 in zip(times[:-1], times[1:])] for i, diff in enumerate(diffs): note[i][time] = diff return note def midiCsvReader(filename): with open(filename, 'r') as f: for record in csv.reader(f): record = [ s.strip() for s in record ] track, time, rtype = record[:3] time, track = int(time), int(track) value = [ int(s) for s in record[3:] if s.isdigit() ] yield track, rtype, time, value @chunk def convert(filename): ''' Convert midi-csv file to note and tempo. input: midi: midi-csv filename output: note: list of Ci tracks with maximum notes track: list of notes with E features tempo: list of [time, value] time: int, the time at which the tempo changes value: int, the value of tempo ''' note, tempo, open_note = [], [], {} ppqn = 1 # pulses per beat for track, rtype, time, value in midiCsvReader(filename): time /= ppqn if rtype == 'Header': ppqn = value[-1] elif rtype == 'Tempo': tempo.append(Tempo(time, value[0]/config.tempo.default)) elif rtype.startswith('Note'): channel, pitch, volume = value # close the note, add to a track in the note if (track, channel, pitch) in open_note: if volume == 0 or rtype == 'Note_off_c': feat = open_note.pop((track,channel,pitch)) feat[id['duration']] = duration = time - feat[id['time']] note.append(feat) # open a new note elif rtype == 'Note_on_c': feat = [0]*len(config.music.id2feat) feat[id['pitch']] = pitch feat[id['volume']] = volume feat[id['time']] = time open_note[track,channel,pitch] = feat if len(tempo)==0: tempo.append(Tempo(0, 1)) return note, tempo <file_sep>#!/usr/bin/env python import io import logging logging.getLogger('jseg.jieba').setLevel(logging.ERROR) from flask import Flask, request, send_file import model para = 'model/test.para' model.use_cuda = False port = 80 static = 'gui' app = Flask('syf-server', static_url_path='', static_folder=static) def midigen(text): app.logger.debug("< {}".format(text)) midi = tr.translate(text) buff = io.BytesIO() midi.writeFile(buff) return buff def root(): if 'text' in request.args: buff = midigen(request.args['text']) buff.seek(0) return send_file(buff, attachment_filename='melody.mid') else: return app.send_static_file('index.html') tr = model.Translator() sd = model.load(para) tr.load_state_dict(sd) app.route('/')(root) app.route('/index.html')(root) app.run(debug=True, port=port, threaded=True, host='0.0.0.0') <file_sep>#!/usr/bin/env python from bs4 import BeautifulSoup import requests import midi import logging fmt = '%(name)s - %(levelname)s - %(message)s' logging.basicConfig(format=fmt, filename='crawler.log', filemode='w') logger = logging.getLogger('MIDIDownloader') sh = logging.StreamHandler() sh.setFormatter(logging.Formatter(fmt)) logger.addHandler(sh) import sys if len(sys.argv) > 1: PATH = sys.argv[1] else: PATH = '../data/raw' def mdownload(path): for pagelink in pagelinks: titlelinks=midi.songlink(pagelink) for songurl in titlelinks: try: midi.songtext(songurl,path) except Exception as e: logger.error(songurl) logger.error(e) result=requests.get('http://sql.jaes.ntpc.edu.tw/javaroom/midi/alas/Ch/ch.htm') page=result.text doc=BeautifulSoup(page,"html.parser") pagelist=doc.find_all('td') pagelinks=[page.find('a') for page in pagelist] while None in pagelinks: pagelinks.remove(None) pagelinks=[page.get('href') for page in pagelinks] pagelinks=['http://sql.jaes.ntpc.edu.tw/javaroom/midi/alas/Ch/'\ +page for page in pagelinks] mdownload(PATH) <file_sep>from bs4 import BeautifulSoup import requests import re import urllib import os import logging logger = logging.getLogger('MIDI') def songlink(url): result=requests.get(url) page=result.text doc=BeautifulSoup(page,"html.parser") titlelist=doc.find_all('a') titlelinks=[title.get('href') for title in titlelist] titlelinks=['http://sql.jaes.ntpc.edu.tw/javaroom/midi/alas/Ch/'+\ title for title in titlelinks] titlelinks=[re.sub('ch\d','Ch',title) for title in titlelinks] return titlelinks def songtext(url,path): result=requests.get(url) try: page=result.text.encode('ISO-8859-1').decode('big5') except Exception: page=result.text.encode('ISO-8859-1').decode('hkscs') doc=BeautifulSoup(page,"html.parser") test1=doc.find_all('td') titlyr=[t.text for t in test1] title='' while title=='': title=titlyr.pop(0) title=re.sub('[":]','-',title) title = ''.join(title.split()) titletxt=title+'.txt' lyr='\n'.join(titlyr) lyr=re.sub('\(轉載請標明出處,否則請勿引用\)','',lyr) lyr=lyr.strip('\n') lyr=re.sub('\xa0','',lyr) fout=open(os.path.join(path,titletxt),'wt') fout.write(lyr) fout.close() song=doc.find('bgsound') try: songurl=song.get('src') songurl='http://sql.jaes.ntpc.edu.tw/javaroom/midi/alas/Ch/'+songurl titlemid=title+'.mid' urllib.request.urlretrieve(songurl,os.path.join(path,titlemid)) except Exception: try: test1=doc.find_all('a') b=test1[1].get('href') songurl='http://sql.jaes.ntpc.edu.tw/javaroom/midi/alas/Ch/'+b titlemid=title+'.mid' urllib.request.urlretrieve(songurl,os.path.join(path,titlemid)) except Exception as pro: logger.error(title) logger.error(pro) <file_sep>DATA_DIR = data RAW_DIR = $(DATA_DIR)/raw CSV_DIR = $(DATA_DIR)/csv SEG_DIR = $(DATA_DIR)/seg WORD2VEC = $(DATA_DIR)/word-vectors.txt MIDICSV = midicsv PYTHON = python ICONV = iconv -f ISO-8859-1 -t utf-8 -o MIDI_FILES = $(wildcard $(RAW_DIR)/*.mid) TXT_FILES = $(wildcard $(RAW_DIR)/*.txt) CSV_FILES = $(MIDI_FILES:$(RAW_DIR)/%.mid=$(CSV_DIR)/%.csv) DATASET = $(DATA_DIR)/train.jsonl $(DATA_DIR)/valid.jsonl all: dataset crawl: | $(RAW_DIR) $(PYTHON) crawler/midi_download.py $(RAW_DIR) midi2csv: $(CSV_FILES) $(CSV_DIR) $(RAW_DIR) $(SEG_DIR): mkdir -p $@ TIMEOUT = timeout 9 $(CSV_FILES): $(CSV_DIR)/%.csv : $(RAW_DIR)/%.mid | $(CSV_DIR) -$(TIMEOUT) $(MIDICSV) "$<" | $(ICONV) "$@" word2vec: $(WORD2VEC) $(WORD2VEC): $(TXT_FILES) $(PYTHON) lyrics2vec.py dataset: $(DATASET) $(DATASET): $(WORD2VEC) $(PYTHON) dataset.py RM = rm -d clean: $(RM) $(RAW_DIR) $(CSV_DIR) $(SEG_DIR)
a4a8a0e022474cf6a5039406fb348b111fae1906
[ "Markdown", "Python", "Text", "Makefile" ]
12
Python
ht-dep/SingYourFeelings
1c302099ee22fc8a335864dd95087c1d5f08c981
fab8eccee01266f1af48090a7b63fcb2d672e982
refs/heads/master
<repo_name>nooberfsh/threadpool<file_sep>/README.md # threadpool A simple thread pool. ## Example ```rust extern crate threadpool; use threadpool::Task; use threadpool::Builder; struct Simple { name: String, } impl Task for Simple { fn run(&mut self) { println!("{} done", self.name); } } fn main() { let pool = Builder::new() .worker_count(4) .name("simple_thread_pool") .build(); for i in 0..100 { let s = Simple { name: format!("{}", i), }; pool.spawn(s); } } ``` <file_sep>/Cargo.toml [package] name = "threadpool" version = "0.1.0" authors = ["nooberfsh <<EMAIL>>"] [dependencies] crossbeam-channel = "0.1" num_cpus = "1.8" log = "0.4" [dev-dependencies] env_logger = "0.4" <file_sep>/src/lib.rs //! A simple thread pool. //! //! Example //! //! ``` //! use threadpool::Task; //! use threadpool::Builder; //! //! struct Simple { //! name: String, //! } //! //! impl Task for Simple { //! fn run(&mut self) { //! println!("{} done", self.name); //! } //! } //! //! let pool = Builder::new() //! .worker_count(4) //! .name("simple_thread_pool") //! .build(); //! for i in 0..100 { //! let s = Simple { //! name: format!("{}", i), //! }; //! pool.spawn(s); //! } //! ``` extern crate crossbeam_channel; #[macro_use] extern crate log; extern crate num_cpus; use std::thread::{self, JoinHandle}; use std::marker::PhantomData; use crossbeam_channel::{Receiver, Sender}; /// An error indicate the thread pool was dropped. #[derive(Debug)] pub struct Stopped; /// User's real task should implement this trait. /// /// Why not just use `FnOnce()`, use a user defined type can avoid /// dynamic dispatching. pub trait Task: Send + 'static { /// Run the task. fn run(&mut self); } /// ThreadPool builder. pub struct Builder<T: Task> { name: String, num: usize, _marker: PhantomData<T>, } /// ThreadPool pub struct ThreadPool<T: Task> { name: String, tx: Sender<Option<T>>, workers: Vec<Worker<T>>, } /// ThreadPool handle. /// /// It may return `Stopped` when spawning task. pub struct Handle<T: Task> { tx: Sender<Option<T>>, } impl<T: Task> Builder<T> { /// Create a thread pool builder using the default configuration. pub fn new() -> Self { Builder { name: "threadpool".into(), num: num_cpus::get(), _marker: PhantomData, } } /// Set the thread pool name. pub fn name<N: Into<String>>(mut self, name: N) -> Self { self.name = name.into(); self } /// Set worker count. pub fn worker_count(mut self, count: usize) -> Self { self.num = count; self } /// Create the thread pool. pub fn build(self) -> ThreadPool<T> { let mut workers = Vec::with_capacity(self.num); let (tx, rx) = crossbeam_channel::unbounded(); for i in 0..self.num { let rx = rx.clone(); let name = format!("{}_worker_{}", self.name, i); let worker = Worker::new(name, rx); workers.push(worker); } ThreadPool { name: self.name, tx: tx, workers: workers, } } } impl<T: Task> Default for Builder<T> { fn default() -> Self { Self::new() } } impl<T: Task> ThreadPool<T> { /// Create a thread pool using the default configuration. pub fn new() -> Self { Builder::new().build() } /// Get the thread pool name. pub fn name(&self) -> &str { &self.name } /// Get worker count. pub fn worker_count(&self) -> usize { self.workers.len() } /// Spawn a task. pub fn spawn(&self, task: T) { self.tx.send(Some(task)).unwrap(); } /// Get the thread pool handle. pub fn handle(&self) -> Handle<T> { Handle { tx: self.tx.clone(), } } } impl<T: Task> Default for ThreadPool<T> { fn default() -> Self { Self::new() } } impl<T: Task> Drop for ThreadPool<T> { fn drop(&mut self) { info!("ThreadPool: {} is dropping", self.name); for _ in 0..self.worker_count() { self.tx.send(None).unwrap(); } } } impl<T: Task> Handle<T> { /// Spawn a task. /// /// It may return `Stopped` when the thread pool was dropped. pub fn spawn(&self, task: T) -> Result<(), Stopped> { self.tx.send(Some(task)).map_err(|_| Stopped) } } /// Thread helper. struct Worker<T: Task> { thread: Option<JoinHandle<()>>, _marker: PhantomData<T>, } impl<T: Task> Worker<T> { fn new<N: Into<String>>(name: N, rx: Receiver<Option<T>>) -> Self { let thread = thread::Builder::new() .name(name.into()) .spawn(move || run(&rx)) .unwrap(); Worker { thread: Some(thread), _marker: PhantomData, } } } fn run<T: Task>(rx: &Receiver<Option<T>>) { while let Some(mut task) = rx.recv().unwrap() { task.run(); } } impl<T: Task> Drop for Worker<T> { fn drop(&mut self) { self.thread.take().unwrap().join().unwrap(); } } #[cfg(test)] mod tests { use super::*; use std::time::{Duration, Instant}; #[test] fn test_threadpool() { let pool = Builder::new().worker_count(2).build(); let (tx, rx) = crossbeam_channel::unbounded(); let start = Instant::now(); for dur in vec![500, 1000, 1500] { let task = MyTask { dur: dur, tx: tx.clone(), }; pool.spawn(task); } assert_eq!(rx.recv().unwrap(), 500); assert_eq!(rx.recv().unwrap(), 1000); assert_eq!(rx.recv().unwrap(), 1500); assert!(start.elapsed() > Duration::from_millis(2000)); assert!(start.elapsed() < Duration::from_millis(3000)); } #[test] fn test_handle() { let pool = Builder::new().worker_count(2).build(); let handle = pool.handle(); drop(pool); let res = handle.spawn(Empty); assert!(res.is_err()); } struct MyTask { dur: u64, tx: Sender<u64>, } impl Task for MyTask { fn run(&mut self) { thread::sleep(Duration::from_millis(self.dur)); self.tx.send(self.dur).unwrap(); } } struct Empty; impl Task for Empty { fn run(&mut self) {} } }
e0161c49b4470d244fff589979209c62471630d8
[ "Markdown", "TOML", "Rust" ]
3
Markdown
nooberfsh/threadpool
4b3450aed001f6d7cb5343f0d6dddbc3ba02d45c
4707016ce8c95f57038e966936044c02cf658589
refs/heads/master
<repo_name>ISEL-HGU/MulticollinearityExpTool<file_sep>/src/main/java/edu/handong/csee/isel/weka/DataImbalance.java package edu.handong.csee.isel.weka; import weka.core.Instances; import weka.filters.Filter; import weka.filters.supervised.instance.SMOTE; import weka.filters.supervised.instance.SpreadSubsample; public class DataImbalance { public Instances spreadSubsampling(Instances trainData) throws Exception { // training data undersampling final SpreadSubsample spreadsubsample = new SpreadSubsample(); spreadsubsample.setInputFormat(trainData); spreadsubsample.setDistributionSpread(1.0); trainData = Filter.useFilter(trainData, spreadsubsample); return trainData; } public Instances smote(Instances trainData) throws Exception { // smote final SMOTE smote = new SMOTE(); smote.setInputFormat(trainData); smote.setNearestNeighbors(1); trainData = Filter.useFilter(trainData, smote); return trainData; } }
f88f4215772f6f6b957382b2cee1761a37acede3
[ "Java" ]
1
Java
ISEL-HGU/MulticollinearityExpTool
f99d4111fb3f83d946b461f6f09a4fec47726cd0
e814713f739c267927e0efacb14b7db399a4af55
refs/heads/main
<repo_name>lokinder1/Simple_Mern_Short_Demo_ErrorBoundaries<file_sep>/client/src/index.js import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; // In dev mode React will still shows errors after catching with ErrorBoundary if (process.env.NODE_ENV === "development") { import("react-error-overlay").then((m) => { m.stopReportingRuntimeErrors(); }); } ReactDOM.render(<App />, document.getElementById("root")); <file_sep>/client/src/components/HomeComponent.js import * as React from "react"; import { ErrorBoundary } from "react-error-boundary"; import Paper from "@material-ui/core/Paper"; import { makeStyles } from "@material-ui/core/styles"; import TextField from '@material-ui/core/TextField'; const useStyles = makeStyles(() => ({ root: { flexGrow: 1, "overflow-x": "hidden", }, main: { width: "100%", }, errorComponent: { padding: " 50px !important", margin: " 10px !important", }, button: { margin: " 8px !important", }, })); function ErrorFallback({ error, resetErrorBoundary }) { const classes = useStyles(); return ( <Paper className={classes.errorComponent}> <p>Something went wrong:</p> <pre style={{ color: "red" }}>{error.message}</pre> <button onClick={resetErrorBoundary}>Try again</button> </Paper> ); } function Bomb({ username }) { if (username === "bomb") { throw new Error("💥 CABOOM 💥"); } return `Hi ${username}`; } export default function Home() { const [username, setUsername] = React.useState(""); const usernameRef = React.useRef(null); const classes = useStyles(); return ( <div className={classes.main}> <TextField id="input1" label="Username (don't type bomb)" value={username} ref={usernameRef} placeholder={`type "bomb"`} onChange={(e) => setUsername(e.target.value)} fullWidth /> <div> <ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => { setUsername(""); usernameRef.current.focus(); }} resetKeys={[username]} > <Bomb username={username} /> </ErrorBoundary> </div> </div> ); } <file_sep>/README.md # Simple_MERN_Short_Demo_ErrorBoundaries It's a simple example or demo project to show Error Boundaries usage it's made by using following technologies - ReactJS - MaterialUI ## How To Run ``` - Client 1. Move To Client Directory cd Client/ 2. Install Packages yarn 3. start App yarn start ``` ## Tasks Completed 1. Homepage 2. Basic Error Boundary ## Demo ScreenShots - Error Occurred ![error](error.png) - No Error Occurred ![noError](noError.png)
7900776b1fec2dda99f2a7af00efd258b36f6169
[ "JavaScript", "Markdown" ]
3
JavaScript
lokinder1/Simple_Mern_Short_Demo_ErrorBoundaries
f1b3e963576b8ad6708b932942ab154f64e46f43
e7c949077e295cbaa58c7d472063ed63e355190d
refs/heads/master
<file_sep>import React, { Component } from "react"; import PropTypes from "prop-types" import { Link } from "react-router-dom" import Book from "./Book" import * as BooksAPI from "../BooksAPI" export default class Search extends Component { static propTypes = { books: PropTypes.array.isRequired, updateShelf: PropTypes.func.isRequired } state = { searchedBooks: [], query: "" } // Update query as user starts typing updateQuery = (query) => { this.setState({ query: query }) if (query !== "") { this.searchQuery(query); } else { this.setState({ searchedBooks: [] }); } } //return the search result (if any) searchQuery(query) { BooksAPI.search(query).then(searchResult => { if (searchResult) { this.setState({ searchedBooks: searchResult }) } else { this.setState({ searchedBooks: [] }) } }) } render() { const { books, updateShelf } = this.props; const { query, searchedBooks } = this.state; return ( < div className = "search-books" > < div className = "search-books-bar" > < Link to = "/" className = "close-search" > Close < /Link> < div className = "search-books-input-wrapper" > < input type = "text" placeholder = "Search by title or author" value = { query } onChange = { (e) => this.updateQuery(e.target.value) } /> < /div> < /div> < div className = "search-books-results" > { query && ( < div className = "showing-contacts" > < span > Search for "{query}" shows { searchedBooks.length > 0 ? searchedBooks.length : "0" } results < /span> < /div> ) } < ol className = "books-grid" > { searchedBooks.length > 0 && searchedBooks.map((book) => ( < li key = { book.id } > < Book book = { book } books = { books } updateShelf = { updateShelf } /> < /li> )) } < /ol> < /div> < /div> ) } } <file_sep># Book Tracking App --- ## Description This app utilizes the React framework to create an app for ordering your readings. It allows you to sort the books you read into three categories: 1. Now Reading 2. Want to Read 3. Already Read. It also allows to filter the books by the title or author. The app was developed within the Udacity Front End Developer Nanodegree. ## How to run this app 1. download/clone this project to your desktop: ``` git clone https://github.com/kasiaphilly/reactnd-project-myreads-starter.git ``` 2. open cmd / terminal and navigate to the project folder 3. run the following commands: ``` npm install npm start ``` 4. open the website on your local server ## Dependencies This app uses html, css, JavaScript and the React framework. ## Resources 1. [Udacity starter kit](https://github.com/udacity/reactnd-project-myreads-starter) 2. [JavaScript beautifier](https://www.danstools.com/javascript-beautify/) 3. Book cover [placeholder image](https://www.google.com/url?sa=i&source=images&cd=&ved=2ahUKEwjU7Kqwsc_eAhXNmuAKHYUZCRAQjRx6BAgBEAU&url=https%3A%2F%2Fwww.libreture.com%2Flibrary%2FMasseR%2Fbook%2Fmetamorphosis%2F&psig=AOvVaw3TioS3II4HC2Qtxr9SfnUe&ust=1542129335021685)
b01c5086e1fee5e4954eb30ada469b119504a82e
[ "JavaScript", "Markdown" ]
2
JavaScript
kasiaphilly/reactnd-project-myreads-starter
e15df41853fb63263eb1a4029e9a4d83790c8ab1
d8e01d63d85ad40aefd21801c533061b042fc75f
refs/heads/master
<repo_name>borrow-ui/borrow-ui<file_sep>/packages/ui/src/components/table/Table.types.ts type alignType = string; type verticalAlignType = string; export type TableColumnType = { /** Name of property of the entry */ prop: string; /** Title of the column */ title?: string; align?: alignType; verticalAlign?: verticalAlignType; width?: number | string; padding?: number; }; export type TableConfigType = { borderType?: 'none' | 'row' | 'cell'; verticalAlign?: verticalAlignType; align?: alignType; zebra?: boolean; }; export type TableStateType = { columns: Array<TableColumnType>; page: number; pageSize: number; }; export type TableSetStateType = React.Dispatch<React.SetStateAction<TableStateType>>; export type TableEntryType = { [key: string]: any }; type TableSetPageType = (page: number) => void; // React.Dispatch<React.SetStateAction<number>>; interface TableContainerProps extends React.ComponentPropsWithoutRef<React.ElementType> {} export type TableCellElementsPropsType = { /** Props added to the cell element (th, td). * If `getProps` function is passed, it will be called with two arguments, * `column` and `entry`, which represents the current column and the current * entry. In the header, `entry` is not passed. */ cellProps?: TableCellContainerPropsValueType; /** Props added to the cell content element (the div inside th or td). * If `getProps` function is passed, it will be called with two arguments, * `column` and `entry`, which represents the current column and the current * entry. In the header, `entry` is not passed. */ cellContentProps?: TableCellContainerPropsValueType; containerProps?: TableContainerProps; }; export interface TableProps { columns: Array<TableColumnType>; entries: Array<TableEntryType>; config?: TableConfigType; pagination?: { pageSize: number; }; statusBar?: { visible: boolean; }; className?: string; elementsProps?: TableCellElementsPropsType; } export interface TableWrapperProps { className?: string; tableConfig: TableConfigType; tableState: TableStateType; entries: Array<TableEntryType>; elementsProps: TableCellElementsPropsType; } export interface TableHeadProps { className?: string; tableConfig: TableConfigType; tableState: TableStateType; elementsProps: TableCellElementsPropsType; } export interface TableBodyProps { className?: string; tableConfig: TableConfigType; tableState: TableStateType; entries: Array<TableEntryType>; elementsProps: TableCellElementsPropsType; } export type TableCellContainerNameType = 'cellProps' | 'cellContentProps'; export type TableCellContainerPropsType = { className?: string; verticalAlign?: verticalAlignType; align?: alignType; }; export type TableCellContainerPropsValueType = { getProps?: (column: TableColumnType, entry?: TableEntryType) => TableConfigType; verticalAlign?: verticalAlignType; align?: alignType; }; export interface TableCellProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; Tag?: 'td' | 'th'; tableConfig: TableConfigType; elementsProps: TableCellElementsPropsType; column: TableColumnType; entry?: TableEntryType; } export interface TableStatusBarProps { tableState: TableStateType; totEntries: number; } export interface TablePaginationProps { tableState: TableStateType; setTableState: TableSetStateType; totEntries: number; } export interface TablePaginationPageProps { label?: React.ReactNode; pageNumber: number; page?: number; setPage: TableSetPageType; } <file_sep>/packages/ui/src/components/link/Link.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Link } from './Link'; <Meta title="Components/Link" component={Link} /> # Link Links are used to create connections between pages and to external content. The `Link` component can be used as a standard link (`a` tag) or customized to use another component (like `react-router-dom`'s `Link`). <Canvas> <Story name="Default"> <div> A normal link with "a" tag <Link>looks like this</Link>. </div> </Story> </Canvas> By default the link is underlined, but the decoration can be turned off by using the `underline` property: <Canvas> <Story name="Witohut Underline"> <div> A link without underline <Link underline={false}>looks like this</Link>. </div> </Story> </Canvas> ## Default tag The default tag is `a` tag and it is obtained from config function called `getLinkComponent`. This is a function that returns a valid component or tag. The setting can be changed with config setter function called `setConfig`. In your `App.js` or `index.js` file you can call the function and set your custom one: ```jsx import { Link as RouterLink } from 'react-router-dom'; import { setConfig } from '@borrow-ui/ui'; setConfig('getLinkComponent', () => RouterLink); export default function App() { // ... } ``` This can always be overridden by specifying the `tag` prop. ## Props <ArgsTable of={Link} /> <file_sep>/packages/ui/src/components/lorem/Lorem.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Lorem } from './Lorem'; <Meta title="Components/Lorem" component={Lorem} /> # Lorem When developing pages sometimes is useful to have pre-generated text as placeholder. The `Lorem` component can be used precisely for this. A `paragraphs` prop can be used to specify how many text paragraphs should be rendered (from 1 to 3). <Canvas> <Story name="Default"> <div> <Lorem paragraphs={3} /> </div> </Story> </Canvas> ## Props <ArgsTable of={Lorem} /> <file_sep>/packages/ui/src/components/tabs/Tabs.types.ts import { TagType } from '../../utils/sharedTypes'; interface TabInterface extends React.ComponentPropsWithoutRef<React.ElementType> { label: React.ReactNode; content: React.ReactNode; } interface TabForwardProps extends React.ComponentPropsWithoutRef<React.ElementType> { className?: string; } export interface TabsProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** The list of tabs. Each list element is an object with `label` and `content` keys */ tabs: Array<TabInterface>; /** Specifies which tab will be open by default (starts from 1) */ firstOpen?: number; /** Applies padding to all body's sides */ padded?: boolean; /** Applies padding only on body's top */ paddedTop?: boolean; /** Properties to forward to TabHeader */ tabHeaderProps?: TabForwardProps; /** Properties to forward to TabBody */ tabBodyProps?: TabForwardProps; className?: string; } export interface TabHeaderProps { tabs: Array<TabInterface>; className?: string; /** Selected tab number (starts from 1) */ selectedTab: number; /** Function called when tab is selected */ setSelectedTab: React.Dispatch<React.SetStateAction<number>>; /** Element to be shown after all labels */ extraHeader?: React.ReactNode; } export interface TabBodyProps { tabs: Array<TabInterface>; className?: string; /** Selected tab number (starts from 1) */ selectedTab: number; /** Applies padding to all sides */ padded: boolean; /** Applies padding only on top */ paddedTop: boolean; } <file_sep>/packages/website-next/components/home/PageExample.js import { useRouter } from 'next/router'; import { Title, Text, Button, Row, Col, Link, Monospace, SyntaxHighlight } from '@borrow-ui/ui'; import styles from './home.module.scss'; export function PageExample() { const router = useRouter(); const navigate = (e, href) => { e.preventDefault(); router.push(href); }; return ( <div className={styles['home__page-example']}> <Title>Page Example</Title> <Row> <Col colClassName="col-xs-12 col-sm-12 col-md-12 col-lg-6"> <Text> Create website pages by writing MDX code instead of verbose HTML/JSX. </Text> <Text> With <Link href="https://mdxjs.com/">MDX</Link> you can write Markdown files and use JSX components: every compoment you add to your library will be usable directly in the <Monospace>.mdx</Monospace> files. </Text> <Text> If you need additional components for a specific section of the website, you can include them together with the library components and make them available as well. </Text> <Text> The example shows how to setup a <Monospace>[slug].js</Monospace> file that will source the content from the mdx files inside a <Monospace>content/blog</Monospace> folder. </Text> <Text className="flex-center-center" style={{ margin: 60 }}> <Button size="big" mean="secondary" onClick={(e) => navigate(e, '/blog')}> See this in action here! </Button> </Text> <Text>A simple page looks like this:</Text> <SyntaxHighlight code={samplePage} language="mdx" /> </Col> <Col colClassName="col-xs-12 col-sm-12 col-md-12 col-lg-6"> <Text> Prepare the <Monospace>[slug].js</Monospace> page like this: </Text> <SyntaxHighlight code={sampleSlug} language="jsx" /> </Col> </Row> </div> ); } let samplePage = `--- title: Code Example --- Hello! Welcome to my first blog post, created with mdx and borrow-ui. This is how you start the development server for this website: <div className="flex-center-center"> <Terminal className="m-b-20 w-400 m-r-20 m-l-20" title="Next.js website" code="yarn dev" language="bash" /> </div> `; let sampleSlug = `import path from 'path'; import React from 'react'; import Head from 'next/head'; import { MDXRemote } from 'next-mdx-remote'; import { MDXProvider } from '@mdx-js/react'; import * as uiLibrary from '@borrow-ui/ui'; import { Terminal } from '../../components/common/Terminal'; import { generateGetStaticPaths, generateGetStaticProps } from '../../core/mdx/mdx'; import { providerComponents } from '../../core/mdx/providerComponents'; const SOURCE_PATH = path.join(process.cwd(), 'content/blog'); // Extends components available in the mdx const mdxComponents = { ...uiLibrary, Terminal }; const { Title } = uiLibrary; // use components here as well const Content = ({ code, metadata }) => { return <> <Head> <title>Blog</title> <meta property="og:title" content="Blog" key="title" /> </Head> <MDXProvider components={providerComponents}> <Title className="color-primary">{metadata.title}</Title> <MDXRemote {...code} components={mdxComponents} /> </MDXProvider> </> }; export const getStaticProps = generateGetStaticProps(SOURCE_PATH); export const getStaticPaths = generateGetStaticPaths(SOURCE_PATH); export default Content;`; <file_sep>/packages/ui/src/config.ts import { FunctionComponent, ElementType } from 'react'; export const UI_PREFIX: string = 'borrow-ui'; export const SIZES = ['smaller', 'small', 'normal', 'big', 'bigger', 'huge'] as const; type GenericFunctionType = () => any; type FunctionReactTagType = () => FunctionComponent | ElementType; interface IConfig { getLocation: GenericFunctionType; getLinkComponent: FunctionReactTagType; smallScreenMaxWidth: number; } export const config: IConfig = { getLocation: () => {}, getLinkComponent: () => 'a', smallScreenMaxWidth: 599, }; export type configSettingType = keyof IConfig; export type configSettingValue = number | GenericFunctionType | FunctionReactTagType; export const setConfig = <K extends configSettingType>(setting: K, value: IConfig[K]): boolean => { if (!config.hasOwnProperty(setting)) { console.error('Invalid setting:', setting); return false; } config[setting] = value; return true; }; export const getConfig = (setting: configSettingType): configSettingValue => config[setting]; <file_sep>/packages/ui/src/components/forms/toggle/Toggle.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; import { Field } from '../field/Field'; import { Toggle } from './Toggle'; <Meta title="Forms/Components/Toggle" component={Toggle} /> # Toggle `Toggle` component can be used as an alternative of checkboxes. <Canvas> <Story name="Default"> <FormsStoryWrapper initialState={{ value: true }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Close the window when the process is done"> <Toggle checked={state.value} onClick={() => setState({ value: !state.value })} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> Disabled status is supported as well via `disabled` prop: <Canvas> <Story name="Disabled"> <FormsStoryWrapper initialState={{ value: true }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Close the window when the process is done"> <Toggle checked={state.value} disabled={true} onClick={() => setState({ value: !state.value })} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Props <ArgsTable of={Toggle} /> <file_sep>/packages/dashboard/src/App.js import { useContext, useState, useEffect } from 'react'; import { BrowserRouter, Link, useLocation } from 'react-router-dom'; import { SidebarContext, getSidebarContextDefaultState, setConfig } from '@borrow-ui/ui'; import { Header } from './components/layout/Header'; import { MainSidebar } from './components/layout/MainSidebar'; import { storeContext, StoreProvider, initializeStore } from './store'; import { MainRoutes } from './Routes'; /** * Set react-router-dom default hook and component as default * for borrow-ui components. */ setConfig('getLocation', useLocation); setConfig('getLinkComponent', () => Link); function App() { /** * Ideally, also a store provider (i.e. Redux) can be placed here, * to wrap the entire application with the main store. * * For the purpose of this dashboard, we will use a dummy store based on * React's Context API. We will be able to consume a store/setStore pair * when using the store context in the forms, list and detail pages. * Store value can be taken from the store context: * * const { store } = useContext(storeContext); * */ return ( <div className="borrow-ui"> <StoreProvider> <DashboardApp /> </StoreProvider> </div> ); } function DashboardApp() { const { store, setStore } = useContext(storeContext); useEffect(() => { if (!store.applicationLoaded && !store.initializing) { setStore((s) => ({ ...s, initializing: true })); initializeStore(store, setStore) .then(() => { setStore((s) => ({ ...s, applicationLoaded: true, initializing: false })); }) .catch(console.error); } }, [store, setStore]); /** * Create a Sidebar context state, and pass to the context provider. * This will set a provider for the main sidebar and will allow * the trigger on the Header to open/collapse the main sidebar. */ const sidebarState = useState(getSidebarContextDefaultState()); /** * A router provider can also be set here. * * Why creating this component and not add everything in App? * A reason is to have distinction below between logged user or not, * showing a login screen instead of header+sidebar+content. */ return ( <BrowserRouter> <SidebarContext.Provider value={sidebarState}> <Header /> <div className="flex w-100pc"> <MainSidebar /> <MainRoutes /> </div> </SidebarContext.Provider> </BrowserRouter> ); } export default App; <file_sep>/packages/dashboard/src/apps/books/components/books/BooksList.js /** * Shows the list of books in a tabular format, by using the * simple Table components. * */ import { useMemo } from 'react'; import PropTypes from 'prop-types'; import { Link, Loader, Table } from '@borrow-ui/ui'; import { BOOKS_BOOK_BASE_URL } from 'apps/books/constants'; import { DeleteBookButton } from './DeleteBookButton'; const TABLE_COLUMNS = [ { prop: 'title_link', title: 'Title' }, { prop: 'subtitle', title: 'Subtitle' }, { prop: 'isbn13', title: 'ISBN' }, { prop: 'controls', title: '' }, ]; export function BooksList({ books, deleteBook, showSubtitle = true }) { let columns = deleteBook ? TABLE_COLUMNS : TABLE_COLUMNS.filter((col) => col.prop !== 'controls'); if (!showSubtitle) columns = columns.filter((col) => col.prop !== 'subtitle'); const booksList = useMemo(() => { if (!books) return null; return books.map((book) => ({ ...book, title_link: <Link to={`${BOOKS_BOOK_BASE_URL}/${book.isbn13}`}>{book.title}</Link>, controls: deleteBook ? ( <> <DeleteBookButton book={book} deleteBook={deleteBook} buttonProps={{ size: 'smaller', flat: true }} /> </> ) : null, })); }, [books, deleteBook]); if (!books) return ( <div className="flex-center-center h-200"> <Loader /> </div> ); return <Table entries={booksList} columns={columns} pagination={{ pageSize: 5 }} />; } BooksList.propTypes = { /** List of books */ books: PropTypes.array.isRequired, /** Function to call to delete a book. If not passed, * controls column will not be rendered */ deleteBook: PropTypes.func, }; <file_sep>/packages/ui/src/components/forms/toggle/Toggle.types.ts export interface ToggleProps extends React.ComponentPropsWithRef<React.ElementType> { /** Function called when the toggle is clicked */ onClick: (newToggleStatus: boolean) => void; /** Function called when the toggle is clicked (to keep same prop of other fields) */ onChange: (newToggleStatus: boolean) => void; checked?: boolean; disabled?: boolean; className?: string; } <file_sep>/packages/ui/src/components/card/Card.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Card } from './Card'; import { Button } from '../button/Button'; import { Icon } from '../icon/Icon'; <Meta title="Components/Card" component={Card} /> # Card The `Card` component creates a card with a `side` and a `main` part. The `side` part is used to render an icon (see `Icon` component). The `main` part has different properties: - a `title`, rendered on top; - a `subtitle`, rendred below the title; - a `description`, the main content of the card; - `controls`, rendered at the bottom, that can be used to add buttons or another description. Each of the sections have a dedicated prop that can be used to customize the section (i.e. `titleProps` - see the Props table below). <Canvas> <Story name="Default"> <Card standingHover={true} icon={<Icon name="home" size="big" className="color-primary" />} title="Card sample" subtitle="Subtitle goes here" description="Card can have content, called description, as well as title and subtitle. Check the hover!" className="m-b-20" style={{ maxWidth: 500 }} sideProps={{ className: 'color-primary-bg' }} controls={ <Fragment> <div>Controls Content</div> <div> <Button mean="neutral-reverse" className="m-r-5"> Secondary </Button> <Button mean="positive" onClick={() => window.alert('Clicked')}> Click me </Button> </div> </Fragment> } /> </Story> </Canvas> ## Variations A card can be rendered without icon and controls as well: <Canvas> <Story name="Simple"> <Card standingHover={true} title="Card sample" subtitle="Example of a card" description="This card has only the main elements: title, subtitle and description. It also has fixed width." className="m-b-20 w-400" /> </Story> </Canvas> or with a custom side content (different from an icon) through `sideContent` prop: <Canvas> <Story name="Side Content"> <Card title="Card sample" subtitle="Example of a card" sideContent={<div className="flex-center-center">Hello :)</div>} sideProps={{ style: { backgroundColor: '#eee' } }} description="This card has only the main elements: title, subtitle and description. It also has fixed width." className="m-b-20 w-400" /> </Story> </Canvas> ## Props <ArgsTable of={Card} /> <file_sep>/packages/ui/src/components/tabs/Tabs.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Lorem } from '../lorem/Lorem'; import { Tabs } from './Tabs'; import { TabHeader } from './TabHeader'; import { TabBody } from './TabBody'; <Meta title="Components/Tabs" component={Tabs} /> # Tabs Tabs are a common way to separate content by context. The `Tabs` component allows to create tabs in a simple way. It expects a `tabs` prop as a list of objects: each object has must have two keys, `label` and `content`. Tabs are managed as a list; the initial open item can be set by using the tab's index value with `firstOpen` prop. This index starts from 1. <Canvas> <Story name="Default"> <Tabs tabs={[ { label: 'First', content: ( <Block> <h2>First</h2> <Lorem paragraphs={1} /> </Block> ), }, { label: 'Default', content: ( <Block> <h2>Default</h2> <Lorem paragraphs={2} /> </Block> ), }, { label: 'Third', content: ( <Block> <h2>Third</h2> <Lorem paragraphs={3} /> </Block> ), }, { label: 'Fourth', content: ( <Block> <h2>Fourth</h2> <Lorem paragraphs={1} /> </Block> ), }, ]} firstOpen={2} /> </Story> </Canvas> `Tabs` component is divided into two parts: header and body. Header is rendered by `TabHeader` component, while body by `TabBody` component. Extra properties can be passed to them via `tabHeaderProps` and `tabBodyProps` props. ### Extra Header component It's possible to include another component after the autogenerated labels, by using `extraHeader` prop. This is contained in a flex div which occupies all horizontal space. <Canvas> <Story name="Extra Header"> <Tabs tabs={[ { label: 'First', content: ( <Block> <h2>First</h2> <Lorem paragraphs={1} /> </Block> ), }, { label: 'Default', content: ( <Block> <h2>Default</h2> <Lorem paragraphs={2} /> </Block> ), }, ]} firstOpen={2} tabHeaderProps={{ extraHeader: ( <span style={{ fontSize: 'small', color: '#888' }}> Click on a label to change body content. </span> ), }} /> </Story> </Canvas> ## Tabs Props <ArgsTable of={Tabs} /> ## TabHeader Props <ArgsTable of={TabHeader} /> ## TabBody Props <ArgsTable of={TabBody} /> <file_sep>/packages/website-next/pages/_app.js import '../layout/thirdParty'; import '../styles/project-ui.scss'; import { Layout } from '../layout/Layout'; function MyApp({ Component, pageProps }) { return <Layout Component={Component} pageProps={pageProps} />; } export default MyApp; <file_sep>/packages/ui/src/components/text/Subtitle.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Lorem } from '../lorem/Lorem'; import { Title } from './Title'; import { Subtitle } from './Subtitle'; <Meta title="Components/Typography/Subtitle" component={Subtitle} /> # Subtitle `Subtitle` component can be used under a title to add more context information. <Canvas> <Story name="Default"> <Title>This will have a subtitle</Title> <Subtitle>This is the component tested</Subtitle> <Lorem /> </Story> </Canvas> ## Subtitle Props <ArgsTable of={Subtitle} /> <file_sep>/packages/ui/src/components/forms/react-select/ReactSelect.types.ts type ReactSelectOptionType = { value: any; label: string; [key: string]: any; }; type ReactSelectValueType = string | number; export type MappedOptionsType = { [key: string | number]: any; }; export interface ReactSelectProps extends React.ComponentPropsWithRef<React.ElementType> { options: Array<ReactSelectOptionType>; /** Current Selected value. Specify the `key` value to select an element from the options. */ value?: ReactSelectValueType | Array<ReactSelectValueType> | null; /** Customize which is the key to be used to determine the value */ key?: string; /** Specifies if the selection is invalid */ invalid?: boolean; /** Allow multiple options to be selected */ isMulti?: boolean; /** Allows to add an option to the list directly from the input */ creatable?: boolean; disabled?: boolean; className?: boolean; } <file_sep>/packages/ui/src/components/forms/input/Input.types.ts export interface InputProps extends React.ComponentPropsWithRef<React.ElementType> { className?: string; } <file_sep>/packages/ui/src/components/icon/Icon.types.ts import { SIZES } from '../../config'; export const ICON_SIZES = [...SIZES] as const; export type IconSizes = typeof SIZES[number]; export const ICON_MODIFIERS = ['clickable', 'spin', '90deg', '180deg', '270deg'] as const; export type IconModifiers = typeof ICON_MODIFIERS[number]; export type IconFamilyType = 'material-icons' | 'fa' | 'fas' | 'fab'; export interface IconProps extends React.ComponentPropsWithoutRef<React.ElementType> { name?: string; /** Adds a class with the family name */ family?: IconFamilyType; /** Available modifiers: `clickable`, `spin`, `90deg`, `180deg`, `270deg` */ modifiers?: IconModifiers | IconModifiers[]; className?: string; /** Size of the icon: `smaller`, `small`, `normal`, `big`, `bigger`, `huge` */ size?: IconSizes; onClick?: React.MouseEventHandler; onKeyDown?: React.KeyboardEventHandler; } <file_sep>/packages/dashboard/src/apps/books/pages/books/forms/AddBookPage.js /** * This page shows an empty book form and has the logic to connect * the form with the store. * * The actions are passed down, so the BookForm is store independent. */ import { useContext } from 'react'; import { useNavigate } from 'react-router-dom'; import { Page } from '@borrow-ui/ui'; import { storeContext } from 'store'; import { BOOKS_BOOK_BASE_URL, BOOKS_BASE_URL } from 'apps/books/constants'; import { booksModel } from 'apps/books/models/book'; import { BookForm } from 'apps/books/components/books/BookForm'; export function AddBookPage() { const navigate = useNavigate(); const { setStore } = useContext(storeContext); const onSubmit = (newBook) => { return booksModel.add(setStore, newBook).then(() => { navigate(`${BOOKS_BOOK_BASE_URL}/${newBook.isbn13}`); }); }; const onCancel = () => navigate(BOOKS_BASE_URL); return ( <Page title="Add new book"> <BookForm onSubmit={onSubmit} onCancel={onCancel} /> </Page> ); } <file_sep>/packages/website-next/README.md This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). ## Installation All the dependencies shuold have been installed already for the monorepo, otherwise run: ```bash yarn ``` This will install all the dependencies. The component library, (@borrow-ui/ui workspace) is already configured to work for this website. ## Getting Started To run the development server, run: ```bash yarn dev ``` You should be able to open [http://localhost:3000](http://localhost:3000) with your browser and see the project home page. There are the following pages created as a demonstration: - `pages/index.js`: this is the home page entry point. A `Home` component has been created and places in `components/home` folder; - `pages/blog/*`: an example of a blog section, with a customized `index.js` file (hybrid MDX/JSX) and the blog posts loaded only from MDX files; - `pages/project/*`: an example of a full-MDX section, including `index` page (reachable from `/project` URL). The code is commented where needed and explanations are added to the first blog post. ## Build You can build this project by running ```bash yarn build ``` This will create a folder, `.next`, with the built version. <file_sep>/packages/ui/src/components/forms/react-select/ReactSelect.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; import { Field } from '../field/Field'; import { ReactSelect } from './ReactSelect'; <Meta title="Forms/Components/ReactSelect" component={ReactSelect} /> # ReactSelect `ReactSelect` component is a wrapper around [react-select](https://react-select.com/home)'s `Select` or `CreatableSelect` components, based on `creatable` prop. <Canvas> <Story name="Default"> <FormsStoryWrapper initialState={{ country: null }}> {({ state, setState }) => { return ( <div style={{ width: 400, marginBottom: 200 }}> <Field label="Select your country"> <ReactSelect options={[ { value: 'Italy', label: 'Italy' }, { value: 'spain', label: 'Spain' }, ]} value={state.country ? state.country.value : null} onChange={(obj) => setState({ country: obj })} isClearable={true} /> </Field> <div> <span style={{ marginRight: 10 }}>Selected country:</span> {state.country ? state.country.label : 'No country selected'} </div> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Cretable: Tags An example of `creatable` property is to enable tag associations: <Canvas> <Story name="Creatable"> <FormsStoryWrapper initialState={{ tags: [{ value: 'bug', label: 'bug' }] }}> {({ state, setState }) => { return ( <div style={{ width: 400, marginBottom: 200 }}> <Field label="Select some tags"> <ReactSelect options={['bug', 'help needed', 'production'].map((v) => ({ value: v, label: v, }))} value={ state.tags.length > 0 ? state.tags.map((obj) => obj.value) : [] } onChange={(tags) => { setState({ tags }); }} isMulti={true} creatable={true} isClearable={true} /> </Field> <div> <span style={{ marginRight: 10 }}>Selected tags:</span> {state.tags.length > 0 ? state.tags.map((tag) => tag.label).join(', ') : 'No tags selected'} </div> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Props <ArgsTable of={ReactSelect} /> <file_sep>/packages/ui/src/components/button/Button.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from './Button'; <Meta title="Components/Button" component={Button} /> # Button The `Button` renders a button. With the `mean` property we can define the style: - `neutral` - `primary` - `positive` - `negative` - `warning` - `accent` Using this property will automatically adds a class. A `-reverse` suffix can be added to use reverse colors. <Canvas> <Story name="Default"> <div> <div> <Button mean="neutral">Neutral</Button> <Button mean="neutral-reverse">Neutral Reverse</Button> <Button mean="primary">Primary</Button> <Button mean="primary-reverse">Primary Reverse</Button> <Button mean="accent">Accent</Button> <Button mean="accent-reverse">Accent Reverse</Button> </div> <div> <Button mean="positive">Positive</Button> <Button mean="positive-reverse">Positive Reverse</Button> <Button mean="negative">Negative</Button> <Button mean="negative-reverse">Negative Reverse</Button> <Button mean="warning">Warning</Button> <Button mean="warning-reverse">Warning Reverse</Button> </div> </div> </Story> </Canvas> The size of the button can be controlled with the `size` prop (default is `normal`): <Canvas> <Story name="Size"> <div> <Button mean="accent" size="smaller"> Smaller </Button> <Button mean="accent" size="small"> Small </Button> <Button mean="accent" size="normal"> Normal </Button> <Button mean="accent" size="big"> Big </Button> <Button mean="accent" size="bigger"> Bigger </Button> <Button mean="accent" size="huge"> Huge </Button> </div> </Story> </Canvas> Showcase of other props using `flat` and `icon`; If you want to put aside buttons with and without icon, use `flex` display for the parent component: <Canvas> <Story name="Flat and Icon"> <div style={{ display: 'flex', padding: 5 }}> <Button mean="primary" flat={true}> Flat </Button> <Button mean="primary" icon="home"> Home </Button> <Button mean="primary" icon="home" iconProps={{ style: { color: 'red' } }}> Red Home </Button> <Button mean="primary" flat={false}> Non Flat </Button> </div> </Story> </Canvas> ## Props <ArgsTable of={Button} /> --- ## React Tutorial Button component allows to create consistent buttons with basic meanings: neutral, primary, semaphore (positive/negative/warning) and accentuated. To start, we can define some CSS classes (one for each mean) and associate a `mean` prop: ```jsx import React from 'react'; export function Button({ mean='neutral', children, ...rest }) { const className = `button button--${mean}`; return ( <button className={className} {...rest}>{children}</button>; ); } ``` Given the consistency of the BEM style, we can add other properties, such as size or separated (with margins) and apply all these modifiers at once: ```jsx import React from 'react'; export function Button({ mean='neutral', size='normal', separated=false, children, ...rest }) { const mods = [ // set values if prop is not undefined, mean && mean, size && size, separated && 'separated', ].filter(m => m); // remove undefined // generate BEM classes const modifiersClass = mods.map(mod => `button--${mod}`).join(' '); const className = `button ${modifiersClass}`.trim(); return ( <button className={className} {...rest}>{children}</button>; ); } ``` In the above examples, if we pass a `className` in the rest props, it will override the built one so we need to take that into consideration as well: ```jsx import React from 'react'; export function Button({ mean='neutral', size='normal', separated=false, className='', children, ...rest }) { // ... same as before const buttonClassName = `button ${className} ${modifiersClass}`.trim(); return ( <button className={buttonClassName} {...rest}>{children}</button>; ); } ``` Like other components, we can customize the tag as well: ```jsx {diff} import React from 'react'; export function Button({ mean = 'neutral', size = 'normal', separated = false, + tag: Tag = 'button', className = '', children, ...rest }) { // ... same as before return ( <Tag className={buttonClassName} {...rest}>{children}</Tag>; ); } ``` Finally, we can add a shortcut to include an icon before the button text. For consistency, icons will use the `Icon` component by default. In this case, the only custom property to be derived from button is the size: the icon size should be smaller than the button, given it will be "inside" it. Since buttons and icons shares the same sizes names, we can take the immediate smaller one automatically: ```jsx {diff} import React from 'react'; +import { SIZES } from '../../config'; +import { Icon } from '../icon/Icon'; export function Button({ mean = 'neutral', size = 'normal', separated = false, tag: Tag = 'button', + icon, + iconProps = {}, className = '', children, ...rest }) { // ... same as before // Get icon size that is smaller than button or the smallest // if the button is the smallest as well + const iconSize = icon && SIZES[Math.max(SIZES.indexOf(size) - 1, 0)]; // Get the class name to extened it with a margin helper + const { className: iconClassName = '', ...restIconProps } = iconProps; return ( <Tag className={buttonClassName} {...rest}> + {icon && ( + <Icon + size={iconSize} + name={icon} + {...restIconProps} + className={`${iconClassName} m-r-5`} + /> + )} <span>{children}</span> </Tag>; ); } ``` <file_sep>/packages/documentation/.storybook/theme.js import { create } from "@storybook/theming"; import brandImage from "../public/ui-logo.png"; export default create({ base: "light", brandTitle: "borrow-ui Storybook", brandUrl: "https://www.borrow-ui.dev/", brandImage, }); <file_sep>/packages/ui/src/components/forms/label/Label.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Label } from './Label'; <Meta title="Forms/Label" component={Label} /> # Label `Label` component generates the label of a field. The examples are explained in the `Field` documentation, as all props are exposed by the `Field` component. ## Props <ArgsTable of={Label} /> <file_sep>/packages/ui/src/components/accordion/Accordion.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Lorem } from '../lorem/Lorem'; import { Accordion, AccordionGroup } from './Accordion'; <Meta title="Components/Accordion" component={Accordion} /> # Accordion Accordions allow to show and hide content by clicking on their title bar. An Accordion can be open or closed at start. By default, accordions start closed. It is possible to customize both the title and the content container via `titleProps` and `contentProps`. To have the transition animation a `max-height` value is required. It is set in the CSS, but in case the default value is not enough it can be overridden via `maxHeight` props. <Canvas> <Story name="Default"> <Accordion title="Accordion title"> <div style={{ padding: 20 }}> <Lorem /> </div> </Accordion> </Story> </Canvas> # AccordionGroup If you need to have multiple accordions and only one can be open at a time, you can use `AccordionGroup`. The `initialOpenTitle` prop allows to open an Accordion on the first render: <Canvas> <Story name="Accordion Group"> <div> <h3>First Accordion Group (all closed)</h3> <AccordionGroup> <Accordion title="Accordion 1"> <Lorem /> </Accordion> <Accordion title="Accordion 2"> <Lorem /> </Accordion> <Accordion title="Accordion 3"> <Lorem /> </Accordion> </AccordionGroup> <h3>Second Accordion Group (with one initially open)</h3> <AccordionGroup initialOpenTitle="Accordion 4"> <Accordion title="Accordion 1"> <Lorem /> </Accordion> <Accordion title="Accordion 4"> <Lorem /> </Accordion> </AccordionGroup> </div> </Story> </Canvas> ## Props <ArgsTable of={Accordion} /> ## AccordionGroup Props <ArgsTable of={AccordionGroup} /> --- ## React Tutorial Accordion component is relative simple. The main elements are the title and the content, both wrapped into their containers. The idea is that clicking on the title the content shuold swap visibilty. For example, if the content is not visible, clicking the title should make it visible. To achieve this we can use a state variable and show/hide the content accordingly: ```jsx import React, { useState } from 'react'; export function Accordion({ title, children }) { const [isOpen, setIsOpen] = useState(false); // make content hidden by default return ( <div> <div onClick={() => setIsOpen(!isOpen)}>{title}</div> <div style={{ display: isOpen ? 'block' : 'none' }}>{children}</div> </div> ); } ``` We can then customize the initial state with another prop: `initialStatus`. This can have more explicit values rather than just a boolean, such as `open` or `closed`: ```jsx export function Accordion({ title, initialStatus, children }) { // Initialization based on initialStatus prop const [isOpen, setIsOpen] = useState(initialStatus === 'open'); // ... same as before } ``` <file_sep>/packages/dashboard/src/components/home/Home.js /** * Dashboard home page. * * This page: * - shows the links to the apps by using tiles; * - connects to the store and shows the latest books. */ import { useContext } from 'react'; import { Page, Title, TileLink, Text } from '@borrow-ui/ui'; import { storeContext } from 'store'; import { BookCard } from 'apps/books/components/books/BookCard'; export function Home() { const { store } = useContext(storeContext); const books = store.books && store.books.books ? Object.values(store.books.books) : []; return ( <Page title="Dashboard Home"> <div> <Title tag="h3" className="color-secondary m-t-0"> Welcome {store.user.first_name}! </Title> <Text> This is your dashboard home page. Here you will find your latest books and albums. </Text> </div> <div className="dashboard-home__container"> <div className="flex-start-start flex--wrap"> <TileLink size="big" to="/books" name="My books" description="View and manage all your books" icon="my_library_books" /> <TileLink size="big" to="/movies" name="My Movies" description="View and manage movies library" icon="movie" /> </div> <div className="dashboard-home__latest-items"> <Title tag="h3">Latest books</Title> <div className="m-b-20"> {books.slice(0, 2).map((book) => ( <BookCard key={book.isbn13} book={book} /> ))} </div> </div> </div> </Page> ); } <file_sep>/packages/ui/src/components/forms/field/Field.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Monospace } from '../../text/Monospace'; import { Input } from '../input/Input'; import { Field, VField, HField } from './Field'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; <Meta title="Forms/Field" component={Field} /> # Field Field represents forms' label-controller couple. The `Field` component wraps the controller and optionally creates a label, if the prop is specified. A `required` prop can be used to mark a field as required. <Canvas> <Story name="Default"> <FormsStoryWrapper> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="This field has a label" required={true}> <Input placeholder="Insert your name..." /> </Field> <Field> <Input placeholder="This one doesn't" /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ### Layout Field's label and controller can have a vertical disposition (default) or an horizontal disposition. This can be changed by specifying `layout` prop or by using the shortcut component `VField` or `HField`. <Canvas> <Story name="Layout"> <FormsStoryWrapper> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <div> <Field label="Vertical layout label"> <Input placeholder="Insert your name..." /> </Field> </div> <div> <Field label="Horizontal layout label" layout="horizontal"> <Input placeholder="Insert your name..." /> </Field> </div> <h3>The same with shortcut components</h3> <div> <VField label="Vertical layout label"> <Input placeholder="Insert your name..." /> </VField> </div> <div> <HField label="Horizontal layout label"> <Input placeholder="Insert your name..." /> </HField> </div> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> When using the horizontal layout is convenient to specify a label width, to keep the spacing armoniuous between all the fields. This can be done by using `labelWidth` prop: <Canvas> <Story name="Label Width"> <FormsStoryWrapper> {({ state, setState }) => { const lw = 280; return ( <div style={{ width: 500 }}> <HField labelWidth={lw} label="Horizontal layout label"> <Input placeholder="Insert your name..." /> </HField> <HField labelWidth={lw} label="Short label"> <Input placeholder="Insert your name..." /> </HField> <HField labelWidth={lw} label="Very very long field label for input field"> <Input placeholder="Insert your name..." /> </HField> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ### Label Alignment The label can also be aligned with `labelAlignment` prop shortcut. Possible values are: `left` (default), `center` and `right`. The `description` prop can be used to display a description after the field content. <Canvas> <Story name="Label Alignment"> <FormsStoryWrapper> {({ state, setState }) => { const lw = 280; const aligments = ['left', 'center', 'right']; return ( <div style={{ width: 500 }}> {aligments.map((alignment) => { return ( <div key={alignment} className="m-b-20"> <h4> Alignment: <Monospace>{alignment}</Monospace> </h4> <HField labelWidth={lw} labelAlignment={alignment} label="Horizontal layout label" > <Input placeholder="Insert your name..." /> </HField> <HField labelWidth={lw} labelAlignment={alignment} label="Short label" description="This is a short label used to describe the field content." > <Input placeholder="Insert your name..." /> </HField> <HField labelWidth={lw} labelAlignment={alignment} label="Very very long field label for input field" > <Input placeholder="Insert your name..." /> </HField> </div> ); })} </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ### Vertical Alignment As you can see, the previous "Short label" field is aligned in the middle of the description and field controller. The vertical alignment can be set as well by using `vAlignment` prop: <Canvas> <Story name="Vertical Alignment"> <FormsStoryWrapper> {() => { return ( <> <HField vAlignment="top" labelWidth={100} label="Short label" description="This is a short label used to describe the field content." > <Input placeholder="Insert your name..." /> </HField> <HField vAlignment="middle" labelWidth={100} label="Short label" description="This is a short label used to describe the field content." > <Input placeholder="Insert your name..." /> </HField> <HField vAlignment="bottom" labelWidth={100} label="Short label" description="This is a short label used to describe the field content." > <Input placeholder="Insert your name..." /> </HField> </> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Props <ArgsTable of={Field} /> <file_sep>/packages/website-next/components/home/GetStarted.js import { Title, Row, Col, Text, Monospace, Link } from '@borrow-ui/ui'; import { Terminal } from '../common/Terminal'; export function GetStarted() { return ( <div> <Title>Get Started</Title> <Row> <Col colClassName="col-xs-12 col-sm-12 col-md-6 last-xs first-md"> <div className="flex-center-center"> <Terminal className="m-b-20 w-400 m-r-20 m-l-20" title="Get started" code={getStartedCode} language="bash" /> </div> </Col> <Col colClassName="col-xs-12 col-sm-12 col-md-6"> <Text> Start developing your website/blog now is as simple as running two simple commands. </Text> <Text>Enter the website package and run the development server!</Text> </Col> </Row> <Row style={{ marginTop: 50, marginBottom: 50 }}> <Col colClassName="col-xs-12 col-sm-12 col-md-6"> <Text> Building the website only requires to change the command from <Monospace>dev</Monospace> to <Monospace>build</Monospace>. </Text> <Text> The build can then be hosted by yourself or using one of the many available services. For example, this website is hosted using{' '} <Link href="https://www.netlify.com/">Netlify</Link>. </Text> </Col> <Col colClassName="col-xs-12 col-sm-12 col-md-6"> <div className="flex-center-center"> <Terminal className="m-b-20 w-400 m-r-20 m-l-20" title="Build" code={buildCode} language="bash" /> </div> </Col> </Row> </div> ); } const getStartedCode = `cd packages/website-next; yarn dev`; const buildCode = `cd packages/website-next; yarn build`; <file_sep>/packages/ui/src/components/forms/date-picker/DatePicker.types.ts import { IconProps } from '../../icon/Icon.types'; import { InputProps } from '../input/Input.types'; export interface IDatePickerState { date?: Date; string?: string; } export interface DatePickerProps { /** Handler called when date is changed. Three args are passed: date, modifiers and dayPickerInput. * The date is a string or object, depending on `onDayChangeFormat` prop. * For modifiers and dayPickerInput, see * [`react-day-picker` documentation](https://react-day-picker.js.org/api/DayPickerInput#onDayChange). */ onDayChange?: (date: Date | string | undefined, inputValue: string) => void; /** Format of the date passed to `onDayChange` handler */ onDayChangeFormat?: 'date' | 'string'; /** Date format. For all formats, see * [`date-fns` documentation](https://date-fns.org/v2.28.0/docs/format). */ format?: string; placeholder?: string; initialValue?: string; /** Return partial strings, i.e. `2020-04-` */ returnPartial?: boolean; disabled?: boolean; invalid?: boolean; /** Props passed to input field */ inputProps?: InputProps; /** Props passed to the Icon component */ iconProps?: IconProps; /** Props passed to the overlay wrapper see * [documentation](https://react-day-picker.js.org/api/DayPickerInput#overlayComponent) */ overlayWrapperProps?: React.HTMLAttributes<HTMLDivElement>; /** Props passed to `usePopper` hook, see * [documentation](https://popper.js.org/react-popper/v2/hook/) */ usePopperProps?: any & { placement?: string /** Pop up position */; }; } export interface DatePickerOverlayProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; selectedDay?: Date; overlayProps?: React.HTMLAttributes<HTMLDivElement>; /** Show the input overlay aligned on the right side of input */ rightAlign?: boolean; className?: string; } <file_sep>/packages/ui/src/utils/constants.ts interface IKeyCodes { ENTER: string; ESCAPE: string; ESCAPE_LEGACY: string; SPACEBAR: string; SPACEBAR_LEGACY: string; } export const KEY_CODES: IKeyCodes = { ENTER: 'Enter', ESCAPE: 'Escape', ESCAPE_LEGACY: 'Esc', SPACEBAR: ' ', SPACEBAR_LEGACY: 'Spacebar', }; <file_sep>/packages/dashboard/src/thirdParty.js import '@fontsource/poppins/300.css'; import '@fontsource/poppins/400.css'; import '@fontsource/poppins/700.css'; import 'material-design-icons-iconfont/dist/material-design-icons.css'; import '@fortawesome/fontawesome-free/css/all.css'; import 'react-day-picker/dist/style.css'; <file_sep>/packages/ui/src/components/tooltip/Tooltip.types.ts import { ReferenceOverlayPlacementType, ReferenceOverlayTriggerModeType, } from '../reference-overlay/ReferenceOverlay.types'; export interface TooltipProps { /** Tooltip content */ tooltip: React.ReactNode; /** Trigger */ children: React.ReactNode; /** Tooltip placement */ placement?: ReferenceOverlayPlacementType; /** Which event will make the tooltip visible */ triggerMode?: ReferenceOverlayTriggerModeType; /** Applies a class with min-width (150px) */ minWidth?: boolean; /** Applies a class with max-width (300px) */ maxWidth?: boolean; /** Props passed to the tooltip container */ tooltipProps?: React.HTMLProps<HTMLDivElement> & { className?: string; }; /** Props passed to the tooltip arrow */ tooltipArrowProps?: React.HTMLProps<HTMLDivElement> & { className?: string; }; /** Props forwarded to popper hook. * See [documentation](https://popper.js.org/react-popper/v2/hook/). */ popperProps?: any; className?: string; } <file_sep>/packages/ui/rollup.config.js import cleaner from 'rollup-plugin-cleaner'; import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import typescript from '@rollup/plugin-typescript'; import { terser } from 'rollup-plugin-terser'; import dts from 'rollup-plugin-dts'; import peerDepsExternal from 'rollup-plugin-peer-deps-external'; // To visualize the bundle import { visualizer } from 'rollup-plugin-visualizer'; import packageJson from './package.json'; // Libraries used that should not be bundled. // These are installed with optionalDependencies. const externals = [ '@popperjs/core/lib', 'date-fns', 'lodash.debounce', 'prismjs', 'prop-types', 'react', 'react-day-picker/DayPickerInput', 'react-day-picker', 'react-dom', 'react-dropzone', 'react-media', 'react-popper', 'react-select', 'react-select/creatable', ]; const configuration = { input: 'src/index.ts', output: [ { file: packageJson.main, format: 'cjs', sourcemap: true, }, { file: packageJson.module, format: 'esm', sourcemap: true, }, ], plugins: [ cleaner({ targets: ['./build_stats'], }), peerDepsExternal(), resolve(), commonjs({ exclude: 'src/**', }), typescript({ tsconfig: './tsconfig.json' }), visualizer({ filename: './build_stats/bundle.html' }), terser(), ], // @babel/runtime has a long id, doing as // suggested in docs. external: (id) => id.includes('@babel/runtime') || externals.includes(id), }; const typesConfiguration = { input: 'dist/esm/types/index.d.ts', output: [{ file: 'dist/index.d.ts', format: 'esm' }], external: [/\.css$/, /\.scss$/], plugins: [dts()], }; export default [configuration, typesConfiguration]; <file_sep>/packages/ui/src/components/text/Monospace.types.ts export interface MonospaceProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; className?: string; } <file_sep>/packages/website-next/layout/Header.js import React, { useState, useEffect } from 'react'; import Image from 'next/image'; import NextLink from 'next/link'; import { Icon, Navbar, NavbarLink, SidebarTrigger } from '@borrow-ui/ui'; import logoColor from '../public/logo-color-192.png'; import packageJson from '../package.json'; import { ThemeTrigger } from './theme'; export function Header({ isSmallScreen }) { // Required for Hydration, initial render should be the same as // server. "Logic" should be placed in effects. const [showLinks, setShowLinks] = useState(false); useEffect(() => { setShowLinks(!isSmallScreen); }, [isSmallScreen]); const logo = ( <Image src={logoColor || '/logo-color-192.png'} alt="borrow-ui logo" width={25} height={25} /> ); return ( <Navbar sticky={false} fixed={true} className="main-header" left={[ { headerLabel: ( <NextLink href="/"> <a className="borrow-ui__navbar__group borrow-ui__navbar__link"> <div className="flex-center-center"> {logo} <span className="header__title">Home</span> </div> </a> </NextLink> ), }, showLinks && { headerLabel: ( <NextLink href="/blog" prefetch={false}> <a className="borrow-ui__navbar__group borrow-ui__navbar__link"> <span>Blog</span> </a> </NextLink> ), }, showLinks && { headerLabel: ( <NextLink href="/project" prefetch={false}> <a className="borrow-ui__navbar__group borrow-ui__navbar__link"> <span>Project</span> </a> </NextLink> ), }, ].filter((v) => !!v)} right={[ <ThemeTrigger key="theme-trigger" />, <NavbarLink tag="a" href="https://github.com/borrow-ui/borrow-ui/tree/master/packages/website-next" target="_blank" rel="noopener noreferrer" key="github" > <Icon family="fab" name="fa-github" size="small" /> </NavbarLink>, showLinks && ( <span className="header__version" key="version"> v{packageJson.version} </span> ), <div key="trigger" className="header__sidebar-trigger"> <SidebarTrigger /> </div>, ].filter((v) => !!v)} /> ); } <file_sep>/packages/website-next/layout/theme.js import { useLayoutEffect, useEffect, useState, useCallback, useRef } from 'react'; import { Icon } from '@borrow-ui/ui'; const useClientLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect; export function ThemeTrigger() { const { theme, toggleTheme } = useThemes(); const isDark = theme === 'dark'; const iconClass = `m-r-10 ${isDark ? 'color-neutral-white' : 'color-dark'}`; 7; return ( <div> <Icon className={iconClass} name={isDark ? 'nightlight' : 'sunny'} onClick={() => toggleTheme('dark')} /> </div> ); } function useThemes({ defaultTheme = null, localStorageKey = '__website_theme' } = {}) { const mountedRef = useRef(false); const [theme, setTheme] = useState(defaultTheme); const toggleTheme = useCallback( (themeName) => { setTheme((currentValue) => { const removeTheme = themeName === currentValue; if (removeTheme) { document.querySelector('body').removeAttribute('data-theme'); localStorage.removeItem(localStorageKey); } else { document.querySelector('body').setAttribute('data-theme', themeName); localStorage.setItem(localStorageKey, themeName); } return removeTheme ? null : themeName; }); }, [setTheme, localStorageKey] ); useClientLayoutEffect(() => { if (mountedRef.current) return; const savedTheme = localStorage && localStorage.getItem(localStorageKey); toggleTheme(savedTheme); mountedRef.current = true; }, [localStorageKey, toggleTheme]); return { theme, setTheme, toggleTheme }; } <file_sep>/packages/ui/src/components/badge/Badge.types.ts export interface BadgeProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** Adds a color with `color-on-<COLOR>` class */ color?: string; /** Adds a background color with `color-<COLOR>-bg` class */ backgroundColor?: string; /** Change the badge type */ type?: 'rounded' | 'circular' | 'squared'; /** Specify which tag has to be used for the badge */ tag?: keyof JSX.IntrinsicElements | React.ComponentType; onClick?: React.MouseEventHandler; children: React.ReactNode; className?: string; } <file_sep>/packages/ui/src/components/modal/Modal.types.ts import { IconProps } from '../icon/Icon.types'; type SetVisibleType = React.Dispatch<React.SetStateAction<boolean>>; type GetModalWindowPropsInput = { setVisible: SetVisibleType }; export interface ModalProps { /** Trigger component, will receive a `setVisible` function, * which arg is a boolean to set the modal status */ Trigger: React.ElementType<any>; /** Function called to get the Modal props, it should return an object. * See `ModalWindow` props to see the valid keys for the return object. */ getModalWindowProps: (arg0: GetModalWindowPropsInput) => {}; } export type ModalStateType = { isMaximized: boolean; modalContainerStyle: { width?: string | number | undefined; height?: string | number | undefined; }; isLoading: boolean; }; type OnOpenInput = { resolve: (value: unknown) => void; reject: (reason?: any) => void }; export interface ModalWindowProps { /** Modal Title */ title?: React.ReactNode; /* Modal Content, rendered as modal body */ content?: React.ReactNode; /** Modal Footer, rendered after the body */ footer?: React.ReactNode; /** */ closeModal?: () => {}; /** setVisible callback, coming from Modal's Trigger */ setVisible: SetVisibleType; /** Render a close Icon on the top right to close the modal */ showCloseIcon?: boolean; /** Set the modal maximized on open */ maximized?: boolean; /** If the modal can maximize to full screen, show icons to trigger the status */ canMaximize?: boolean; /** Close the modal if Escape key is pressed */ closeOnEscape?: boolean; /** Stop click event to be propagated outside the modal window */ stopClickPropagation?: boolean; /** Initial modal height */ startHeight?: string | number; /** Initial modal width */ startWidth?: string | number; /** Hooks called on modal events. Valid events are: `onOpen` */ hooks?: { onOpen?: (arg0: OnOpenInput) => Promise<void> | void; }; /** Props to be passed to modal's top element */ wrapperProps?: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's container, inside wrapper element */ containerProps?: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's content, inside wrapper element */ contentProps?: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's footer, inside wrapper element */ footerProps?: React.HTMLProps<HTMLDivElement>; } export interface ModalWindowPortalInput { /** Modal Title */ title?: React.ReactNode; /* Modal Content, rendered as modal body */ content?: React.ReactNode; /** Modal Footer, rendered after the body */ footer?: React.ReactNode; classes: { modalContainerStatusClass: string; modalContentSizeClass: string; }; styles: { modalContentStyle: Object; }; /** Render a close Icon on the top right to close the modal */ showCloseIcon?: boolean; /** If the modal can maximize to full screen, show icons to trigger the status */ canMaximize?: boolean; setIsMaximized: (isMax: boolean) => void; closeModalWindow?: () => void; /** Stop click event to be propagated outside the modal window */ stopClickPropagation?: boolean; modalState: ModalStateType; modalContainer: Element; /** Props to be passed to modal's top element */ wrapperProps: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's container, inside wrapper element */ containerProps: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's content, inside wrapper element */ contentProps: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's footer, inside wrapper element */ footerProps: React.HTMLProps<HTMLDivElement>; } export interface IconControlMaximizedProps extends IconProps { setIsMaximized: (isMax: boolean) => void; } export interface IconControlCloseWindowModalProps extends IconProps { closeModalWindow?: (props?: {}) => void; } <file_sep>/packages/dashboard/README.md # Dashboard <div style="width: 90%; margin-left: auto; margin-right: auto; margin-bottom: 20px"> <img src="./public/dashboard-home.png" /> </div> <div align="center"> <table> <tr> <td> <a href="https://dashboard.borrow-ui.dev/">Dashboard demo</a> </td> <td> <img src="https://api.netlify.com/api/v1/badges/5b80574a-c68a-4616-b599-9610ae3c7fa9/deploy-status" alt="Netlify Status" /> </td> </tr> </table> </div> This project contains a Dashboard based on `borrow-ui` and [Create React App](https://github.com/facebook/create-react-app). The Dashboard has: - a landing page; - a folder with common components; - two applications, to show how to organise the code for multiple apps; - no memory (database): everything is restored after refresh; - an example of a form with controlled components and one with uncontrolled components, with different ways of importing and using the form controllers. The Dashboard does not follow common React best practices for: - tests: components are not tested, and not extensively documented; - API: everything is in memory, using a global context; - URL/parameters/input sanitization and check; - catch on promises; - custom pages (i.e. 404). Despite this, it can be used as a starter project to create a multi application dashboard, already setup to use the components library. ## Commands To start the dashboard in development mode, run ```bash yarn start ``` This will open the Dashboard on the default CRA address, [http://localhost:3000](http://localhost:3000). To build the project, run ```bash yarn build ``` <file_sep>/packages/website-next/pages/blog/index.js import path from 'path'; import React from 'react'; import Head from 'next/head'; import NextLink from 'next/link'; import { MDXRemote } from 'next-mdx-remote'; import { MDXProvider } from '@mdx-js/react'; import { parse, format } from 'date-fns'; import * as uiLibrary from '@borrow-ui/ui'; import { providerComponents } from '../../core/mdx/providerComponents'; import { getSingleContent, getAllSources } from '../../core/mdx/mdx'; import style from './blog.module.scss'; export const SOURCE_PATH = path.join(process.cwd(), 'content/blog'); const { Title, Card, Link, Icon } = uiLibrary; const mdxComponents = { ...uiLibrary, }; export default function Content({ code, metadata = {}, posts }) { const title = `Blog`; const publishedPosts = posts .filter((post) => post.metadata.isPublished) .sort((a, b) => (a.metadata.postDate > b.metadata.postDate ? -1 : 1)); return ( <> <Head> <title>{title}</title> <meta property="og:title" content={title} key="title" /> </Head> <MDXProvider components={providerComponents}> <> <div className="website__text" style={{ paddingBottom: 30 }}> <Title className="color-primary">{metadata.title}</Title> <MDXRemote {...code} components={mdxComponents} /> </div> </> </MDXProvider> <div className="website__text" style={{ marginBottom: 30 }}> <Title>Posts</Title> <div className="flex flex--wrap"> {publishedPosts.map((post) => { const postDate = parse(post.metadata.postDate, 'yyyy-MM-dd', new Date()); const displayDate = format(postDate, 'eee, d MMMM yyyy'); return ( <Card key={post.metadata.title} className={`w-400 m-r-20 m-b-20 m-t-20 ${style['blog-card']}`} icon={ <Icon name={post.metadata.iconName || 'article'} size="huge" className="color-teal-l2" /> } mainProps={{ className: style['blog-card__main'] }} sideProps={{ className: style['blog-card__side'] }} title={ <NextLink href={`/blog/${post.slug}`}> <Link tag="a">{post.metadata.title}</Link> </NextLink> } description={post.metadata.description} descriptionProps={{ className: style['blog-card__description'] }} controls={ <> <span className="color-neutral-light">{displayDate}</span> <NextLink href={`/blog/${post.slug}`}> <Link tag="a">Read post</Link> </NextLink> </> } /> ); })} </div> </div> <div className={style['blog__order-container']}> The blog posts are sorted by date, so you shuold start reading from the second! </div> <div className="website__text" style={{ marginTop: 50, marginBottom: 50 }}> However, as you might already know, Next.js does not offer a {'"memory"'}{' '} functionality so your {'"most read"'} posts counter shuold be handled separately. </div> </> ); } export async function getStaticProps({ params = {} }) { const content = await getSingleContent(SOURCE_PATH, 'index'); const posts = await getAllSources([SOURCE_PATH]); return { props: { ...content, posts }, }; } <file_sep>/packages/website-next/content/blog/blog-instructions.mdx --- title: Blog Instructions isPublished: true postDate: '2021-08-01' author: borrow-ui description: How does this section work? iconName: auto_stories --- The first post of this blog! Each blog post file can have few attributes: - `isPublished`: a boolean that determines if the post will show up in the list; - `postDate`: the date of the post; - `author`: the author of the post; - `description`: a brief description shown in the home page. You can extend the basic tags just by adding them in the `.mdx` files and then handling them in the `[slug].js`. All the logic can be placed there, for example to show author and date only if the name of the file is different from `index`. Each slug then must correspond to the `.mdx` file (usually) placed in `content/section` folder. All the blog entries, for example, are placed inside `content/blog` folder and each file name will be used as URL slug. The slug file has three important exports: - the `getStaticProps` function, which will generate the props for the content component, by reading the correspondent `.mdx` file; - the `getStaticPaths` function, which generates a list of possible slugs from the content folder; - the main component, exported as `default`, which consumes the generated props. The two functions are "generated" by passing a content folder. The `core/mdx` folder contains two files used to facilitate the generation of multiple slug pages and a list of components used to override the basic HTML ones (for example, to use the library `Title` component instead of `h*`). And of course, you can use the library components and styles as well! <div className="p-20 m-20 flex-center-center"> <Loader /> </div> <Text size="small">Just a random loader, don't wait for it to stop!</Text> <file_sep>/packages/ui/src/hooks/useLocationHash.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Hooks/useLocationHash" /> # useLocationHash `useLocationHash` hook is used to get the hash of the location from the window object. For example, if the location is `https://my.blog.com/page1#first-anchor?test=1&test2=2` it will return `first-anchor`. Note: it relies on query string to be after the hash. ### Usage ```jsx import { useLocationHash } from '@borrow-ui/ui'; export function Page() { // hooks and state // .... const locationHash = useLocationHash(); // other code return ( <div> <a name="first-anchor" href="#first-anchor" className={locationHash === 'first-anchor' ? 'active' : ''} > Title </a> <Lorem /> </div> ); } ``` <file_sep>/packages/ui/src/components/breadcrumbs/Breadcrumbs.types.ts import { TagType } from '../../utils/sharedTypes'; export interface BreadcrumbProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; link?: string; isLast?: boolean; onClick?: React.MouseEventHandler; /** Use a different tag from `div`. */ tag?: TagType; } export interface BreadcrumbsProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; /** A list of objects. Each object must have a `label` and optionally * a link. `className` will be added to the generated one. */ breadcrumbs?: Array<BreadcrumbProps>; } <file_sep>/packages/ui/src/components/reference-overlay/ReferenceOverlay.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from '../button/Button'; import { Icon } from '../icon/Icon'; import { IconControl } from '../icon/IconControl'; import { Lorem } from '../lorem/Lorem'; import { ReferenceOverlay } from './ReferenceOverlay'; <Meta title="Components/ReferenceOverlay" component={ReferenceOverlay} /> # ReferenceOverlay ReferenceOverlay is used to show an overlay when the trigger is clicked or hovered. The `ReferenceOverlay` component accepts two main props: - `overlayContent`: the content of the overlay; - `children`: an element that, when hovered or clicked, will show the overlay; The component is based on the great external library [Popper](https://popper.js.org/) and it's hook. <Canvas> <Story name="Default"> <Fragment> <ReferenceOverlay overlayContent="This is a simple text" className="m-r-20"> <Button mean="positive">Hover me</Button> </ReferenceOverlay> <ReferenceOverlay overlayContent="If you need help, read the docs!" className="m-r-20"> <Icon name="help" className="color-primary" /> </ReferenceOverlay> <ReferenceOverlay overlayContent={ <div style={{ border: '1px solid #444', padding: 5, marginRight: 5, backgroundColor: 'white', }} > This should be shown on the right </div> } className="m-r-20" placement="right" > <Button mean="primary-reverse">Right placed</Button> </ReferenceOverlay> <ReferenceOverlay overlayContent="You must click the trigger or this message to close me!" className="m-r-20" placement="bottom" triggerMode="click" > <Button mean="primary-reverse">Click</Button> </ReferenceOverlay> </Fragment> </Story> </Canvas> ## Positioning Popper automatically set coordinates to the overlay element accordingly to the visibility. The following demo allows to see this in action: <Canvas> <Story name="Positioning"> <div style={{ overflow: 'hidden', position: 'relative' }}> <div style={{ width: '100%', height: 400, overflow: 'auto', padding: 10 }}> <div style={{ width: '200%' }}> <div style={{ display: 'block', height: 160 }}></div> <div style={{ display: 'flex' }}> <div style={{ display: 'block', width: '45%' }}></div> <ReferenceOverlay overlayProps={{ style: { maxWidth: 300 } }} overlayContent={<Lorem paragraphs={1} />} triggerMode="click" > <Button mean="primary">Click me</Button> </ReferenceOverlay> <div style={{ display: 'block', width: '45%' }}></div> </div> <div style={{ display: 'block', height: 400 }}></div> </div> </div> </div> </Story> </Canvas> ## Arrow To see how the arrow is used and styled, please have a look at the `Tooltip` component. ## ReferenceOverlay Props <ArgsTable of={ReferenceOverlay} /> <file_sep>/packages/ui/src/components/breadcrumbs/Breadcrumbs.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Breadcrumbs } from './Breadcrumbs'; <Meta title="Components/Breadcrumbs" component={Breadcrumbs} /> # Breadcrumbs `Breadcrumbs` component is used to display the page path, usually from home. It expects a list of objects with a mandatory `label` key, and an optional `link`. If the link is not present the breadcrumb will be added just as a label (usually the last element does not have a link). <Canvas> <Story name="Default"> <Breadcrumbs breadcrumbs={[ { label: 'Home', link: '/url/to/home' }, { label: 'List of Tests', link: '/url/to/list-of-tests' }, { label: 'Selected test' }, ]} > <h2>Selected test 123</h2> </Breadcrumbs> </Story> </Canvas> ## Props <ArgsTable of={Breadcrumbs} /> --- ## React Tutorial Breadcrumbs component is built from a list of elements, each of them rendered by a Breadcrumb component. In order to get the list working we need to create the single element component as well: ```javascript import React from 'react'; import Link from 'react-router-dom'; export function Breadcrumbs({ breadcrumbs, children }) { return ( <div className="breadcrumbs"> {breadcrumbs.map((breadcrumb, index) => { return <Breadcrumb link={breadcrumb.link}>{breadcrumb.label}</Breadcrumb>; })} {children} </div> ); } function Breadcrumb({ link, children }) { return ( <Link className="breadcrumb" to={link}> {children} </Link> ); } ``` In the example above few choices are made, to simplify the initial code: - `breadcrumbs` prop is a list of objects, each of them having two attributes: `link` and `label`; - the link will use react-router-dom component `Link`. The second point needs some improvements for those situations where we need a normal label or use a different component (i.e. Gatsby's Link or just an 'a'). Instead of using react-router-dom component we will use a "default" one, that we can configure when we initialize the UI in the app. To see how this is done, [look at the Link component tutorial]() (#TODO). ```jsx {diff} import React from 'react'; - import Link from 'react-router-dom'; + import { config } from '../../config'; export function Breadcrumbs({ breadcrumbs, children }) { return ( <div className='breadcrumbs'> {breadcrumbs.map((breadcrumb, index) => { - return <Breadcrumb link={breadcrumb.link}> + return <Breadcrumb link={breadcrumb.link} tag={breadcrumb.tag}> {breadcrumb.label} </Breadcrumb>; })} {children} </div> ); } function Breadcrumb({ link, tag, children }) { + const Tag = tag ? tag : link ? config.getLinkComponent() : 'div'; return <Tag className='breadcrumb' to={link}> {children} </Tag>; } ``` <file_sep>/packages/ui/src/config.test.ts import { config, setConfig, getConfig } from './config'; describe('config', () => { test('default values', () => { // Initial getLocation should be undefined expect(config.getLocation()).toBeUndefined(); expect(config.getLinkComponent()).toBe('a'); }); test('setConfig', () => { // Initial getLocation should be undefined expect(config.getLocation()).toBeUndefined(); const original = config.getLocation; // set new getLocation const configSet = setConfig('getLocation', () => ({ path: '/' })); expect(configSet).toBe(true); expect(config.getLocation().path).toBe('/'); // set a config that is not listed should return false const err = console.error; console.error = jest.fn(); // @ts-ignore const wrongConfigSet = setConfig('setWhatever', 1); expect(wrongConfigSet).toBe(false); console.error = err; // set back setConfig('getLocation', original); }); test('getConfig', () => { // getConfig should return the config setting expect(getConfig('getLinkComponent')).toBe(config.getLinkComponent); }); }); <file_sep>/packages/ui/src/components/forms/checkbox/Checkbox.types.ts import { LabelProps } from '../label/Label.types'; export interface CheckboxProps extends React.ComponentPropsWithRef<React.ElementType> { className?: string; /** Handler executed when the checkbox container is clicked. Normally, it toggles the value */ onClick?: (newCheckedStatus: boolean) => void; /** Alternative to onClick, to have the same prop of ther form fields */ onChange?: (newCheckedStatus: boolean) => void; checked?: boolean; disabled?: boolean; /** Checkbox own label */ label?: React.ReactNode; labelProps?: LabelProps; } <file_sep>/packages/dashboard/src/components/layout/MainSidebar.js /** * Dashboard sidebar, created with SidebarBody and SidebarEntry * components. * * Instead of using a Sidebar component which has the trigger within it, * it uses the context defined in App.js and delegates the trigger to * the Header component. * * Ideally, the links here shuold be different from the Header, but the * purpose of this demo is to show components and their usage. */ import { Icon, SidebarBody, SidebarEntry } from '@borrow-ui/ui'; export function MainSidebar() { return ( <SidebarBody hideTrigger={true} className="main-sidebar" stickyTop={46} height={'calc(100vh - 46px)'} > {/* sidebar has space-between, so we need to group items */} <div> <SidebarEntry iconName="home" to="/"> Home </SidebarEntry> <SidebarEntry iconName="my_library_books" to="/books"> Books </SidebarEntry> <SidebarEntry iconName="movie" to="/movies"> Movies </SidebarEntry> </div> <div className="flex-center-center p-b-10 p-t-10"> <Icon name="help_outline" /> </div> </SidebarBody> ); } <file_sep>/packages/documentation/stories/0-Welcome.stories.mdx import { Meta, Story, Canvas } from "@storybook/addon-docs"; import LinkTo from "@storybook/addon-links/react"; <Meta title="Getting Started/Welcome" /> # Welcome Welcome to `borrow-ui` Storybook documentation! This website contains component examples and documentation, as well as some interactive demos. The following sections are available: - `Components`: view all UI components and see how to use them; - `Forms`: special components used in forms (such as inputs, checkboxes, etc.) - `Hooks`: few hooks used by components but also available for other pages. <file_sep>/packages/ui/src/components/grid/Grid.types.ts export interface RowProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; } export interface ColProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; /** Set the size for the sm column. This is a shortcut to configure `col-xs-12 col-sm-*`. */ size?: number; /** Overrides the default `col-xs-12 col-sm-<size>` value. */ colClassName?: string; } <file_sep>/packages/ui/src/components/sidebar/SidebarIcon.types.ts export interface SidebarIconProps extends React.ComponentPropsWithoutRef<React.ElementType> { name: string; className?: string; isActive?: boolean; isOpen?: boolean; } <file_sep>/packages/dashboard/src/apps/books/components/reviews/DeleteReviewIconControl.js /** * Similarly to DeleteBookButton, use an IconControl to open a modal * for confirmation. * * While the promise is loading, the modal will not be closable. */ import { useState } from 'react'; import PropTypes from 'prop-types'; import { Button, Modal, Loader, IconControl } from '@borrow-ui/ui'; export function DeleteReviewIconControl({ reviewId, deleteReview }) { const [loading, setLoading] = useState(false); const deleteReviewFn = (id) => { setLoading(true); return deleteReview(id).catch(() => { setLoading(false); }); }; return ( <Modal Trigger={({ setVisible }) => ( <IconControl name="delete" onClick={() => setVisible(true)} /> )} getModalWindowProps={({ setVisible }) => ({ title: 'Delete review', content: `Are you sure to delete this review?`, footer: ( <> <span /> <div> <Button mean="negative" className="m-r-5" onClick={async () => { await deleteReviewFn(reviewId).catch(() => { setVisible(false); }); }} disabled={loading} flat={true} > {loading ? <Loader type="inline" /> : 'Delete'} </Button> <Button onClick={() => setVisible(false)} disabled={loading}> Cancel </Button> </div> </> ), showCloseIcon: !loading, closeOnEscape: !loading, canMaximize: false, startHeight: 200, startWidth: 400, })} /> ); } DeleteReviewIconControl.propTypes = { /** Review ID to be deleted */ reviewId: PropTypes.number.isRequired, /** Function to call when Delete confirmation button is pressed */ deleteReview: PropTypes.func.isRequired, }; <file_sep>/packages/website-next/layout/thirdParty.js import 'material-design-icons-iconfont/dist/material-design-icons.css'; import '@fortawesome/fontawesome-free/css/all.css'; import 'react-day-picker/dist/style.css'; import 'prismjs'; import 'prismjs/themes/prism.css'; import 'prismjs/components/prism-bash.min'; import 'prismjs/components/prism-json.min'; import 'prismjs/components/prism-jsx.min'; import 'prismjs/components/prism-markdown.min'; import 'prismjs/components/prism-scss.min'; import 'prismjs/plugins/line-highlight/prism-line-highlight.min'; import 'prismjs/plugins/line-highlight/prism-line-highlight.css'; import 'prismjs/plugins/line-numbers/prism-line-numbers.min'; import 'prismjs/plugins/line-numbers/prism-line-numbers.css'; import 'prismjs/plugins/toolbar/prism-toolbar.min'; import 'prismjs/plugins/toolbar/prism-toolbar.css'; import 'prismjs/plugins/show-language/prism-show-language'; <file_sep>/packages/ui/src/components/text/Title.types.ts import { TagType } from '../../utils/sharedTypes'; export interface TitleProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; className?: string; /** Use a different tag than div. */ tag?: TagType; underline?: boolean; /** If set, wraps the children with an 'a' tag and assign this value as ID. */ anchor?: string; anchorClassName?: string; } <file_sep>/packages/ui/src/hooks/useHover.types.ts type RefType = React.RefObject<any> | null; export type UseHoverType = [RefType, boolean]; <file_sep>/packages/ui/src/components/forms/dropzone/Dropzone.types.ts import { TagType } from '../../../utils/sharedTypes'; export type FileType = { name: string }; type OnRemoveType = (fileIndex: number) => void; export interface IDropzoneState { files: Array<FileType>; lastChangeReason: null | string; } export interface DropzoneProps { className?: string; /** Message displayed in the Drop area */ dragMessage?: React.ReactNode; /** Message displayed in the Drop area when a file is dragged into it (before dropping) */ dragActiveMessage?: React.ReactNode; /** Message displayed int he Drop area when dragging in not active */ dragInactiveMessage?: React.ReactNode; /** Initial list of files, where each object requires the following keys: * * - `name`: the name of the file */ initialFiles?: Array<FileType>; /** Maximum number of files */ maxFiles?: number; disabled?: boolean; /** Message shown when the field is disabled */ disabledMessage?: React.ReactNode; /** Function called when a file is dropped in the drop area */ onDrop?: ( acceptedFiles: Array<FileType>, newState?: IDropzoneState, setState?: React.Dispatch<React.SetStateAction<IDropzoneState>> ) => void; /** Callback called when a file is removed */ onFileRemove?: ( acceptedFiles: FileType, newState?: IDropzoneState, setState?: React.Dispatch<React.SetStateAction<IDropzoneState>> ) => void; /** Callback called when the list of file is changed (either for files added or removed) */ onFilesChanges?: ( newState: IDropzoneState, setState?: React.Dispatch<React.SetStateAction<IDropzoneState>> ) => void; /** Props passed to the dropzone drop area, which contains also the input element */ dropAreaProps?: React.HTMLAttributes<HTMLDivElement>; /** Props passed to the hidden input */ inputProps?: React.HTMLAttributes<HTMLInputElement>; /** Component used to replace the default File representation in the list of files (see `DropzoneFile` props) */ FileComponent?: TagType; } export interface DropzoneFilesProps extends React.ComponentPropsWithoutRef<React.ElementType> { dropzoneState: { files: Array<FileType>; }; onRemove?: OnRemoveType; FileComponent?: TagType; disabled?: boolean; className?: string; } export interface DropzoneFileProps { file: FileType; fileIndex: number; onRemove?: OnRemoveType; disabled?: boolean; } <file_sep>/packages/website-next/content/blog/unpublished.mdx --- title: Unpublished post isPublished: false postDate: '2025-01-01' author: borrow-ui description: Welcome 2025! --- Few years in the future, this post will be listed in the home page! I just need to remember to push the date ahead at some point. <file_sep>/packages/website-next/components/home/Home.js import NextLink from 'next/link'; import { Page, Block, Link, Title, Text, Monospace } from '@borrow-ui/ui'; import { Features } from './Features'; import { PageExample } from './PageExample'; import { GetStarted } from './GetStarted'; import styles from './home.module.scss'; export function Home() { return ( <Page continuousScroll={true} pageBodyProps={{ className: styles['home__page'] }}> <Block padded={false}> <main className="website__text__columns"> <Title className={styles['home__main-title']}> Welcome to{' '} <Link href="https://borrow-ui.dev" className={styles['home__main-link']}> borrow-ui </Link>{' '} demo! </Title> <Text size="big">You can read the subtitle here, made with Text component</Text> <Text style={{ marginTop: 20 }}> This is a demo site made with <Monospace>@borrow-ui/ui</Monospace> </Text> </main> <div className="website__text__columns"> <Features /> </div> </Block> <div className={styles['home__page-example__container']}> <div className="website__text__columns"> <PageExample /> </div> </div> <div className="website__text__columns"> <GetStarted /> </div> <div className={styles['home__guide__container']}> <div className="website__text__columns"> Read the quick guide in the{' '} <NextLink href="/blog"> <Link>Blog section</Link> </NextLink> </div> </div> </Page> ); } <file_sep>/packages/dashboard/src/apps/books/components/reviews/ReviewForm.js /** * Creates an "uncontrolled" form using form components. * The components are imported directly from the library, * as opposed as BookForm. * Both ways are fine. * * The uncontrolled form is managed with react-hook-form. * Some components can be registered directly (text input and textarea) * while others needs to be wrapped with rhf's Controller. * * This forms shows also how to use watch to create a custom components * specific for this form (for the 'stars'). * * The result is a much more verbose form but with better performances * and less re-rendering. * * As other parts of this demo, there is no need for validation or catches, * they are out of scope. */ import { useState } from 'react'; import PropTypes from 'prop-types'; import { useForm, Controller } from 'react-hook-form'; import { Button, Loader, Icon, Field, Textarea, Input, Toggle, Select, DatePicker, Dropzone, Checkbox, } from '@borrow-ui/ui'; import { beautify } from 'utils/strings'; import { TOPICS } from 'apps/books/constants'; const topicsOptions = TOPICS.map((cat) => ({ value: cat, label: beautify(cat) })); export function ReviewForm({ review, onSubmit, onCancel }) { const [loading, setLoading] = useState(false); const { control, register, handleSubmit, setValue, watch } = useForm({ defaultValues: review, }); const watchStars = watch('stars'); const onFormSubmit = (formReview) => { setLoading(true); const changedReview = { ...review, ...formReview }; onSubmit(changedReview).catch(() => { setLoading(false); }); }; return ( <form onSubmit={handleSubmit(onFormSubmit)}> <div className="dashboard__readable-content"> <Field label="Title" htmlFor="isbn13"> <Input defaultValue={review.title || ''} {...register('title')} /> </Field> <Field label="Rating" htmlFor="stars" layout="horizontal" labelWidth={100}> <Star value={1} watchStars={watchStars} setValue={setValue} /> <Star value={2} watchStars={watchStars} setValue={setValue} /> <Star value={3} watchStars={watchStars} setValue={setValue} /> <Star value={4} watchStars={watchStars} setValue={setValue} /> <Star value={5} watchStars={watchStars} setValue={setValue} /> {watchStars > 0 && ( <Icon name="block" className="color-neutral-light m-r-10 cursor-pointer" size="smaller" onClick={() => setValue('stars', 0)} /> )} </Field> <Controller name="completed" control={control} defaultValue={review.completed} render={({ field }) => ( <Field label="Completed" htmlFor="completed" layout="horizontal" labelWidth={100} > <Toggle {...field} id="completed" checked={field.value} onChange={field.onChange} /> </Field> )} /> <Controller name="started_on" control={control} defaultValue={review.started_on} render={({ field }) => { return ( <Field label="Started On" htmlFor="started_on" layout="horizontal" labelWidth={100} > <DatePicker {...field} initialValue={review.started_on} onDayChange={field.onChange} /> </Field> ); }} /> <Controller name="topics" control={control} defaultValue={review.topics} render={({ field }) => { return ( <Field label="Topics" htmlFor="topics" layout="horizontal" labelWidth={100} > <Select options={topicsOptions} {...field} value={field.value || []} onChange={(vv) => field.onChange(vv ? vv.map((v) => v.value) : []) } isMulti={true} /> </Field> ); }} /> <Field label="Description" htmlFor="description"> <Textarea defaultValue={review.description || ''} {...register('description')} /> </Field> <Controller name="recommend_to_friends" control={control} defaultValue={review.recommend_to_friends} render={({ field }) => ( <Field label="Recommend to friends" htmlFor="recommend_to_friends" layout="horizontal" labelWidth={160} > <Checkbox {...field} checked={field.value} id="recommend_to_friends" onChange={field.onChange} /> </Field> )} /> <Controller name="attachments" control={control} render={({ field }) => ( <Field label="Attachments" htmlFor="attachments" description="For the purpose of this demo, this will be ignored" > <Dropzone multiple={true} onChange={(e) => field.onChange(e.target.files)} /> </Field> )} /> <div className="flex-end-center"> <Button mean="neutral" onClick={onCancel} className="m-r-5" disabled={loading}> Cancel </Button> <Button mean="primary" type="submit" disabled={loading}> {loading ? <Loader type="inline" /> : 'Save'} </Button> </div> </div> </form> ); } ReviewForm.propTypes = { book: PropTypes.object, onSubmit: PropTypes.func.isRequired, onCancel: PropTypes.func.isRequired, }; function Star({ value, watchStars, setValue }) { return ( <Icon name={watchStars >= value ? 'star' : 'star_outline'} className={`${ watchStars >= value ? 'color-secondary' : 'color-neutral-light' } m-r-5 cursor-pointer`} size="smaller" onClick={() => setValue('stars', value)} /> ); } Star.propTypes = { value: PropTypes.number.isRequired, watchStars: PropTypes.number, setValue: PropTypes.func.isRequired, }; <file_sep>/packages/ui/src/components/loader/Loader.types.ts export type LoaderType = 'triangle' | 'line' | 'inline'; export interface LoaderProps extends React.ComponentPropsWithoutRef<React.ElementType> { className?: string; type?: LoaderType; } <file_sep>/packages/dashboard/src/apps/movies/constants.js export const MOVIES_BASE_URL = '/movies'; <file_sep>/packages/ui/src/components/sidebar/Sidebar.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Lorem } from '../lorem/Lorem'; import { SidebarMenu } from '../sidebar-menu/SidebarMenu'; import { Sidebar, SidebarBody } from './Sidebar'; import { SidebarEntry } from './SidebarEntry'; import { SidebarTrigger } from './SidebarTrigger'; <Meta title="Components/Sidebar" component={Sidebar} /> # Sidebar `Sidebar` component can be used to create sidebars or a side menu container. A sidebar usually has two statuses, opened or closed. The status can be triggered by clicking an "expand" element (i.e. an icon with three lines). By default the sidebar is closed. The elements inside the sidebar are `SidebarEntry` component instances. The `children` prop is used to add the entries. The `Sidebar` component has a flex column display, so in order to group all the items on top they should be wrapped in a container. **Note**: to use sidebar, it must be wrapped with a flex container. ### Sidebar The Sidebar component allows to create a sidebar to be placed in the page. Sidebar has it's own context to determine if it is open/closed, if any entry is expanded/collapsed and if the links should close the sidebar when clicked. <Canvas> <Story name="Default"> <div style={{ display: 'flex', width: '100%', height: 400 }}> <Sidebar> <div> <SidebarEntry iconName="dashboard">Dashboard</SidebarEntry> <SidebarEntry shortcut="SC">Shortcut</SidebarEntry> <SidebarEntry isActive={true} shortcut="AE"> Active Entry </SidebarEntry> <SidebarEntry id="entry-with-content-arrow" iconName="arrow_forward" content={ <ul> <li>Row 1</li> <li>Row 2</li> </ul> } > Click arrow to view content </SidebarEntry> <SidebarEntry id="entry-with-content" iconName="assignment" content={ <ul> <li>Row 1</li> <li>Row 2</li> </ul> } entryClickToggleContent={true} > Click me view content </SidebarEntry> <SidebarEntry> <span>No Icon or shortcut</span> </SidebarEntry> <SidebarEntry shortcut={null}> <span>No Icon or shortcut w/ spacer</span> </SidebarEntry> </div> <div> <span>v 1.0</span> </div> </Sidebar> <div className="p-l-20 p-r-20 p-b-20"> <h2 className="m-t-10">Collapsible Sidebar</h2> <Block className="overflow-auto"> <Lorem /> </Block> </div> </div> </Story> </Canvas> Each `SidebarEntry` can have an icon and a label (the `children` prop). If no icon is specified, a shortcut is generated from the label, if it is a string. Entries can have additional content, which will be visible when the content is expanded (click on the arrow on the right). The `id` prop is required in this case. If the prop `entryClickToggleContent` is passed, then clicking anywhere in the entry label will toggle the content to be shown/hidden. ### Global Sidebar with external trigger If you need to put the status trigger outside of the Sidebar, you need to use the same context of the sidebar. You can set the default state with the helper function `getSidebarContextDefaultState`. `SidebarTrigger` component then can be used to render the trigger. If you want to use a different trigger, you can use `SidebarCustomTrigger`, which accepts a function as children and it's called with three props: - `toggleStatus`: a function that toggles the open/closed status when called; - `sidebarState`: current value of the state; - `setSidebarState`: state setter, to custom control the behavior. The `SidebarBody` component then can be used to generate the sidebar. For example, if you want to put the trigger in the page header, this needs to be wrapped in the sideber provider and the context passed to be used: ```jsx // MainSidebar.js import React from 'react'; import { SidebarBody, SidebarContext } from '@borrow-ui/ui'; // The SidebarBody instance, consuming the context // and a contextualized SidebarEntry export function MainSidebar({ SidebarEntry }) { return ( <SidebarBody hideTrigger={true} shadowWhenOpen={false} className="main-sidebar" stickyTop={true} > <SidebarEntry iconName="home" href="/"> Home </SidebarEntry> </SidebarBody> ); } ``` ```jsx // Layout.js import React, { useState } from 'react'; import { SidebarContext } from '@borrow-ui/ui'; import { MainSidebar } from './MainSidebar'; export function Layout({ Component, pageProps }) { const sidebarState = useState(getSidebarContextDefaultState()); return ( <div className="borrow-ui"> <SidebarContext.Provider value={sidebarState}> <Header /> <div style={{ display: 'flex' }}> <MainSidebar SidebarEntry={SidebarEntry} /> <Component {...pageProps} /> </div> </SidebarContext.Provider> </div> ); } ``` Then, in the `Header` component: ```jsx import React from 'react'; // Use a "contextless" trigger, will be passed import { Navbar, NavbarLink, SidebarTrigger } from '@borrow-ui/ui'; export function Header() { return ( <Navbar left={[ <SidebarTrigger />, { headerLabel: ( <Link href="/"> <NavbarLink>My Site</NavbarLink> </Link> ), name: 'home', }, ]} right={[<span>v 0.1</span>]} /> ); } ``` ### Side menu Another way of using a sidebar is as a container for a side menu. This uses `SidebarMenu` component. The sidebar can be made non-collapsible, so the menu is always visible. <Canvas> <Story name="Sidebar with SidebarMenu"> <div style={{ display: 'flex', width: '100%', height: 400 }}> <Sidebar hideTrigger={true} initialState={{ opened: true }}> <SidebarMenu padded={true}> <SidebarMenu.Title>Section Title 1</SidebarMenu.Title> <SidebarMenu.Entry isActive={true}>Active entry</SidebarMenu.Entry> <SidebarMenu.Entry>Entry 2</SidebarMenu.Entry> <SidebarMenu.Entry>Entry 3</SidebarMenu.Entry> <SidebarMenu.Separator /> <SidebarMenu.Title>Section Title 2</SidebarMenu.Title> <SidebarMenu.Entry>Entry 4</SidebarMenu.Entry> <SidebarMenu.Title>Section Title 3</SidebarMenu.Title> <SidebarMenu.Entry>Entry 5</SidebarMenu.Entry> <SidebarMenu.Entry>Entry 6</SidebarMenu.Entry> </SidebarMenu> </Sidebar> <div className="p-l-20 p-r-20 p-b-20"> <h2 className="m-t-10">Collapsible Sidebar</h2> <Block className="overflow-auto"> <Lorem /> </Block> </div> </div> </Story> </Canvas> Sidebar can also work on top of the content, instead of moving it. Few adjustments needs to be made: - container should have `position: relative`; - the "main page" element should have a `margin-left: 46px` (or bigger); - sidebar should have `position: absolute` and a `z-index: 1` (or higher). <Canvas> <Story name="Sidebar over content"> <div style={{ display: 'flex', width: '100%', height: 400, position: 'relative' }}> <Sidebar style={{ position: 'absolute', zIndex: 1 }}> <div> <SidebarEntry iconName="dashboard">Dashboard</SidebarEntry> <SidebarEntry shortcut="SC">Shortcut</SidebarEntry> <SidebarEntry isActive={true} shortcut="AE"> Active Entry </SidebarEntry> <SidebarEntry id="entry-with-content-arrow" iconName="arrow_forward" content={ <ul> <li>Row 1</li> <li>Row 2</li> </ul> } > Click arrow to view content </SidebarEntry> </div> </Sidebar> <div className="p-l-20 p-r-20 p-b-20" style={{ marginLeft: 46 }}> <h2 className="m-t-10">Collapsible Sidebar over content</h2> <Block className="overflow-auto"> <Lorem /> </Block> </div> </div> </Story> </Canvas> ## Sidebar Props <ArgsTable of={Sidebar} /> ## SidebarBody Props <ArgsTable of={SidebarBody} /> ## SidebarEntry Props <ArgsTable of={SidebarEntry} /> ## SidebarTrigger Props <ArgsTable of={SidebarTrigger} /> <file_sep>/packages/ui/src/components/card/Card.types.ts export interface CardProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** Icon component to render on the side */ icon?: React.ReactNode; /** Content to render instead of icon (i.e. an image) */ sideContent?: React.ReactNode; /** Card title */ title?: React.ReactNode; /** Subtitle rendered below the title */ subtitle?: React.ReactNode; /** The card's main content */ description: React.ReactNode; /** Footer of the card, where to render controls. * The flex alignment is `space-between` so * an empty item (i.e. span) is required if you want * to align one single button to the right. */ controls?: React.ReactNode; /** Card's extra className */ className?: string; /** Apply a shadows to the class */ shadowed?: boolean; /** Enhance the shadow on mouse hover */ standingHover?: boolean; /** Apply a margin on left and bottom: * useful if you are rendering cards one beside another */ marginBetween?: boolean; sideProps?: React.HTMLProps<HTMLDivElement>; iconContainerProps?: React.HTMLProps<HTMLDivElement>; mainProps?: React.HTMLProps<HTMLDivElement>; bodyProps?: React.HTMLProps<HTMLDivElement>; titleProps?: React.HTMLProps<HTMLDivElement>; subtitleProps?: React.HTMLProps<HTMLDivElement>; descriptionProps?: React.HTMLProps<HTMLDivElement>; controlsProps?: React.HTMLProps<HTMLDivElement>; } <file_sep>/packages/ui/src/components/navbar/Navbar.types.ts export type NavbarElementObject = { headerLabel?: React.ReactNode; bodyItem: (...args: any[]) => JSX.Element; showQueryInput?: boolean; floatingControls?: boolean; hideControls?: boolean; }; export type SingleElementType = | React.ReactChild | React.ReactFragment | string | NavbarElementObject; export type NavbarItemType = { showQueryInput?: boolean; floatingControls?: boolean; hideControls?: boolean; }; export interface NavbarProps extends React.ComponentPropsWithoutRef<React.ElementType> { className?: string; /** Position with position:sticky on the top of the container */ sticky?: boolean; /** Use position:fixed to move the navbar on the top of the page, ignoring container */ fixed?: boolean; left?: SingleElementType | Array<SingleElementType>; center?: SingleElementType | Array<SingleElementType>; right?: SingleElementType | Array<SingleElementType>; } export type NavbarStateType = { bodyOpen: boolean; selectedItem: null | SingleElementType; query: string; }; export interface NavbarBodyHeaderControlsProps { toggleBodyOpen: (forcedStatus?: boolean) => void; floating?: boolean; } export interface NavbarBodyHeaderProps { handleChangeQuery: (newQuery: string) => void; toggleBodyOpen: (forcedStatus?: boolean) => void; query?: string; showQueryInput?: boolean; floatingControls?: boolean; hideControls?: boolean; } export interface NavbarBodyProps { selectedItem?: React.ReactNode | NavbarItemType; SelectedItemBody?: React.ComponentType<any> & { query?: string }; query?: string; toggleBodyOpen: (forcedStatus?: boolean) => void; setState: React.Dispatch<React.SetStateAction<NavbarStateType>>; resetState: () => void; } export interface NavbarGroupProps { position: 'left' | 'center' | 'right'; elements: SingleElementType | Array<SingleElementType>; toggleSetItem: (item: SingleElementType, openBody?: boolean) => void; } <file_sep>/packages/ui/src/utils/sharedTypes.ts import { HTMLAttributes, ComponentType, ElementType } from 'react'; export interface TestableDiv extends HTMLAttributes<HTMLDivElement> { 'data-testid'?: string; } export interface TestableInput extends HTMLAttributes<HTMLInputElement> { 'data-testid'?: string; } export type TagType = keyof JSX.IntrinsicElements | ComponentType<any> | ElementType; <file_sep>/packages/dashboard/src/apps/books/api/getReviews.js /** * This shuold come from the database! * * For this example, we are setting a review for the first book of the list. * Value is hard coded. */ export async function getReviews() { return { 1: { id: 1, isbn13: '1001592396277', stars: 4, title: 'Good introduction', description: `This book is a great guide to start learning React again. Probably as good as the tutorial!`, started_on: '2021-05-25', completed: true, recommend_to_friends: true, topics: ['react', 'front-end'], }, }; } <file_sep>/packages/ui/src/components/sidebar-menu/SidebarMenu.types.ts import { TagType } from '../../utils/sharedTypes'; export interface SidebarMenuProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; /** Applies a padding to the content */ padded?: boolean; } export interface SidebarMenuTitleProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; onClick?: React.MouseEventHandler; /** Overrides the tag used to crate the title. If no tag is passed, * it will be set as a `div` or as a `a` if `href` is specified */ tag?: TagType; href?: string; } export interface SidebarMenuEntryProps extends React.ComponentPropsWithoutRef<React.ElementType> { isActive?: boolean; children?: React.ReactNode; className?: string; onClick?: React.MouseEventHandler; /** Overrides the tag used to crate the title. If no tag is passed, * it will be set as a `div` or as a `a` if `href` is specified */ tag?: TagType; href?: string; } export interface SidebarMenuSeparatorProps extends React.ComponentPropsWithoutRef<React.ElementType> { className?: string; } <file_sep>/packages/ui/src/components/tile/Tile.types.ts import { TagType } from '../../utils/sharedTypes'; export interface TileProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** Tile's content */ children?: React.ReactNode; className?: string; /** Customize the tag of Tile */ tag?: TagType; /** Description which will appear on the bottom part of the tile */ description?: React.ReactNode; withBackground?: boolean; } <file_sep>/packages/website-next/content/blog/index.mdx --- title: Blog home --- This section is built using two JS files: - `index.js`: loads this file and then renders the list of posts; - `[slug].js`: the main slug manager, which loads the correspondent file from the content folder. The content of each page is written in MDX and is loaded from `content/blog` folder. If you want to create a new section with a simpler index file that just loads mdx, a slug file needs to be created, and the `index.js` file has to import the necessary function and component from the slug file. In this scenario, the index page should be treated as a special case of slug, otherwise Next.js would consider it literally (i.e. `/blog/index`). An example can be found in the "Project" section. <file_sep>/packages/ui/src/components/sidebar/SidebarTrigger.types.ts import { SidebarStateInterface } from './Sidebar.types'; export interface SidebarTriggerProps extends React.ComponentPropsWithoutRef<React.ElementType> { className?: string; } interface SidebarCustomTriggerChildrenProps { sidebarState: SidebarStateInterface | null; setSidebarState: React.Dispatch<React.SetStateAction<SidebarStateInterface>> | null; toggleStatus: () => void; } export interface SidebarCustomTriggerProps { children: (props: SidebarCustomTriggerChildrenProps) => JSX.Element; } <file_sep>/packages/website-next/core/mdx/providerComponents.js import NextLink from 'next/link'; import { Title, SyntaxHighlight, Monospace, Link } from '@borrow-ui/ui'; let languageRe = /(?<=language-).*$/gm; const titles = { h1: function H1(props) { return <Title tag="h1" className="color-primary" {...props} />; }, h2: function H2(props) { return <Title tag="h2" {...props} />; }, h3: function H3(props) { return <Title tag="h3" {...props} />; }, h4: function H4(props) { return <Title tag="h4" {...props} />; }, h5: function H5(props) { return <Title tag="h5" {...props} />; }, a: function A({ href, ...props }) { if (href && href.substr(0, 4) !== 'http') return ( <NextLink href={href}> <Link tag="a" {...props} /> </NextLink> ); return <Link tag="a" href={href} {...props} />; }, }; function Code(props) { const languageMatches = props.className && props.className.match(languageRe); const language = (languageMatches || []).length > 0 ? languageMatches[0] : undefined; return <SyntaxHighlight language={language} code={props.children} />; } export const providerComponents = { code: Code, inlineCode: Monospace, ...titles, }; <file_sep>/packages/website-next/components/home/Features.js import { Icon } from '@borrow-ui/ui'; import styles from './home.module.scss'; export function Features() { return ( <div className={styles['home__features']}> <Entry icon="settings" title="Configured to work out of the box" description="Start to code immediately your Next.js app using your components library." /> <Entry icon="format_align_left" title="Ready for MDX" description="Pages can be written in MDX and content can be loaded form mdx files." /> <Entry icon="palette" title="SCSS styles" description="Styles are managed with SCSS, and @borrow-ui is ready to be customized." /> <Entry icon="extension" title="Create new components" description="Extend your UI library with custom components and use them in pages and MDX." /> <Entry icon="auto_stories" title="Commented code" description="Project's code is easy to understand and well commented." /> <Entry icon="account_tree" title="Easy to maintain" description="Pages and components are structured in an easy and scalable way." /> </div> ); } function Entry({ icon, title, description }) { return ( <div className={styles['home__features__entry']}> <div className={styles['home__features__entry__title']}> <Icon name={icon} /> <span>{title}</span> </div> <div className={styles['home__features__entry__description']}>{description}</div> </div> ); } <file_sep>/packages/ui/src/index.ts // Configuration export { setConfig, getConfig } from './config'; // Components export { Accordion, AccordionGroup } from './components/accordion/Accordion'; export { Badge } from './components/badge/Badge'; export { Block } from './components/block/Block'; export { Breadcrumbs } from './components/breadcrumbs/Breadcrumbs'; export { Button } from './components/button/Button'; export { Card } from './components/card/Card'; export { Row, Col } from './components/grid/Grid'; export { Icon } from './components/icon/Icon'; export { IconControl } from './components/icon/IconControl'; export { Link } from './components/link/Link'; export { Loader } from './components/loader/Loader'; export { Lorem } from './components/lorem/Lorem'; export { Menu } from './components/menu/Menu'; export { MenuDivider } from './components/menu/MenuDivider'; export { MenuEntry } from './components/menu/MenuEntry'; export { Modal, ModalWindow } from './components/modal/Modal'; export { Monospace } from './components/text/Monospace'; export { Navbar } from './components/navbar/Navbar'; export { NavbarLink } from './components/navbar/NavbarLink'; export { NavbarMenu } from './components/navbar-menu/NavbarMenu'; export { NavbarMenuItem } from './components/navbar-menu/NavbarMenuItem'; export { NavbarMenuTitle } from './components/navbar-menu/NavbarMenuTitle'; export { Page } from './components/page/Page'; export { PageBody } from './components/page/PageBody'; export { PageHeader } from './components/page/PageHeader'; export { Panel } from './components/panel/Panel'; export { ReferenceOverlay } from './components/reference-overlay/ReferenceOverlay'; export { Responsive } from './components/responsive/Responsive'; export { Sidebar, SidebarBody } from './components/sidebar/Sidebar'; export { SidebarContext, getSidebarContextDefaultState } from './components/sidebar/SidebarContext'; export { SidebarEntry } from './components/sidebar/SidebarEntry'; export { SidebarIcon } from './components/sidebar/SidebarIcon'; export { SidebarTrigger, SidebarCustomTrigger } from './components/sidebar/SidebarTrigger'; export { SidebarMenu } from './components/sidebar-menu/SidebarMenu'; export { Subtitle } from './components/text/Subtitle'; export { SyntaxHighlight } from './components/syntax-highlight/SyntaxHighlight'; export { Table } from './components/table/Table'; export { Tabs } from './components/tabs/Tabs'; export { Text } from './components/text/Text'; export { TextContainer } from './components/text/TextContainer'; export { Tile } from './components/tile/Tile'; export { TileLink } from './components/tile-link/TileLink'; export { Title } from './components/text/Title'; export { Tooltip } from './components/tooltip/Tooltip'; export { Forms } from './components/forms'; // hooks export { useHover } from './hooks/useHover'; export { useLocationHash } from './hooks/useLocationHash'; /** * The following exports are redundant with Forms, * but allows for auto discovery and import directly * with editor's autocomplete. */ export { Checkbox } from './components/forms/checkbox/Checkbox'; export { DatePicker } from './components/forms/date-picker/DatePicker'; export { Dropzone } from './components/forms/dropzone/Dropzone'; export { DropzoneFiles, DropzoneFile } from './components/forms/dropzone/DropzoneFiles'; export { Field, VField, HField } from './components/forms/field/Field'; export { Input } from './components/forms/input/Input'; export { Label } from './components/forms/label/Label'; export { ReactSelect } from './components/forms/react-select/ReactSelect'; export { ReactSelect as Select } from './components/forms/react-select/ReactSelect'; export { Textarea } from './components/forms/textarea/Textarea'; export { Toggle } from './components/forms/toggle/Toggle'; <file_sep>/packages/ui/src/components/block/Block.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from './Block'; import { Lorem } from '../lorem/Lorem'; <Meta title="Components/Block" component={Block} /> # Block A `Block` can be used to wrap text or components. It has shortcuts for padding and margin, shadow and round borders, make the text centered (both vertically and horizontally) and to add a title, which can be customized via `titleProps` property. <Canvas> <Story name="Default"> <Block title="Block title"> <Lorem /> </Block> </Story> </Canvas> ### Container props The `Block` container can be customized with different properties: - `separated` adds a margin; - `padded` adds padding; - `rounded` makes border rounded; - `outstanding` adds a shadow to make the block outstading from the background; - `outstandingHover` use outstanding class when the block is hovered. <Canvas> <Story name="Outstanding Squared"> <Block outstanding={true} rounded={false}> With `outstanding` set to `true`. <Lorem paragraphs={1} /> </Block> </Story> </Canvas> Can also receive a `title` that is a component (not a string): <Canvas> <Story name="Title"> <Block outstanding={true} rounded={false} title={<h2 style={{ color: 'red' }}>Red title</h2>} > Is the title in red? <Lorem paragraphs={1} /> </Block> </Story> </Canvas> ### Content props A shortcut to make the content centered is also present: `contentCentered` prop. <Canvas> <Story name="Content Props"> <Block outstanding={true} contentCentered={true} style={{ height: 200 }}> Height of 200px </Block> </Story> </Canvas> ## Props <ArgsTable of={Block} /> --- ## React Tutorial As a text wrapper, the Block component starts by wrapping the content: ```jsx import React from 'react'; export function Block({ children }) { return ( <div>{children}</div>; ); } ``` A set of props, along with a main `className`, can be passed to customize the block style. For an example, see the [Badge tutorial](/components/badge#tutorial). ### Title and sub-components props A special prop, `title`, can be used to generate a title for the block. ```jsx import React from 'react'; export function Block({ title = '', children }) { // Generate a title class const titleClass = 'title'; return ( <div> {title && <h2 className={titleClass}>{title}</h2>} {children} </div>; ); } ``` However, it would be convenient if we could also customize the title props as well. To separate the class customization from the main class for the block, we can use a `titleProps` main prop which will be used to customize the title component. The first try would be to spread the `titleProps`: ```jsx <h2 className={titleClass} {...titleProps}> {title} </h2> ``` but this would override the class generated. An easy trick is then to extract the `className` from the `titleProps` and append that new value to the generated one: ```jsx import React from 'react'; export function Block({ title = '', titleProps = {}, children }) { // Extract the nested class const { className: titleClassName = '', ...restTitleProps } = titleProps; // Generate a title class const titleClass = `title ${titleClassName}`.trim(); return ( <div> {title && <h2 className={titleClass} {...restTitleProps}>{title}</h2>} {children} </div>; ); } ``` This is done via the object destructuring rename feature ([see here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assigning_to_new_variable_names)). The `className` prop is assigned to a variable called `titleClassName`, and all the other defined properties to the `restTitleProps` object. <file_sep>/packages/ui/src/components/panel/Panel.types.ts import { TagType } from '../../utils/sharedTypes'; type SetVisibleType = React.Dispatch<React.SetStateAction<boolean>>; type GetPanelContentPropsInput = { setVisible: SetVisibleType }; type OnOpenInput = { resolve: (value: unknown) => void; reject: (reason?: any) => void }; interface PanelConfigurationInterface { /** Main content to be shown in the panel */ content?: React.ReactNode; /** Title of the panel */ title?: React.ReactNode; /** Items to be shown in the header (like in `PageHeader` component) */ controls?: React.ReactNode; /** Footer of the panel. A `flex` display is used with `space-between`, * so if you need to add elements only on the right you need to pass also * an empty item for the left. */ footer?: React.ReactNode; /** hooks called when the panel: * * - opens: `onOpen`, this must be a promise. */ hooks?: { onOpen?: (arg0: OnOpenInput) => Promise<void> | void; }; /** Width of the panel. */ width?: number | string; /** Width of the content. If you specify `width` as percentage, you need to specify */ innerContainerWidth?: number; /** Add a wrapper */ showWrapper?: boolean; /** Props to be passed to modal's container, inside wrapper element */ containerProps?: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's content, inside wrapper element */ contentProps?: React.HTMLProps<HTMLDivElement>; /** Props to be passed to modal's footer, inside wrapper element */ footerProps?: React.HTMLProps<HTMLDivElement>; } export interface PanelContentProps extends PanelConfigurationInterface { /** Set the panel visible */ visible?: boolean; /** setVisible callback, passed by `Panel` component */ setVisible: (isVisible: boolean) => void; } export interface PanelProps { Trigger: TagType; getPanelContentProps: (arg0: GetPanelContentPropsInput) => PanelConfigurationInterface; } <file_sep>/packages/ui/src/components/loader/Loader.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from '../button/Button'; import { Loader } from './Loader'; <Meta title="Components/Loader" component={Loader} /> # Loader Loaders are usually used when some content is not available and a process needs to be completed. There are three loader types available: `triangle`, `line` and `inline`. The default loader is `triangle`: <Canvas> <Story name="Default"> <div> <Loader /> </div> </Story> </Canvas> The `line` loader extends horizontally: <Canvas> <Story name="Line"> <div> <Loader type="line" /> </div> </Story> </Canvas> The inline one can be put within other content: <Canvas> <Story name="Inline"> <div> <div> This is inline <Loader type="inline" /> with content. </div> <div> It can also be used inside a button: <Button disabled={true} mean="neutral-reverse"> <Loader type="inline" className="m-r-5" /> Loading </Button> </div> </div> </Story> </Canvas> ## Props Note: the `...rest` spread is passed to the loader container. <ArgsTable of={Loader} /> <file_sep>/packages/ui/src/components/text/TextContainer.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Lorem } from '../lorem/Lorem'; import { Title } from './Title'; import { TextContainer } from './TextContainer'; <Meta title="Components/Typography/TextContainer" component={TextContainer} /> # TextContainer `TextContainer` component is used to wrap text. It will limit the width to 960px to make it readable in big screens. <Canvas> <Story name="Default"> <Title>Paragraph 1 - not wrapped</Title> <Lorem /> <Lorem /> <Lorem /> <TextContainer> <Title>Paragraph 2 - wrapped in TextContainer</Title> <Lorem /> <Lorem /> <Lorem /> </TextContainer> </Story> </Canvas> ## TextContainer Props <ArgsTable of={TextContainer} /> <file_sep>/packages/ui/src/components/page/Page.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Button } from '../button/Button'; import { Row, Col } from '../grid/Grid'; import { Icon } from '../icon/Icon'; import { Lorem } from '../lorem/Lorem'; import { Text } from '../text/Text'; import { Monospace } from '../text/Monospace'; import { Page } from './Page'; import { PageHeader } from './PageHeader'; import { PageBody } from './PageBody'; <Meta title="Components/Page" component={Page} /> # Page The `Page` component allows to create pages in a consistent way. It offers few helpers to have an header always visible (with a shadow if the body is scrolled) and a container for the body. The default behaviour can be customized with the following props: - `continuousScroll`: makes the header part of the page and allows to scroll the entire page (not only the body); - `readableContent`: limits the widths to 1300 pixels, so big screens will not generate a page too wide; - `headerVisibleFollowRef`: makes the header title visible only if the React Reference passed is not visible. <Canvas> <Story name="Default"> <div style={{ height: 400, fontSize: '14px', overflow: 'hidden' }}> <Page title="Page Title" style={{ height: '100%' }}> <Text> This content will be rendered inside the body of the page, via{' '} <Monospace>PageBody</Monospace> component. </Text> <Lorem paragraphs={3} /> <Lorem paragraphs={3} /> </Page> </div> </Story> </Canvas> ### continuousScroll property If you want to make the title scrolling away when the pages scroll, use the `continuousScroll` property: <Canvas> <Story name="Continuous Scroll"> <div style={{ height: 400, fontSize: '14px' }}> <Page title="Page Title" continuousScroll={true}> <Text> This content will be rendered inside the body of the page, via{' '} <Monospace>PageBody</Monospace> component. </Text> <Lorem paragraphs={3} /> <Lorem paragraphs={3} /> <Lorem paragraphs={3} /> </Page> </div> </Story> </Canvas> ### headerVisibleFollowRef property If you want to make the title visible only when an element is not visible, you can pass it's ref to the page with the `headerVisibleFollowRef` prop: ```jsx import React, { useRef } from 'react'; import { Lorem } from '../lorem/Lorem'; import { Page } from './Page'; export function PageStoryheaderVisibleFollowRef() { const textRef = useRef(null); return ( <Page title="This should be visible only if element is not" headerVisibleFollowRef={textRef} pageHeaderProps={{ className: 'color-neutral-white-bg', headerVisibleFollowOffset: 100, }} > <div style={{ height: 100 }} className="color-accent-bg flex-center-center"> <h2 className="color-on-accent" size="big" ref={textRef}> While this element is visible, title should be hidden. </h2> </div> <Lorem /> <Lorem /> </Page> ); } ``` The title will be visible on top of the page. An offset can be specified via `headerVisibleFollowOffset` prop (see `PageHeader` component). You can see a demo in the [borrow-ui homepage](https://www.borrow-ui.dev). # PageHeader controls Sometimes it is useful to show buttons or icons in the top right of the page, aligned with page title inside the header. The `controls` prop accepts valid children and will be rendered inside `PageHeader`. <Canvas> <Story name="PageHeader Controls"> <div style={{ height: 400, fontSize: '14px', overflow: 'hidden' }}> <Page title="Page Title" style={{ height: '100%' }} pageHeaderProps={{ controls: ( <Fragment> <Button onClick={() => window.alert('clicked')} mean="primary"> Add item </Button> <Icon name="settings" className="m-l-5 color-neutral" onClick={() => window.alert('settings')} /> </Fragment> ), }} > <Lorem paragraphs={3} /> <Lorem paragraphs={3} /> </Page> </div> </Story> </Canvas> ## Page Props <ArgsTable of={Page} /> ## PageHeader Props <ArgsTable of={PageHeader} /> ## PageBody Props <ArgsTable of={PageBody} /> <file_sep>/packages/dashboard/src/apps/books/components/reviews/ReviewDetail.js /** * Shows one review. * * Instead of being a simple field/value, this component tries to * represent the data with icons for boolean values and a * multi-line text component for the main description. */ import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { Icon, Title, IconControl, Badge } from '@borrow-ui/ui'; import { beautify } from 'utils/strings'; import { MultiLineText } from 'components/common/MultiLineText'; import { BOOKS_REVIEW_BASE_URL } from 'apps/books/constants'; import { DeleteReviewIconControl } from './DeleteReviewIconControl'; import './reviewDetail.scss'; export function ReviewDetail({ review, deleteReview }) { return ( <div className="review"> <Title tag="h3" className="flex-spacebetween-center"> {review.title} <div className="review__controls"> <Link to={`${BOOKS_REVIEW_BASE_URL}/${review.id}/edit`}> <IconControl name="edit" className="m-l-15" /> </Link> <DeleteReviewIconControl reviewId={review.id} deleteReview={deleteReview} /> </div> </Title> <div className="flex-start-center"> <div className="review__info"> {new Array(5) .fill(0) .map((_, i) => i < review.stars ? ( <Icon key={i} name="star" size="smaller" className="color-secondary m-r-5" /> ) : ( <Icon key={i} name="star_outline" size="smaller" className="color-neutral-light m-r-5" /> ) )} </div> <div className="review__info"> {review.topics.map((topic) => ( <Badge key={topic} color="secondary" className="m-l-0 m-r-10"> {beautify(topic)} </Badge> ))} </div> </div> <div className="flex-start-center m-t-15"> <div className="review__info"> <span className="color-neutral-light m-r-5">Started on </span> {review.started_on} {review.completed && ( <> <Icon name="check" size="small" className="color-positive m-l-20 m-r-5" /> <span className="color-neutral-light">Completed</span> </> )} {!review.completed && ( <> <Icon name="close" size="small" className="color-negative m-l-20 m-r-5" /> <span className="color-neutral-light">Not Completed (yet)</span> </> )} </div> <div className="review__info"> {review.recommend_to_friends && ( <> <Icon name="check" size="small" className="color-positive m-r-5" /> <span className="color-neutral-light">Recommend to friends</span> </> )} {!review.recommend_to_friends && ( <> <Icon name="close" size="small" className="color-negative m-r-5" /> <span className="color-neutral-light">Would not recommend</span> </> )} </div> </div> <div className="m-t-15"> <MultiLineText text={review.description} /> </div> </div> ); } ReviewDetail.propTypes = { review: PropTypes.object.isRequired, }; <file_sep>/packages/ui/src/components/forms/textarea/Textarea.types.ts export interface TextareaProps extends React.ComponentPropsWithRef<React.ElementType> { disabled?: boolean; invalid?: boolean; className?: string; } <file_sep>/packages/dashboard/src/apps/books/pages/home/BooksHomePage.js /** * The home page of the books app. * * This page uses the store (context) to retrieve the books * and to show them as a list. * * This component could definitely use more creativity and reprents books * in different ways (i.e. with shelves!), but for this demo a table * is more straightforward to keep the code compact. */ import { useContext } from 'react'; import { Link } from 'react-router-dom'; import { Breadcrumbs, Button, Page, Responsive } from '@borrow-ui/ui'; import { storeContext } from 'store'; import { DASHBOARD_SMALL_SCREEN_MEDIA_QUERIES } from 'configs'; import { BOOKS_BOOK_BASE_URL } from 'apps/books/constants'; import { booksModel } from 'apps/books/models/book'; import { BooksList } from 'apps/books/components/books/BooksList'; export function BooksHomePage() { const { store, setStore } = useContext(storeContext); return ( <Page title={ <> <Breadcrumbs breadcrumbs={[{ link: '/', label: 'Home' }]} /> Books Home </> } pageHeaderProps={{ controls: ( <Button mean="primary" tag={Link} to={`${BOOKS_BOOK_BASE_URL}/add`}> Add Book </Button> ), }} > <Responsive queries={DASHBOARD_SMALL_SCREEN_MEDIA_QUERIES}> {({ small }) => ( <BooksList books={Object.values(store.books.books)} deleteBook={(isbn13) => booksModel.delete(setStore, isbn13)} showSubtitle={!small} /> )} </Responsive> </Page> ); } <file_sep>/packages/ui/src/components/text/Subtitle.types.ts import { TextProps } from './Text.types'; export interface SubtitleProps extends TextProps {} <file_sep>/packages/ui/src/components/icon/Icon.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import '@fortawesome/fontawesome-free/css/all.css'; import { Icon } from './Icon'; import { IconControl } from './IconControl'; <Meta title="Components/Icon" component={Icon} /> # Icon ## Sets and installation Icons are a great way to represent concepts with images. `borrow-ui` icons are flexible and allows to use different families/vendors. The default set of icon is [Material Design Icons DX](https://jossef.github.io/material-design-icons-iconfont/). The demo application also works with the latest [Font Awesome](http://fontawesome.io/icons/). Each set has to be installed separately and it's not bundled with `borrow-ui`. ```bash yarn add material-design-icons-iconfont yarn add @fortawesome/fontawesome-free ``` And then in your App: ```jsx import 'material-design-icons-iconfont/dist/material-design-icons.css'; import '@fortawesome/fontawesome-free/css/all.css'; ``` ## Usage The `Icon` component has two main props: - `name`: used to specify the name of the icon, i.e. `content_copy` for material or `fa-camera` for fontawesome; - `family`: used to specify the family: by default it is `material-icons`; for fontawesome icons you need to specify the category, like `fas` or `fab`. <Canvas> <Story name="Default"> <div> <Icon name="content_copy" className="color-primary" /> <Icon name="fa-camera" family="fas" className="color-primary m-l-20" /> </div> </Story> </Canvas> The `size` prop can be used to apply a specific size class: <Canvas> <Story name="Size"> <div> <Icon name="view_in_ar" size="huge" className="color-primary" /> <Icon name="view_in_ar" size="bigger" className="color-accent" /> <Icon name="view_in_ar" size="big" className="color-primary" /> <Icon name="view_in_ar" className="color-accent" /> <Icon name="view_in_ar" size="small" className="color-primary" /> <Icon name="view_in_ar" size="smaller" className="color-accent" /> </div> </Story> </Canvas> Two modifiers are available: `clickable` (which adds a pointer cursor) and `spin`. If the `onClick` property is set, `clickable` modifier will be added automatically. For animation it is suggested to use native icons classes if available (i.e. `fa-spin`). <Canvas> <Story name="Modifiers"> <div> <span className="p-20 display-inline-block"> <Icon name="weekend" size="big" onClick={() => window.alert('Enjoy the weekend!')} /> </span> <span className="p-20 display-inline-block"> <Icon name="work" size="big" modifiers={['clickable']} /> </span> <span className="p-20 display-inline-block"> <Icon name="videocam" size="big" modifiers={['spin']} /> </span> </div> </Story> </Canvas> ### IconControl A spcial wrapper of the `Icon` component is the `IconControl`. `IconControl`s are rendered as small icons with a circle background on hover, and allows to trigger the `onClick` property when focused by pressing the space-bar (add `tabIndex` property as well). They pass the other `props` to the `Icon` component. <Canvas> <Story name="IconControl"> <div> <span className="p-20 display-inline-block"> <IconControl name="add" tabIndex="0" onClick={() => window.alert('clicked')} /> </span> <span className="p-20 display-inline-block"> <IconControl name="remove" tabIndex="0" onClick={() => window.alert('clicked')} /> </span> <span className="p-20 display-inline-block"> <IconControl name="fullscreen" tabIndex="0" onClick={() => window.alert('clicked')} /> </span> </div> </Story> </Canvas> ## Props <ArgsTable of={Icon} /> <file_sep>/packages/ui/src/components/icon/IconControl.types.ts import { IconProps } from './Icon.types'; export interface IconControlProps extends IconProps {} <file_sep>/packages/ui/src/components/forms/index.ts import { LAYOUTS } from './constants'; import { Checkbox } from './checkbox/Checkbox'; import { DatePicker } from './date-picker/DatePicker'; import { Dropzone } from './dropzone/Dropzone'; import { DropzoneFiles, DropzoneFile } from './dropzone/DropzoneFiles'; import { Field, VField, HField } from './field/Field'; import { Input } from './input/Input'; import { Label } from './label/Label'; import { ReactSelect } from './react-select/ReactSelect'; import { Textarea } from './textarea/Textarea'; import { Toggle } from './toggle/Toggle'; export const Forms = { Checkbox, DatePicker, Dropzone, DropzoneFiles, DropzoneFile, Field, HField, Input, Label, ReactSelect, Select: ReactSelect, Textarea, Toggle, VField, LAYOUTS, }; <file_sep>/packages/website-next/pages/project/[slug].js import path from 'path'; import React from 'react'; import Head from 'next/head'; import { MDXRemote } from 'next-mdx-remote'; import { MDXProvider } from '@mdx-js/react'; import * as uiLibrary from '@borrow-ui/ui'; import { generateGetStaticPaths, generateGetStaticProps } from '../../core/mdx/mdx'; import { providerComponents } from '../../core/mdx/providerComponents'; const SOURCE_PATH = path.join(process.cwd(), 'content/project'); const { Title } = uiLibrary; const Content = ({ code, metadata }) => { const title = `Project`; return ( <> <Head> <title>{title}</title> <meta property="og:title" content={title} key="title" /> </Head> <MDXProvider components={providerComponents}> <> <div className="website__text" style={{ paddingBottom: 30 }}> <Title className="color-primary">{metadata.title}</Title> <MDXRemote {...code} /> </div> </> </MDXProvider> </> ); }; export const getStaticProps = generateGetStaticProps(SOURCE_PATH); export const getStaticPaths = generateGetStaticPaths(SOURCE_PATH); export default Content; <file_sep>/packages/dashboard/src/apps/books/Routes.js /** * Entry point component for the `books` application. * In this component store content can be initialized, or * at least related/mandatory entities can be fetched. * * For example, categories of books can be preloaded from the * database to be used without fetching them in every component. * * In this demo, the books are loaded when the apps store is * initialized so they might not be loaded yet. * For this reason, a Loader is shown until the store is filled. */ import { useContext } from 'react'; import { Routes, Route } from 'react-router-dom'; import { Loader } from '@borrow-ui/ui'; import { storeContext } from 'store'; import { BooksHomePage } from './pages/home/BooksHomePage'; import { BookDetailPage } from './pages/books/detail/BookDetailPage'; import { AddBookPage } from './pages/books/forms/AddBookPage'; import { EditBookPage } from './pages/books/forms/EditBookPage'; import { AddReviewPage } from './pages/reviews/forms/AddReviewPage'; import { EditReviewPage } from './pages/reviews/forms/EditReviewPage'; import { BOOKS_BASE_URL } from './constants'; export { BOOKS_BASE_URL }; export function BooksRoutes() { const { store } = useContext(storeContext); // if books are not loaded yet, show a Loader // in this way we can avoid to put this check around if (!store.books || !store.books.books) return ( <div className="w-100 h-100 flex-center-center"> <Loader /> </div> ); return ( <Routes> <Route index element={<BooksHomePage />} /> <Route exact path={`book/add`} element={<AddBookPage />} /> <Route exact path={`book/:isbn13/edit`} element={<EditBookPage />} /> <Route exact path={`book/:isbn13`} element={<BookDetailPage />} /> <Route exact path={`review/add/:isbn13`} element={<AddReviewPage />} /> <Route exact path={`review/:id/edit`} element={<EditReviewPage />} /> </Routes> ); } <file_sep>/packages/ui/src/utils/propTypes.js import PropTypes from 'prop-types'; const propTypesChild = PropTypes.oneOfType([PropTypes.func, PropTypes.node, PropTypes.object]); export const propTypesChildren = PropTypes.oneOfType([ propTypesChild, PropTypes.arrayOf(propTypesChild), ]); export const propTypesRef = PropTypes.oneOfType([ // A function PropTypes.func, // Or the instance of a DOM native element (see the note about SSR) PropTypes.shape({ current: PropTypes.object }), ]); export const propTypesRefElement = PropTypes.oneOfType([ // A function PropTypes.func, // Or the instance of a DOM native element - requires Element shim for SSR: // Element = typeof Element === 'undefined' ? function(){} : Element PropTypes.shape({ current: PropTypes.instanceOf(PropTypes.element) }), ]); <file_sep>/packages/ui/src/components/sidebar/SidebarEntry.types.ts import { TagType } from '../../utils/sharedTypes'; import { IconProps } from '../icon/Icon.types'; export interface SidebarEntryProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; /** Name of the icon */ iconName?: string; /** Shortcut alternative to the icon */ shortcut?: string; /** Link associated with the entry */ link?: string; /** Elements visible only when the sidebar is open and expanded */ content?: React.ReactNode; /** Entry id, required if `content` is passed */ id?: string; /** Additional properties passed to the icon component */ iconProps?: IconProps; /** Tag to use for the entry */ tag?: TagType; /** Flag to apply active class */ isActive?: boolean; /** Flag to determine if clicking the label will toggle the content */ entryClickToggleContent?: boolean; /** Link target for react-router */ to?: string; /** Link target for standard links or Next */ href?: string; role?: string; underline?: boolean; onClick?: React.MouseEventHandler; } <file_sep>/packages/dashboard/src/apps/books/store.js /** * Initialize the app store. * When initialized, the books are loaded with the models * `getList` method, and added to the store. */ import { booksModel } from './models/book'; import { reviewsModel } from './models/review'; export async function initializeBookStore(store, setStore) { if (store.books) return true; const books = await booksModel.getList(); const reviews = await reviewsModel.getList(); setStore((s) => ({ ...s, books: { books, reviews } })); } <file_sep>/packages/ui/src/components/reference-overlay/ReferenceOverlay.types.ts import { TagType } from '../../utils/sharedTypes'; type PLACEMENT_SE = '' | '-start' | '-end'; type PLACEMENT_POS = 'auto' | 'top' | 'bottom' | 'left' | 'right'; export type ReferenceOverlayPlacementType = `${PLACEMENT_POS}${PLACEMENT_SE}`; export type ReferenceOverlayTriggerModeType = 'hover' | 'click'; export interface ReferenceOverlayProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** Content of the overlay */ overlayContent?: React.ReactNode; /** Trigger content */ children?: React.ReactNode; className?: string; /** Overlay placement. * See [popper documentation](https://popper.js.org/docs/v2/constructors/#options). */ placement?: ReferenceOverlayPlacementType; /** Which event will make the tooltip visible */ triggerMode?: ReferenceOverlayTriggerModeType; /** Props passed to the trigger container */ triggerProps?: React.HTMLProps<any>; /** Tag to be used as trigger/wrapper (i.e. for thead or cells). * Defaults to 'div'. */ triggerTag?: TagType; /** Props passed to the overlay container */ overlayProps?: React.HTMLProps<HTMLDivElement> & { className?: string; style?: React.CSSProperties; 'data-testid'?: string; }; /** Props passed to the overlay arrow container */ overlayArrowProps?: React.HTMLProps<HTMLDivElement> & { className?: string; style?: React.CSSProperties; }; /** Props forwarded to popper hook. * See [documentation](https://popper.js.org/react-popper/v2/hook/). */ popperProps?: any; portalRef?: React.RefObject<HTMLElement>; } export interface ReferenceOverlayContentProps { overlayContent?: React.ReactNode; triggerMode: ReferenceOverlayTriggerModeType; overlayProps: React.HTMLProps<HTMLDivElement> & { className?: string; style?: React.CSSProperties; }; overlayArrowProps: React.HTMLProps<HTMLDivElement> & { className?: string; style?: React.CSSProperties; }; portalRef?: React.RefObject<HTMLElement>; setPopperElement: React.Dispatch<React.SetStateAction<HTMLElement | null>>; attributes: { popper?: any }; setArrowElement: React.Dispatch<React.SetStateAction<HTMLElement | null>>; isVisible?: boolean; setIsVisible: React.Dispatch<React.SetStateAction<boolean>>; styles: { [key: string]: React.CSSProperties; }; update: (() => Promise<Partial<any>>) | null; } <file_sep>/packages/ui/src/components/responsive/Responsive.types.ts import React from 'react'; import { MediaQueryValue, QueryResults } from 'react-media'; export interface ResponsiveProps { /** An object with name of the query as key and media query as value */ queries?: { [key: string]: MediaQueryValue }; /** Just the media query: the component content will be rendered only if the query passes. */ query?: MediaQueryValue; children: (matches: any) => React.ReactNode; } <file_sep>/packages/ui/src/components/panel/Panel.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from '../button/Button'; import { Lorem } from '../lorem/Lorem'; import { Panel, PanelContent } from './Panel'; <Meta title="Components/Panel" component={Panel} /> # Panel Panels are content containers that slides from the right. The `Panel` component expects two props, both functions (similarly to `Modal` component): - `Trigger`: a function that returns an element used to trigger the panel; - `getPanelContentProps`: a function that returns an object with valid `PanelContent` props. Both functions have one argument: an object with a `setVisible` property. This is a function that takes a boolean as argument and can make the modal visible or not. <Canvas> <Story name="Default"> <Panel Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary"> Open Panel </Button> )} getPanelContentProps={() => ({ title: 'Panel demo title', content: <Lorem paragraphs={3} />, })} /> </Story> </Canvas> ## PanelContent props examples ### Title and foooter Both title and footer can be passed/customized. The title isset via `title` prop; the header also accepts a `controls` (like `PageHeader`) and the footer can be set via `footer` prop. <Canvas> <Story name="Title and Footer"> <Panel Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="accent"> Open Panel </Button> )} getPanelContentProps={({ setVisible }) => ({ title: <h3 className="color-accent">Custom title</h3>, controls: ( <Button onClick={() => window.alert('clicked')} size="small"> Test </Button> ), content: <Lorem paragraphs={3} />, footer: ( <Fragment> <Button onClick={() => setVisible(false)} mean="negative"> Close </Button> <Button onClick={() => setVisible(false)} mean="positive"> Save </Button> </Fragment> ), })} /> </Story> </Canvas> ### Width The `Panel` width can be set via `width` prop, and the content width via `innerContainerWidth`. <Canvas> <Story name="Width"> <Fragment> <Panel Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)}>Open Panel (400px - 300px)</Button> )} getPanelContentProps={() => ({ title: 'Panel demo title', content: <Lorem paragraphs={3} />, width: 400, innerContainerWidth: 300, })} /> <Panel Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="neutral-reverse"> Open Panel (75% - 300px) </Button> )} getPanelContentProps={() => ({ title: 'Panel demo title', content: <Lorem paragraphs={3} />, width: '75%', innerContainerWidth: 300, })} /> <Panel Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)}>Open Panel (75% - auto)</Button> )} getPanelContentProps={() => ({ title: 'Panel demo title', content: <Lorem paragraphs={3} />, width: '75%', })} /> </Fragment> </Story> </Canvas> ### onOpen hook It is possible to specify a callback called when the component is open via `onOpen` callback. This can be useful for example if you need to define a state variable and populate it asynchronously, like `const [variableContent, setVariableContent] = useState(null);`. <Canvas> <Story name="onOpen hook"> <Panel Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary"> Open Panel with onOpen </Button> )} getPanelContentProps={() => ({ title: 'Panel demo title', content: <Lorem paragraphs={3} />, // use variableContent hooks: { onOpen: ({ resolve }) => { setTimeout(() => { // setVariableContent('Content set after 1500 ms.'); resolve(); }, 1500); }, }, })} /> </Story> </Canvas> ## Panel Props <ArgsTable of={Panel} /> ## PanelContent Props <ArgsTable of={PanelContent} /> <file_sep>/packages/ui/src/hooks/useLocationHash.ts import { useEffect, useState } from 'react'; export function useLocationHash(): string { /** * Returns location.hash if on client, or '' when on SSR */ // Ignore the line, check done for SSR // istanbul ignore next const hash = typeof window !== 'undefined' ? window.location.hash : ''; const [locationHash, setLocationHash] = useState(hash.split('?')[0].substring(1)); useEffect(() => { setLocationHash(hash.split('?')[0].substring(1)); }, [hash]); return locationHash; } <file_sep>/packages/ui/src/hooks/useHover.stories.mdx import { Meta } from '@storybook/addon-docs'; <Meta title="Hooks/useHover" /> # useHover `useHover` hook is used to determine if an element is hovered (the cursor is on it). It returns a `ref` that has to be passed to the element we want to test and a boolean telling if the element is hovered or not. ### Usage ```jsx import { useHover } from '@borrow-ui/ui'; export function PageWithElements() { // hooks and state const [hoverRef, isHovered] = useHover(); // .... // other code const hoveredClass = isHovered ? 'link-class__hovered' : ''; return ( <div> <a ref={hoverRef} className={hoveredClass}> Title </a> <Lorem /> </div> ); } ``` <file_sep>/packages/dashboard/src/utils/strings.js /** * Example of a shared utility. * * The beautify function creates a readable version from a coded string, * i.e. react_programming -> React Programming. */ export function ucFirst(string) { return string && typeof string === 'string' ? string.charAt(0).toUpperCase() : ''; } export function beautify(string, { separator = '_' } = {}) { if (!string) return ''; return string .split(separator) .map((p) => ucFirst(p) + p.substr(1)) .join(' '); } <file_sep>/packages/ui/src/components/sidebar/Sidebar.types.ts export interface SidebarStateInterface { /** Sidebar initialize as opened */ opened: boolean; /** Object to determine which entry content is opened (id -> true) */ openedEntrySubContent: { [key: string | number]: boolean }; /** Automatically close the Sidebar if a link is clicked */ autoCloseLink: boolean; } export interface SidebarStateOverrideInterface { /** Sidebar initialize as opened */ opened?: boolean; /** Object to determine which entry content is opened (id -> true) */ openedEntrySubContent?: { [key: string | number]: boolean }; /** Automatically close the Sidebar if a link is clicked */ autoCloseLink?: boolean; } export interface SidebarBodyProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** If elements does not require sidebar's state, the content can be passed as children. */ children?: React.ReactNode; className?: string; style?: React.CSSProperties; /** Hide the trigger to open/close the sidebar. */ hideTrigger?: boolean; /** Make the sidebar sticky to the top; expects pixel value. */ stickyTop?: number; /** Overrides the height of the container. */ height?: string | number; /** Width of the sidebar when is closed. */ closedWidth?: string | number; /** Apply a shadow when the sidebar is open. */ shadowWhenOpen?: boolean; } export interface SidebarProps extends SidebarBodyProps { initialState?: SidebarStateOverrideInterface; } <file_sep>/packages/ui/src/components/tooltip/Tooltip.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from '../button/Button'; import { Icon } from '../icon/Icon'; import { IconControl } from '../icon/IconControl'; import { Lorem } from '../lorem/Lorem'; import { Tooltip } from './Tooltip'; <Meta title="Components/Tooltip" component={Tooltip} /> # Tooltip Tooltips are a great way to show additional content with user interaction. Usually the are visible when an element is clicked or hovered. The `Tooltip` component accepts two main props: - `tooltip`: the tooltip content; - `children`: an element that, when hovered or clicked, will show the tooltip; The component leverages `ReferenceOverlay` component that is based on the great external library [Popper](https://popper.js.org/) and it's hook. <Canvas> <Story name="Default"> <div style={{ padding: 60 }}> <Tooltip tooltip="This is a simple tooltip" className="m-r-20"> <Button mean="positive">Hover me!</Button> </Tooltip> <Tooltip tooltip="If you need help, read the docs!" className="m-r-20"> <Icon name="help" className="color-primary" /> </Tooltip> <Tooltip tooltip="This is a simple tooltip, shown on the right" className="m-r-20" placement="right" > <Button mean="primary-reverse">Right placed</Button> </Tooltip> <Tooltip tooltip="You must click the trigger or the message to close this tooltip!" className="m-r-20" placement="bottom" triggerMode="click" > <Button mean="primary-reverse">Click</Button> </Tooltip> </div> </Story> </Canvas> ## Positioning Popper automatically set coordinates to the overlay element accordingly to the visibility. The following demo allows to see this in action: <Canvas> <Story name="Positioning"> <div style={{ width: '100%', height: 400, overflow: 'auto' }}> <div style={{ width: '200%' }}> <div style={{ display: 'block', height: 160 }}></div> <div style={{ display: 'flex' }}> <div style={{ display: 'block', width: '45%' }}></div> <Tooltip tooltip={ <div className="w-400"> <Lorem paragraphs={1} /> </div> } maxWidth={false} triggerMode="click" > <Button mean="primary">Click me</Button> </Tooltip> <div style={{ display: 'block', width: '45%' }}></div> </div> <div style={{ display: 'block', height: 400 }}></div> </div> </div> </Story> </Canvas> ## Tooltip Props <ArgsTable of={Tooltip} /> <file_sep>/packages/ui/src/components/page/Page.types.ts import { TagType } from '../../utils/sharedTypes'; export interface PageProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** Title passed to `PageHeader` as children */ title?: React.ReactNode; /** Makes the title part of the body scroll (so it will not stick on the top when the page body is scrolled) */ continuousScroll?: boolean; /** Use `PageBody` component. If `false`, will append children after `PageHeader` (if title is passed) */ usePageBody?: boolean; /** Makes the content centered in big screens (> 1300px) */ readableContent?: boolean; /** Class name passed to the container */ className?: string; /** Additional props passed to `PageHeader` */ pageHeaderProps?: PageHeaderProps; /** Additional props passed to `PageBody` */ pageBodyProps?: PageBodyProps; /** See `PageHeader` props */ headerVisibleFollowRef?: React.RefObject<HTMLDivElement>; /** See `PageHeader` props */ headerVisibleFollowOffset?: number; children?: React.ReactNode; } export interface PageHeaderProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** Page controls: will be shown on the right of the header (useful for buttons or icons) */ controls?: React.ReactNode; /** React ref of the body element. It is used to determine if the body element is scrolled, * to apply a shadow to the `PageHeader` container */ scrollRef?: React.RefObject<HTMLDivElement>; /** Center the content if the page is greater than 1300 px */ readableContent?: boolean; /** React ref of a component. If passed, the `PageHeader` will be rendered only if the referenced component * is not visible. */ headerVisibleFollowRef?: React.RefObject<HTMLDivElement>; /** Apply an offset to determine if the header should be visibile or not (higher the offset, higher the scroll offset) */ headerVisibleFollowOffset?: number; /** Tag used for the title */ titleTag?: TagType; /** If true, controls are hidden on small screens and an icon is shown, which will trigger an overlay with controls */ responsiveControls?: boolean; children: React.ReactNode; className?: string; } export interface PageHeaderResponsiveControlsProps { controls: React.ReactNode; responsiveControls: boolean; } export interface PageBodyProps extends React.ComponentPropsWithoutRef<React.ElementType> { /** Props passed to indicate if the component is rendered after a `PageHeader` (to determine offsets) */ withPageHeader?: boolean; /** Center the content if the window is greater than 1300px. */ readableContent?: boolean; /** React ref assigned to `PageBody` container (to be used as `scrollRef` prop of `PageHeader`) */ pageBodyRef?: React.RefObject<HTMLDivElement>; children?: React.ReactNode; className?: string; } <file_sep>/packages/dashboard/src/apps/books/pages/reviews/forms/AddReviewPage.js /** * */ import { useContext, useMemo } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { Page } from '@borrow-ui/ui'; import { storeContext } from 'store'; import { BOOKS_BOOK_BASE_URL } from 'apps/books/constants'; import { reviewsModel } from 'apps/books/models/review'; import { ReviewForm } from 'apps/books/components/reviews/ReviewForm'; export function AddReviewPage() { const navigate = useNavigate(); const { setStore } = useContext(storeContext); const params = useParams(); const isbn13 = params.isbn13; const review = useMemo(() => reviewsModel.newReview(isbn13), [isbn13]); const onSubmit = (newReview) => { return reviewsModel.add(setStore, newReview).then(() => { navigate(`${BOOKS_BOOK_BASE_URL}/${isbn13}`); }); }; const onCancel = () => navigate(`${BOOKS_BOOK_BASE_URL}/${isbn13}`); return ( <Page title="Add new review"> <ReviewForm review={review} onSubmit={onSubmit} onCancel={onCancel} /> </Page> ); } <file_sep>/packages/ui/src/components/forms/constants.ts export const LAYOUTS = { HORIZONTAL: 'horizontal' as const, VERTICAL: 'vertical' as const, DEFAULT: 'vertical' as const, }; export const ALIGNMENTS = { LEFT: 'left' as const, CENTER: 'center' as const, RIGHT: 'right' as const, DEFAULT: 'left' as const, }; export const VALIGNMENTS = { TOP: 'top' as const, MIDDLE: 'middle' as const, BOTTOM: 'bottom' as const, DEFAULT: 'middle' as const, }; <file_sep>/packages/ui/src/components/text/Text.types.ts import { TagType } from '../../utils/sharedTypes'; export interface TextProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; className?: string; size?: 'small' | 'normal' | 'big'; /** Use a different tag than div. */ tag?: TagType; underline?: boolean; } <file_sep>/packages/dashboard/src/apps/books/pages/books/forms/EditBookPage.js /** * Similarly to AddBookPage, this page has the logic to connect * the edit form to the store. * * The book to edit is retrieved from the store and the values * are passed down to BookForm. */ import { useContext } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { Page } from '@borrow-ui/ui'; import { storeContext } from 'store'; import { BOOKS_BOOK_BASE_URL } from 'apps/books/constants'; import { booksModel } from 'apps/books/models/book'; import { BookForm } from 'apps/books/components/books/BookForm'; export function EditBookPage() { const navigate = useNavigate(); const { store, setStore } = useContext(storeContext); const params = useParams(); const isbn13 = params.isbn13; const book = store.books.books[isbn13]; const onSubmit = (changedBook) => { return booksModel.save(setStore, changedBook).then(() => { navigate(`${BOOKS_BOOK_BASE_URL}/${changedBook.isbn13}`); }); }; const onCancel = () => navigate(`${BOOKS_BOOK_BASE_URL}/${isbn13}`); return ( <Page title="Edit book"> <BookForm book={book} onSubmit={onSubmit} onCancel={onCancel} /> </Page> ); } <file_sep>/packages/ui/src/components/forms/field/Field.types.ts import { FieldLabelAlignmentType, FieldLayoutType, FieldVerticalAlignmentType, } from '../constants.types'; interface FieldPropsInterface extends React.ComponentPropsWithoutRef<React.ElementType> { className?: string; label?: React.ReactNode; /** Show a description of field value */ description?: React.ReactNode; children?: React.ReactNode; required?: boolean; /** ID of input element */ htmlFor?: string; /** Label and Field vertical alignment. Default vertical alignment is `'middle'` */ vAlignment?: FieldVerticalAlignmentType; labelWidth?: string | number; /** Label alignment (horizontal). Default alignment is `'left'` */ labelAlignment?: FieldLabelAlignmentType; /** Additional props passed to label container */ labelProps?: React.HTMLAttributes<HTMLLabelElement>; /** Additional props passed to controller container */ controllerProps?: React.HTMLAttributes<HTMLDivElement>; /** Additional props passed to description container */ descriptionProps?: React.HTMLAttributes<HTMLDivElement>; /** Do not render the controller if children is falsy */ compact?: boolean; } export interface FieldProps extends FieldPropsInterface { /** Layout can be `vertical` or `horizontal`. You can change the constants, * as well as `DEFAULT`, to create other types of layout. */ layout?: FieldLayoutType; } export interface HFieldProps extends FieldPropsInterface {} export interface VFieldProps extends FieldPropsInterface {} <file_sep>/packages/ui/src/components/forms/date-picker/DatePicker.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from '../../button/Button'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; import { Field } from '../field/Field'; import { DatePicker } from './DatePicker'; <Meta title="Forms/Components/DatePicker" component={DatePicker} /> # DatePicker `DatePicker` component is a wrapper of [react-day-picker](https://react-day-picker.js.org/) `DayPickerInput` component. You need to install the following dependencies: - `react-day-picker`; - `date-fns`: internal dependency of `react-day-picker`, used to convert the input date to the date object. The initial value of the picker can be set with `initialValue` prop. <Canvas> <Story name="Default"> <FormsStoryWrapper initialState={{ select_date: null, initial_date: '2020-06-22' }}> {({ state, setState }) => { return ( <div style={{ width: 400, height: 400 }}> <Field label="Select a date"> <DatePicker onDayChange={(date) => setState({ ...state, select_date: date, }) } /> </Field> <Field label="Picker with initial date"> <DatePicker initialValue={state.initial_date} onDayChange={(date) => setState({ ...state, initial_date: date, }) } /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> `initialValue` can also be used to reset the date from outside the component: <Canvas> <Story name="Initial Value"> <FormsStoryWrapper initialState={{ select_date: null, initial_date: '2020-06-22' }}> {({ state, setState }) => { return ( <div style={{ width: 400, height: 400 }}> <Field label="Picker with initial date"> <DatePicker initialValue={state.initial_date} onDayChange={(date) => setState({ ...state, initial_date: date, }) } /> </Field> <Button onClick={() => setState({ ...state, initial_date: '2020-10-22' })} mean="accent" > Set to 2020-10-22 </Button> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> The new clicked date is passed to `onDayChange` prop function handler. By default the type of `date` argument is string, but it can be changed to native date with `onDayChangeFormat` parameter, by setting it to `date` (open the console to see the changes). <Canvas> <Story name="onDayChange"> <FormsStoryWrapper initialState={{ select_date: null }}> {({ state, setState }) => { return ( <div style={{ width: 400, height: 350 }}> <Field label="Select a date"> <DatePicker onDayChangeFormat="date" onDayChange={(date) => { console.log( 'DatePicker `onDayChangeFormat`: date changed to', date ); setState({ ...state, select_date: date && date.toISOString ? date.toISOString().substr(0, 10) : date, }); }} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> Having an input means we can have partial values (i.e. `2020-04-`) while we are typing. The `onDayChange` handler is called at every change so we can have partial values back. If we need only valid results, we can set `returnPartial` prop to false. Open the console and see the log: <Canvas> <Story name="returnPartial"> <FormsStoryWrapper initialState={{ select_date: null }}> {({ state, setState }) => { return ( <div style={{ width: 400, height: 350 }}> <Field label="Select a date"> <DatePicker returnPartial={false} onDayChange={(date) => { console.log( 'DatePicker `returnPartial`: date changed to', date ); setState({ ...state, select_date: date, }); }} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ### Disabled and Invalid The input field can be set as both disabled and invalid with `disabled` and `invalid` props: <Canvas> <Story name="Disabled and Invalid"> <FormsStoryWrapper initialState={{ disabled_date: '2020-06-25', invalid_date: '2020-04-01' }} > {({ state, setState }) => { return ( <div style={{ width: 400, height: 400 }}> <Field label="Disabled date"> <DatePicker disabled={true} initialValue={state.disabled_date} onDayChange={(date) => { setState({ ...state, disabled_date: date, }); }} /> </Field> <Field label="Invalid date (pick `2020-04-01`)"> <DatePicker invalid={state.invalid_date === '2020-04-01'} initialValue={state.invalid_date} onDayChange={(date) => { setState({ ...state, invalid_date: date }); }} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Props <ArgsTable of={DatePicker} /> <file_sep>/packages/ui/src/components/forms/label/Label.types.ts import { TagType } from '../../../utils/sharedTypes'; import { FieldLabelAlignmentType, FieldLayoutType, FieldVerticalAlignmentType, } from '../constants.types'; export interface LabelProps extends React.ComponentPropsWithoutRef<React.ElementType> { label: React.ReactNode; required?: boolean; layout?: FieldLayoutType; width?: string | number; tag?: TagType; htmlFor?: string; alignment?: FieldLabelAlignmentType; vAlignment?: FieldVerticalAlignmentType; className?: string; style?: React.CSSProperties; } <file_sep>/packages/ui/src/components/text/Text.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Text } from './Text'; <Meta title="Components/Typography/Text" component={Text} /> # Text `Text` component is used to render readable text in a consistent way. This can be used for posts, long descriptions or the main page content. By default the used tag is `div`, but it can be overriden by using `tag` prop. There are also two other sizes available, that can be specified via `size` prop: `small` and `big`. <Canvas> <Story name="Default"> <h2>Text example</h2> <Text> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis egestas semper leo ac porta. Integer metus urna, lacinia vitae purus et, pharetra auctor purus. Vivamus bibendum id lacus sit amet faucibus. </Text> <Text size="big"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis egestas semper leo ac porta. Integer metus urna, lacinia vitae purus et, pharetra auctor purus. Vivamus bibendum id lacus sit amet faucibus. </Text> <Text size="small"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis egestas semper leo ac porta. Integer metus urna, lacinia vitae purus et, pharetra auctor purus. Vivamus bibendum id lacus sit amet faucibus. </Text> </Story> </Canvas> ## Text Props <ArgsTable of={Text} /> <file_sep>/packages/ui/src/components/badge/Badge.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Badge } from './Badge'; <Meta title="Components/Badge" component={Badge} /> # Badge Badges can be used close to text to emphatize labels or numbers. It is possible to customize the tag (default is `span`) and it's shape. The `color` prop leverages the colors classes. <Canvas> <Story name="Default"> <div> A normal text close to a <Badge>Badge</Badge> </div> </Story> </Canvas> Badges with different colors: <Canvas> <Story name="Colors"> <div> <Badge color="primary">Primary</Badge> <Badge color="accent">Accent</Badge> <Badge color="positive">Positive</Badge> <Badge color="warning">Warning</Badge> <Badge color="negative">Negative</Badge> </div> </Story> </Canvas> Badges with different shape: <Canvas> <Story name="Shapes"> <div> <Badge color="primary">Badge</Badge> <Badge color="accent" type="squared"> Squared </Badge> <Badge color="positive" type="circular"> 10 </Badge> </div> </Story> </Canvas> ## Props <ArgsTable of={Badge} /> --- ## React Tutorial Badge component is one of the simplest components to create. From a JS point of view, it is just a tag with one or more classes: ```jsx import React from 'react'; export function Badge({ className = '', children }) { const badgeClassName = `ui-badge ${className}`.trim(); return ( <span className={badgeClassName}>{children}</span>; ); } ``` It can be further extended with: - a Tag selection (i.e. to use `div` instead of `span`); - a type to determine the shape; - a color to be used as background. The last two will influence the class attribute, while the first will replace the `span`: ```jsx import React from 'react'; export function Badge({ className = '', tag: Tag = 'span', type='rounded', color='neutral', children }) { // Generate the classes // - if color is set, use the color-COLOR-bg and color-on-COLOR classes // defined in the main css colors.scss const colorClass = color ? `color-${color}-bg color-on-${color}` : ''; // - if type is set and is not squared, use the related BEM class const typeClass = type && type !== 'squared' ? `${BADGE_CLASS}--${type}` : ''; const badgeClassName = `badge ${colorClass} ${typeClass} ${className}`.trim(); // Replace the span with the Tag property return ( <Tag className={badgeClassName}>{children}</Tag>; ); } ``` Note the `tag: Tag = 'span'`: this means that the `tag` prop is renamed to `Tag` (so it can be used as JSX compoent) and default to `'span'`. <file_sep>/packages/website-next/content/project/example.mdx --- title: Example --- This page is dynamically loaded based on the slug (URL). The URL of this page shuold be [/project/example](/project/example). <file_sep>/packages/ui/src/components/menu/Menu.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Icon } from '../icon/Icon'; import { Loader } from '../loader/Loader'; import { Monospace } from '../text/Monospace'; import { Menu } from './Menu'; import { MenuDivider } from './MenuDivider'; import { MenuEntry } from './MenuEntry'; <Meta title="Components/Menu" component={Menu} /> # Menu A `Menu` component is available to generate simple Menus. A list of entries can be passed with the `entries` prop. Each entry is an object with the following properties: - `type`: can be either `entry` (rendered with a `MenuEntry` compoent) or `divider` (rendered with a `MenuDivider` component); - `label`: label shown in the menu entry; - `props`: extra properties added to the `MenuEntry` component's label container. <Canvas> <Story name="Default"> <div> <Menu entries={[ { type: 'entry', label: 'Entry 1' }, { type: 'entry', label: 'Disabled Entry', props: { disabled: true } }, { type: 'entry', label: 'Red entry', props: { style: { color: 'red' } } }, { type: 'entry', label: ( <span> <Monospace>onClick</Monospace> specified </span> ), props: { onClick: () => window.alert('clicked') }, }, { type: 'divider' }, { type: 'entry', label: ( <span> <Icon name="home" size="smaller" /> Home </span> ), }, ]} /> </div> </Story> </Canvas> ### Specify entries manually The content (_children_) of `Menu` can also be specified manually without autogeneration. The two components used by the autogeneration can be imported separately and then used directly. <Canvas> <Story name="Entries"> <div> <Menu> <MenuEntry>Entry 1</MenuEntry> <MenuEntry style={{ color: 'red' }}>Red entry</MenuEntry> <MenuDivider /> <MenuEntry> <Loader type="inline" /> Inline loader </MenuEntry> </Menu> </div> </Story> </Canvas> ## Menu Props <ArgsTable of={Menu} /> ## MenuEntry Props <ArgsTable of={MenuEntry} /> <file_sep>/packages/ui/src/components/text/TextContainer.types.ts export interface TextContainerProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; className?: string; /** Applies an auto margin on left and right, to make the container centered on a big screen. */ centered?: boolean; } <file_sep>/packages/website-next/next.config.js module.exports = { reactStrictMode: true, target: 'serverless', env: { STORYBOOK_BASE_URL: process.env.STORYBOOK_BASE_URL, }, }; <file_sep>/packages/ui/src/components/table/Table.stories.mdx import { Fragment } from 'react'; import ReactDOMServer from 'react-dom/server'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from '../button/Button'; import { Table } from './Table'; import { GroupLines } from './TableStory'; <Meta title="Components/Table" component={Table} /> # Table `Table` component can be used to create rich tables. **Note**: documentation to be done. <Canvas> <Story name="Default"> <div className="p-b-20"> <Table columns={[ { prop: 'id', title: 'ID', width: '100px' }, { prop: 'description', title: 'Description' }, { prop: 'controls' }, ]} entries={[ { id: 1, name: 'Entry number one', description: 'This is a description of the entry', controls: ( <Button size="smaller" mean="primary"> Test </Button> ), }, { id: 2, name: 'Entry number two', description: 'This is a description of the entry', controls: ( <Button size="smaller" mean="primary"> Test </Button> ), }, { id: 3, name: 'Entry number thre', description: 'This is a description of the entry', controls: ( <Button size="smaller" mean="primary"> Test </Button> ), }, ]} /> </div> </Story> </Canvas> ### Customize cell properties and appearance Table component can be customized in few ways: - by using table's `config` prop; - by using column definition `verticalAlign` and `align` props; - by using `cellProps` (for cell - td or th) and `cellContentProps` (for the container flex div inside the cell). The priority is the reverse as listed, so `cellProps` will override the column definition, which will override the `config` ones (if they are the same). #### Vertical Alignment To change the vertical alignment of the rows content, set `config.verticalAlign` property. If you need to change one column only, a `verticalAlign` property can be added to the column definition: Vertical Aligment is added to the cell item (`th` or `td`), so it can be changed directly as well with `elementProps.cellProps`. The following example has: - a global vertical alignment set with `config={{ verticalAlign: 'bottom' }}` - a specific vertical alignment set on `name` column with `verticalAlign: 'top'` property on column definition. <Canvas> <Story name="Vertical Alignment"> <div className="p-b-20"> <Table config={{ verticalAlign: 'bottom' }} columns={[ { prop: 'id', title: 'ID', width: '100px' }, { prop: 'name', title: 'Name', verticalAlign: 'top' }, { prop: 'group', title: 'Group' }, ]} entries={[ { id: 1, name: 'first entry', group: <GroupLines />, }, { id: 2, name: 'second entry', group: <GroupLines />, }, { id: 3, name: 'third entry', group: <GroupLines />, }, ]} /> </div> </Story> </Canvas> #### (Horizontal) Alignment In the same way, alignment can be changed by using `config.alignment` or `alignment` property in column definition, with priority to the latter. Aligment is added to the cell content item (`div` inside `th` or `td`), so it can be changed directly as well with `elementProps.cellContentProps`. The `div` has a flex display, so the alignment can be changed by leveraging `justify-content` property. The following example has: - a global horizontal alignment set with `config={{ align: 'center' }}` - a specific horizontal alignment set on `id` column with `align: 'right'` property on column definition; - a specific horizontal alignment set on `name` column with `align: 'left'` property on column definition. <Canvas> <Story name="Alignment"> <div className="p-b-20"> <Table config={{ align: 'center', borderType: 'cell' }} columns={[ { prop: 'id', title: 'ID', width: '100px', align: 'right' }, { prop: 'name', title: 'Name', align: 'left' }, { prop: 'group', title: 'Group' }, ]} entries={[ { id: 1, name: 'first long entry', group: <GroupLines />, }, { id: 2, name: 'second entry', group: <GroupLines />, }, { id: 3, name: 'third very very long entry', group: <GroupLines />, }, ]} /> </div> </Story> </Canvas> ### Controlling props with cellProps and cellContentProps The previous helpers (`align` and `verticalAlign`) are applied to both header and rows. If we want to apply them only to one specific row, or all rows but not headers we can do that by using `cellProps` and `cellContentProps`. Both accepts a `getProps` function as a property which takes two arguments: - `column`: the column object that is rendered; - `entry`: the entry of the row; if it's undefined, it's the header cell. With this method we can also apply an alignment based on content value, i.e. all numbers aligned right. The following example uses `cellContentProps` to align horizontally the numbers on the right only in the cell body. <Canvas> <Story name="Header and rows different alignment"> <div className="p-b-20"> <Table config={{ borderType: 'cell' }} elementsProps={{ cellContentProps: { getProps: (column, entry) => { return { align: entry && typeof entry[column.prop] === 'number' ? 'right' : 'left', }; }, }, }} columns={[ { prop: 'id', title: 'ID', width: '100px' }, { prop: 'name', title: 'Name' }, { prop: 'group', title: 'Group' }, ]} entries={[ { id: 1, name: 'first long entry', group: <GroupLines />, }, { id: 2, name: 'second entry', group: <GroupLines />, }, { id: 3, name: 'third very very long entry', group: <GroupLines />, }, ]} /> </div> </Story> </Canvas> ## Table Props <ArgsTable of={Table} /> <file_sep>/packages/ui/src/components/block/Block.types.ts export interface BlockProps extends React.ComponentPropsWithRef<React.ElementType> { children: React.ReactNode; className?: string; /** Set a title for the block with h2 tag */ title: React.ReactNode; /** Props passed to the title element */ titleProps?: React.HTMLProps<HTMLDivElement>; /** Adds a margin to the block */ separated: boolean; /** Adds padding to the block */ padded: boolean; /** Makes the border rounded */ rounded: boolean; /** Adds a shadow to make block outstanding */ outstanding: boolean; /** Adds a shadow to make block outstanding when mouse is hovered */ outstandingHover: boolean; /** Centers the content */ contentCentered: boolean; /** Set the `ref` prop of the container */ } <file_sep>/packages/website-next/layout/Layout.js import React, { useState } from 'react'; import { SidebarContext, getSidebarContextDefaultState, Responsive } from '@borrow-ui/ui'; import { Header } from './Header'; import { MainSidebar } from './MainSidebar'; import { Footer } from './Footer'; const SIDEBAR_MEDIA_QUERIES = { small: '(max-width: 699px)', medium: '(min-width: 700px) and (max-width: 1199px)', large: '(min-width: 1200px)', }; export function Layout({ Component, pageProps }) { const sidebarState = useState(getSidebarContextDefaultState({ autoCloseLink: true })); return ( <div className="borrow-ui borrow-ui-website"> <SidebarContext.Provider value={sidebarState}> <Responsive queries={SIDEBAR_MEDIA_QUERIES}> {(matches) => <Header isSmallScreen={matches.small} />} </Responsive> <div style={{ display: 'flex' }}> <Responsive queries={SIDEBAR_MEDIA_QUERIES}> {(matches) => <MainSidebar isSmallScreen={matches.small} />} </Responsive> <div className="website__content"> <div className="website__page"> <Component {...pageProps} /> </div> <Footer /> </div> </div> </SidebarContext.Provider> </div> ); } <file_sep>/packages/ui/src/components/navbar/NavbarLink.types.ts import { TagType } from '../../utils/sharedTypes'; export interface NavbarLinkProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; /** Use a different tag from `a`. */ tag?: TagType; } <file_sep>/packages/website-next/content/project/index.mdx --- title: Project index --- You should be able to reach this page by navigating to [/project](/project) URL. The other page under this section is [/project/example](/project/example) which will load the content of `content/project/example.mdx` file. <file_sep>/packages/ui/src/components/forms/checkbox/Checkbox.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; import { Field } from '../field/Field'; import { Checkbox } from './Checkbox'; <Meta title="Forms/Components/Checkbox" component={Checkbox} /> # Checkbox Checkboxes represent a two-statuses controller. In vertical layout fields they are can be associated to a specific label instead of the field's one. <Canvas> <Story name="Default"> <FormsStoryWrapper initialState={{ vertical_label: true, horizontal_label: true }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Checkbox with label on top (vertical)"> <Checkbox checked={state.vertical_label} onClick={() => setState({ ...state, vertical_label: !state.vertical_label, }) } /> </Field> <Field label="Horizontal label" layout="horizontal"> <Checkbox checked={state.horizontal_label} onClick={() => setState({ ...state, horizontal_label: !state.horizontal_label, }) } /> </Field> <Field> <Checkbox label="Checkbox own label" checked={state.own_label} onClick={() => setState({ ...state, own_label: !state.own_label })} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ### Disabled checkbox Checkboxes can be disabled as well: <Canvas> <Story name="Disabled"> <FormsStoryWrapper initialState={{ disabled_label: true }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field> <Checkbox label="This is always checked" checked={state.disabled_label} disabled={true} onClick={() => setState({ ...state, own_label: !state.own_label })} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Props <ArgsTable of={Checkbox} /> <file_sep>/packages/ui/src/components/accordion/Accordion.types.ts export interface IAccordionGroupState { open: React.ReactNode; } export type AccordionContextType = [ IAccordionGroupState | null, React.Dispatch<React.SetStateAction<IAccordionGroupState>> | null ]; export interface AccordionGroupProps { children: React.ReactNode; initialOpenTitle: React.ReactNode; } export interface AccordionProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; className?: string; /** Title of the accordion */ title: React.ReactNode; /** Props passed to the title element */ titleProps?: React.HTMLProps<HTMLDivElement>; /** Props passed to the content container element */ contentProps?: React.HTMLProps<HTMLDivElement>; /** Set the initial open status of the accordion */ initialOpen?: boolean; /** Specify the `maxHeight`. By default CSS adds `600px`. */ maxHeight?: string | number; } <file_sep>/packages/ui/src/components/tile-link/TileLink.types.ts import { IconProps, IconFamilyType } from '../icon/Icon.types'; export interface TileLinkProps { className?: string; /** Used to populate `to` prop of Link component. */ to?: string; /** Used to populate `href` prop of Link component. */ href?: string; /** Icon name. */ icon: string; /** Overrides default icon family. */ iconFamily?: IconFamilyType; /** Name of the Tile. */ name?: React.ReactNode; /** Description of the Tile. */ description?: React.ReactNode; /** Defines how big the Tile is. */ size?: 'small' | 'big'; /** Overrides Icon props. */ iconProps: IconProps; } <file_sep>/packages/website-next/pages/project/index.js import { getStaticProps } from './[slug]'; import Content from './[slug]'; export { getStaticProps }; export default Content; <file_sep>/packages/ui/src/components/syntax-highlight/SyntaxHighlight.types.ts export interface SyntaxHighlightProps { /** Code to highlight */ code?: string; /** List of plugins to load (depends on what has been imported) */ plugins?: Array<string>; /** Language (depends on what has been imported) */ language?: string; /** Properties passed to `pre` element */ preProps?: React.HTMLAttributes<HTMLPreElement>; /** Properties passed to `code` element */ codeProps?: React.HTMLAttributes<any>; className?: string; } <file_sep>/packages/dashboard/src/apps/books/models/review.js /** * See book model for a brief explanation. */ import { getReviews } from '../api/getReviews'; export class ReviewModel { newReview(isbn13) { return { id: null, title: '', isbn13, stars: 0, description: '', completed: false, recommend_to_friends: false, topics: [], started_on: null, }; } getList() { return getReviews(); } add(setStore, review) { return new Promise((resolve) => { // Simulate some delay setTimeout(() => { setStore((store) => { const reviews = { ...store.books.reviews }; // this action is usually done in the database side review.id = Math.max(Object.values(reviews).map((r) => r.id)) + 1; reviews[review.id] = review; return { ...store, books: { ...store.books, reviews } }; }); resolve(); }, 1000); }); } save(setStore, review) { return new Promise((resolve) => { // Simulate some delay setTimeout(() => { setStore((store) => { const reviews = { ...store.books.reviews }; reviews[review.id] = review; return { ...store, books: { ...store.books, reviews } }; }); resolve(); }, 1000); }); } delete(setStore, id) { return new Promise((resolve) => { // Simulate some delay setTimeout(() => { setStore((store) => { const reviews = { ...store.books.reviews }; delete reviews[id]; return { ...store, books: { ...store.books, reviews } }; }); resolve(); }, 1000); }); } } export const reviewsModel = new ReviewModel(); <file_sep>/packages/ui/src/components/forms/Forms.stories.mdx import { Meta, Story, Canvas } from '@storybook/addon-docs'; import { Checkbox } from './checkbox/Checkbox'; import { DatePicker } from './date-picker/DatePicker'; import { Dropzone } from './dropzone/Dropzone'; import { Field } from './field/Field'; import { Input } from './input/Input'; import { Textarea } from './textarea/Textarea'; import { Toggle } from './toggle/Toggle'; import { Forms } from './index'; import { FormsStoryWrapper } from './FormsStoryWrapper'; <Meta title="Forms/Introduction" /> # Forms Forms can be created by a combination of inputs/controllers. The standard way to represent form elements is by using a label-controller couple. This couple is represented by a "form field" and can be rendered by using `Field` component. ```jsx import { Button, Forms } from '@borrow-ui/ui'; const { Field, Input } = Forms; export function Form({ initialValues, onSubmit }) { const [values, setValues] = useState(initialValues); const onFormSubmit = (e) => { e.preventDefault(); onSubmit({ values }); }; return ( <form onSubmit={onFormSubmit}> <Field label="<NAME>"> <Input placeholder="Insert your name..." value={values.name} onChange={(e) => setValues({ ...values, name: e.target.value })} /> </Field> <div> <Button type="submit" mean="positive"> Save </Button> </div> </form> ); } ``` Each controller can be used as `children` of `Field` component. The next example shows all the available controllers. For a detailed documentation of components, see the respective pages. <Playground> <FormsStoryWrapper initialState={{ useInternet: true }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="<NAME>"> <Input placeholder="Insert your name..." /> </Field> <Field label="Bio"> <Textarea placeholder="Tell me something about you..." /> </Field> <Field label="Pick a day of the year"> <DatePicker value={state.favouriteDay} onChange={(date) => setState({ ...state, favouriteDay: date })} /> </Field> <Field label="Favourite day of weekend"> <Forms.Select value={state.favouriteWeekendDay} onChange={(option) => setState({ ...state, favouriteWeekendDay: option.value }) } options={[ { value: 'friday', label: 'Friday' }, { value: 'saturday', label: 'Saturday' }, { value: 'sunday', label: 'Sunday' }, ]} /> </Field> <Field label="I have the following devices:"> <div className="m-t-5"> <div className="m-b-10"> <Checkbox label="Smartphone/Tablet" checked={state.smartphone} onClick={(e) => setState({ ...state, smartphone: !state.smartphone, }) } /> </div> <div className="m-b-10"> <Checkbox label="Laptop" checked={state.laptop} onClick={(e) => setState({ ...state, laptop: !state.laptop })} /> </div> <div className="m-b-10"> <Checkbox label="Desktop" checked={state.desktop} onClick={(e) => setState({ ...state, desktop: !state.desktop })} /> </div> </div> </Field> <Field label="I use internet"> <Toggle checked={state.useInternet} onClick={(e) => setState({ ...state, useInternet: !state.useInternet })} /> </Field> <Field> <Dropzone dragMessage="Upload your desktop wallpaper" /> </Field> </div> ); }} </FormsStoryWrapper> </Playground> <file_sep>/packages/ui/src/components/navbar-menu/NavbarMenu.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Row, Col } from '../grid/Grid'; import { Lorem } from '../lorem/Lorem'; import { Text } from '../text/Text'; import { NavbarMenu } from './NavbarMenu'; import { NavbarMenuItem } from './NavbarMenuItem'; import { NavbarMenuTitle } from './NavbarMenuTitle'; <Meta title="Components/NavbarMenu" component={NavbarMenu} /> # NavbarMenu The `NavbarMenu` component is the ideal way to create menus inside `Navbar`s. Two components are used underneath: `NavbarMenuTitle` and `NavbarMenuItem`. `NavbarMenu` takes a list of entry objects (`entries` prop) whose properties are valid `MenuItem` props. An optional `title` prop will be rendered by using `NavbarTitle` component. <Canvas> <Story name="Default"> <div style={{ fontSize: '14px' }}> <Row> <Col> <NavbarMenu title="Menu on the left" entries={[ { label: 'Entry 1' }, { label: 'Second entry', description: 'This also has a description, helpful to get more context', }, { label: 'Second Third one' }, ]} /> </Col> <Col> <NavbarMenu title="Menu on the right" entries={[ { label: 'Clickable one', description: 'Hover to see the cursor, click to view the alert', style: { cursor: 'pointer' }, onClick: () => window.alert('Entry clicked'), }, { label: <span>Custom element as label</span>, description: 'This also has a description, helpful to get more context', }, { label: 'Custom element as description', description: ( <div style={{ color: 'green' }}>A green description</div> ), }, ]} /> </Col> </Row> </div> </Story> </Canvas> ## NavbarMenu Props <ArgsTable of={NavbarMenu} /> ## NavbarMenuTitle Props <ArgsTable of={NavbarMenuTitle} /> ## NavbarMenuItem Props <ArgsTable of={NavbarMenuItem} /> <file_sep>/packages/dashboard/src/store.js /** * Initialize the dashboard store. */ import { createContext, useState } from 'react'; import PropTypes from 'prop-types'; import { initializeBookStore } from 'apps/books/store'; export const storeContext = createContext(); export function StoreProvider({ children }) { const [store, setStore] = useState({ applicationLoaded: false, user: { id: 1, username: 'username', first_name: 'User', last_name: 'Surname', }, }); return <storeContext.Provider value={{ store, setStore }}>{children}</storeContext.Provider>; } StoreProvider.propTypes = { children: PropTypes.node, }; export async function initializeStore(store, setStore) { return Promise.all([initializeBookStore(store, setStore)]); } <file_sep>/packages/ui/src/components/forms/textarea/Textarea.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; import { Field } from '../field/Field'; import { Textarea } from './Textarea'; <Meta title="Forms/Components/Textarea" component={Textarea} /> # Textarea `Textarea` component is used to input potentially long texts. <Canvas> <Story name="Default"> <FormsStoryWrapper initialState={{ text: '' }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Describe the book you are currently reading"> <Textarea value={state.text} onChange={(e) => setState({ text: e.target.value })} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> Textarea also supports invalid and disabled statuses via `invalid` and `disabled` props. <Canvas> <Story name="Invalid and Disabled"> <FormsStoryWrapper initialState={{ disabled: 'This text cannot be changed', invalid: 'invalid' }} > {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="This textarea should be disabled"> <Textarea value={state.disabled} disabled={true} onChange={(e) => setState({ ...state, disabled: e.target.value })} /> </Field> <Field label="Type `invalid` to see invalid style"> <Textarea value={state.invalid} invalid={state.invalid === 'invalid'} onChange={(e) => setState({ ...state, invalid: e.target.value })} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Props <ArgsTable of={Textarea} /> <file_sep>/packages/ui/src/utils/a11y.ts import { MouseEventHandler, KeyboardEventHandler } from 'react'; import { KEY_CODES } from './constants'; interface IA11yClickableElement { onClick: MouseEventHandler<HTMLElement>; onKeyDown?: KeyboardEventHandler<HTMLElement>; role?: string; tabIndex?: number; } export function a11yClickableElement({ onClick, onKeyDown, role = 'button', tabIndex = 0, }: IA11yClickableElement) { return { role, onClick, onKeyDown: onKeyDown ? onKeyDown : (event: any) => { // TODO: determine correct type if (event.key === KEY_CODES.ENTER) { event.preventDefault(); onClick(event); } }, tabIndex, }; } <file_sep>/packages/dashboard/src/apps/books/constants.js /** * Defines constants used in pages and components. * * Base urls are built by extension of the app base url, * and breadcrumbs too. */ export const BOOKS_BASE_URL = '/books'; export const BOOKS_BREADCRUMBS = [ { link: '/', label: 'Home' }, { link: BOOKS_BASE_URL, label: 'Books' }, ]; export const TOPICS = ['react', 'es6', 'django', 'python', 'front-end', 'back-end']; /* BOOKS */ export const BOOKS_BOOK_BASE_URL = `${BOOKS_BASE_URL}/book`; /* REVIEWS */ export const BOOKS_REVIEW_BASE_URL = `${BOOKS_BASE_URL}/review`; <file_sep>/packages/ui/src/components/lorem/Lorem.types.ts export type LoaderType = 'triangle' | 'line' | 'inline'; export interface LoremProps { /** Number of paragraphs, from 1 to 3. */ paragraphs?: 1 | 2 | 3; } <file_sep>/packages/ui/src/components/forms/input/Input.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; import { Field } from '../field/Field'; import { Input } from './Input'; <Meta title="Forms/Components/Input" component={Input} /> # Input Inputs are the most common forms controller. `Input` component creates inputs controller with a consistent style. <Canvas> <Story name="Default"> <FormsStoryWrapper initialState={{ full_name: '' }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="<NAME>"> <Input placeholder="Insert your name..." value={state.full_name} onChange={(e) => setState({ ...state, full_name: e.target.value })} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> The `Input` component has custom classes for `disabled` and `invalid` statuses: <Canvas> <Story name="Disabled and Invalid"> <FormsStoryWrapper initialState={{ invalid_field: 'invalid' }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Disabled cannot be changed"> <Input value="Fixed string" disabled={true} /> </Field> <Field label="Invalid style"> <Input placeholder="Type 'invalid' to see the invalid style" value={state.invalid_field} invalid={state.invalid_field === 'invalid'} onChange={(e) => setState({ ...state, invalid_field: e.target.value }) } /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Props <ArgsTable of={Input} /> <file_sep>/packages/ui/src/components/tile-link/TileLink.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { TileLink } from './TileLink'; <Meta title="Components/TileLink" component={TileLink} /> # TileLink `TileLink` component can be used to create home page or section menus. It uses the `Tile`, `Link` and `Icon` components to generate a clickable Tile. The `TileLink` component accepts three main props: - `icon`: the icon visualized in the tile; - `name`: the name of the Tile (larger text); - `description`: the description of the Tile (smaller text). It also accepts a `size` prop, which can be `small` or `large` (default to small). <Canvas> <Story name="Default"> <div> <div> <TileLink icon="computer" name="Local" description="Files on this device" size="big" /> <TileLink icon="cloud" name="Cloud" description="Your shared data" size="big" /> </div> <div> <TileLink icon="event" name="Today" description="What happens today" /> <TileLink icon="group" name="Groups" description="Manage available user groups" /> <TileLink icon="person" name="Your Profile" description="Change your profile data" /> </div> </div> </Story> </Canvas> ## TileLink Props <ArgsTable of={TileLink} /> <file_sep>/packages/ui/src/components/navbar/Navbar.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Row, Col } from '../grid/Grid'; import { Lorem } from '../lorem/Lorem'; import { Text } from '../text/Text'; import { NavbarMenu } from '../navbar-menu/NavbarMenu'; import { Navbar } from './Navbar'; import { Element, BodyItem } from './Navbar.stories'; <Meta title="Components/Navbar" component={Navbar} /> # Navbar The `Navbar` components can be used to create navigation bars. Generally the navbar created with the `Navbar` component is the main website container for menus and application header. The navbar elements can be positioned on the left, center and right: the content is expected to be a list of navbar elements. Each navbar element can be: - a node, rendered "as is" without wrapper: - a string, rendered "as is" inside a span with appropriate class; - an object, rendered inside a span with approrpiare class. In case the element is an object, it can have the following properties: - `headerLabel`: label that will be shown in the navbar (a valid node can be used); - `bodyItem`: function that generates content for a "mega-menu" that will be shown/hidden when the element is clicked; - `showQueryInput`: show a query input, mainly used to filter the elements inside: a `query` prop is passed to the `bodyItem`; - `floatingControls`: add a `float` class to the "mega-menu" control icons; - `hideControls`: hides the control icons. The available control icons are: - `close`: display an X to close the menu. <Canvas> <Story name="Default"> <div style={{ height: 400, fontSize: '14px', position: 'relative', border: '1px solid #f5f7fa', }} > <Navbar sticky={false} left={[ 'String item', <span style={{ color: 'green' }} className="flex-center-center"> Node item </span>, ]} center={[ { headerLabel: 'Item with menu', bodyItem: () => ( <Block> <Lorem /> </Block> ), }, { headerLabel: 'Item with query', bodyItem: function ({ query }) { return ( <Block> <Text> Type in the query input to filter the elements below. </Text> <Text className="color-neutral"> Only the labels will be filtered, but the function is implemented by you so you can include also the descriptions. </Text> <Row style={{ marginTop: 20 }}> <Col> <NavbarMenu title="Menu on the left" entries={[ { label: 'Entry 1' }, { label: 'Second entry', description: 'This also has a description, helpful to get more context', }, { label: 'Second Third one' }, ].filter( (e) => !query || e.label.toLowerCase().indexOf(query) >= 0 )} /> </Col> <Col> <NavbarMenu title="Menu on the right" entries={[ { label: 'Another menu' }, { label: 'This one is on the right' }, { label: 'Or below if the page is short' }, ].filter( (e) => !query || e.label.toLowerCase().indexOf(query) >= 0 )} /> </Col> </Row> </Block> ); }, showQueryInput: true, }, ]} right={['v 0.0.1']} /> </div> </Story> </Canvas> ## Floating and hidden controls If you need to use the full space of the item body and keep the controls, you probably wont see the space reserved for header. To use the full space you can make the controls "floating" on the top-right corner. To do this, set `floatingControls` property to `true`. The `hideControls` property hides them entirely: <Canvas> <Story name="Floating Controls"> <div style={{ height: 400, fontSize: '14px', position: 'relative', border: '1px solid #f5f7fa', }} > <Navbar sticky={false} center={[ { headerLabel: 'Item without floating controls', bodyItem: function ({ query }) { return ( <div style={{ backgroundColor: '#CCCCCC', border: '1px solid #999999', }} > <Lorem /> </div> ); }, floatingControls: false, }, { headerLabel: 'Item with floating controls', bodyItem: () => ( <div style={{ backgroundColor: '#CCCCCC', border: '1px solid #999999' }} > <Lorem /> </div> ), floatingControls: true, }, { headerLabel: 'Item without controls', bodyItem: function ({ query }) { return ( <div style={{ backgroundColor: '#CCCCCC', border: '1px solid #999999', }} > <Lorem /> </div> ); }, hideControls: true, }, ]} /> </div> </Story> </Canvas> ## Props <ArgsTable of={Navbar} /> ## Element Props An element can be a `string`, a valid `node` or an object with the following properties: <ArgsTable of={Element} /> ## Body Item Props The component used in the `bodyItem` prop of the elements accepts the following properties: <ArgsTable of={BodyItem} /> <file_sep>/README.md # borrow-ui <p align="center" style="padding: 10px; background-color: white; margin-right: auto; margin-left: auto; width: 220px; margin-bottom: 10px;"> <img src="./assets/images/logo-color-192.png" height="192"/> </p> <br /> <p align="center"> A simple component library made with React. </p> <p align="center"> Visit <a href="https://www.borrow-ui.dev/">borrow-ui website</a> to see a preview of components styles and to get started! </p> <br /> <p align="center"> <a href="https://coveralls.io/github/borrow-ui/borrow-ui"> <img src="https://coveralls.io/repos/github/borrow-ui/borrow-ui/badge.svg" alt="Coverage Status" /> </a> <a href="https://app.travis-ci.com/github/borrow-ui/borrow-ui"> <img src="https://app.travis-ci.com/borrow-ui/borrow-ui.svg?branch=master" alt="Build" /> </a> <a href="https://badge.fury.io/js/@borrow-ui%2Fui"> <img src="https://badge.fury.io/js/@borrow-ui%2Fui.svg" alt="Netlify Status" /> </a> </p> <br /> <br /> <div align="center"> <table> <tr> <td> <a href="https://docs.borrow-ui.dev/">Storybook</a> </td> <td> <img src="https://api.netlify.com/api/v1/badges/b8ed96f0-009b-4325-a5a2-a1026b2b4fc8/deploy-status" alt="Netlify Status" /> </td> </tr> <tr> <td> <a href="https://dashboard.borrow-ui.dev/">Dashboard demo</a> </td> <td> <img src="https://api.netlify.com/api/v1/badges/5b80574a-c68a-4616-b599-9610ae3c7fa9/deploy-status" alt="Netlify Status" /> </td> </tr> <tr> <td> <a href="https://next.borrow-ui.dev/">Website Next.js demo</a> </td> <td> <img src="https://api.netlify.com/api/v1/badges/4f38958f-a89c-40dc-bf1e-863251a1689a/deploy-status" alt="Netlify Status" /> </td> </tr> </table> </div> <br /> # borrow-ui project Welcome to borrow-ui repository! borrow-ui is a simple React component library, which you can extend and/or use as a starting project. You can navigate the [presentation site](https://www.borrow-ui.dev/) or the [dashboard example](https://dashboard.borrow-ui.dev/). You can find the [Storybook documentation here](https://docs.borrow-ui.dev/). This repository uses [`yarn 3`](https://yarnpkg.com/) to organize the code in different packages. The following packages are available: - `ui`: the main package, contains the componenty library. It uses `sass` as a CSS preprocessor, `rollup` to build the code and `jest` and `@testing-library/react` for the tests; - `documentation`: source code of the documentation, based on `storybook`; - `dashboard`: source code of the dashboard demonstration, based on CRA; - `website-next`: source code of a static website based on Next.js. ## Why this project? borrow-ui has been started as a container for simple components that can be used as a base for MVPs, prototype sites and dashboards. During time, few projects based on the core components grew diverging from each other, so the idea of having a starting point based on common components bootstrapped this project. Often, when we work on (React) websites, we need very custom functionalities that can't be achieved with common components libraries: we need more props to be passed, having consistent styles for the custom components, passing refs to others or simply understand how a component work to replicate the same functionality on another. borrow-ui is a set of components which are: - consistents in styles and code; - small enough to be understood by anyone with minimal React experience; - easy to extend; - tested and documented. ## Quick start To get started with borrow-ui, understand how the project is structured and see an explanation of the development workflow, have a look at the [Getting Started](https://www.borrow-ui.dev/getting-started/getting-started) and [Workflow](https://www.borrow-ui.dev/workflow) pages on the project website. If you are in a rush, you can use the following commands: ```bash curl -LJO https://github.com/borrow-ui/borrow-ui/archive/master.zip; unzip borrow-ui-master.zip && mv borrow-ui-master my-ui-name; cd my-ui-name; find . -type f -print0 | xargs -0 sed -i 's/borrow-ui/my-ui-name/g'; yarn yarn workspace @my-ui-name/documentation run storybook ``` Ready to go! This will start Storybook development server with hot-reload. Other commands: - `yarn ui:dev`: develop the UI library with watch mode; - `yarn ui:test`: run UI unit tests (you can add `--watchAll` to start watch mode); - `yarn ui:build`: build production version of UI package; For the full list of commands, see the main `package.json` file and the single packages. ## Roadmap A user friendly roadmap is available in [the website](https://www.borrow-ui.dev/roadmap), however issues and milestones can be also seen in this repository Issues section. A focus will be given to tutorials and documentation, as they are part of the main goal of this project. ## Contribute Contribution are welcome! Any ideas, bug reports, improvements can be suggested/reported in the Issues page of this repository. <file_sep>/packages/ui/src/components/text/Title.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Lorem } from '../lorem/Lorem'; import { Title } from './Title'; <Meta title="Components/Typography/Title" component={Title} /> # Title `Title` component is used to create titles in a consistent way. By default, `h1` tag is used, but can be overridden by specifying `tag` prop. <Canvas> <Story name="Default"> <Title>Title example</Title> <Lorem /> <Title tag="h2">Title example</Title> <Title tag="h3">Title example</Title> <Title tag="h4">Title example</Title> <Title tag="h5">Title example</Title> <Title tag="h6">Title example</Title> </Story> </Canvas> Title can be also used as anchor. An `a` wrapper tag is used if `anchor` prop (anchor's name) is passed. The anchor class can be customized with `anchorClassName` prop. <Canvas> <Story name="Anchor"> <Title anchor="title-1">Anchor title</Title> <Lorem /> <Title anchor="title-2" anchorClassName="color-primary"> Anchor title with custom class </Title> <Lorem /> </Story> </Canvas> ## Title Props <ArgsTable of={Title} /> <file_sep>/packages/dashboard/src/apps/books/components/books/DeleteBookButton.js /** * The delete button opens a modal for confirmation. * * The modal can not be closed while book is being deleted. * * As other forms in this demo, there is no need for a * catch in the promise action. */ import { useState } from 'react'; import PropTypes from 'prop-types'; import { Button, Modal, Loader } from '@borrow-ui/ui'; export function DeleteBookButton({ book, deleteBook, onDelete, buttonProps = {} }) { const [loading, setLoading] = useState(false); const deleteBookFn = (isbn13) => { setLoading(true); return deleteBook(isbn13).then(() => { setLoading(false); }); }; return ( <Modal Trigger={({ setVisible }) => ( <Button mean="negative" onClick={() => setVisible(true)} {...buttonProps}> Delete </Button> )} getModalWindowProps={({ setVisible }) => ({ title: 'Delete book', content: `Are you sure to delete "${book.title}" book?`, footer: ( <> <span /> <div> <Button mean="negative" className="m-r-5" onClick={async () => { await deleteBookFn(book.isbn13); setVisible(false); onDelete && onDelete(); }} disabled={loading} flat={true} > {loading ? <Loader type="inline" /> : 'Delete'} </Button> <Button onClick={() => setVisible(false)} disabled={loading}> Cancel </Button> </div> </> ), showCloseIcon: !loading, closeOnEscape: !loading, canMaximize: false, startHeight: 200, startWidth: 400, })} /> ); } DeleteBookButton.propTypes = { /** Book to be deleted */ book: PropTypes.object.isRequired, /** Function to call when Delete confirmation button is pressed */ deleteBook: PropTypes.func.isRequired, /** Function to call when a book has been deleted */ onDelete: PropTypes.func, /** Forward props to the button for overrides */ buttonProps: PropTypes.object, }; <file_sep>/packages/ui/src/components/grid/Grid.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Row, Col } from './Grid'; <Meta title="Components/Grid" component={Row} /> # Grid `borrow-ui` uses [`flexboxgrid2`](https://evgenyrodionov.github.io/flexboxgrid2/) to organize spaces with rows and columns. `flexboxgrid2` is based on `flex` property and offers a responsive grid based on classes. The `Row` component represents the `row` class, while the `Col` component represents the column classes. The `Col` component has two properties to customize classes. By default the size of a column is half row if the window size is greater than `medium` and full row below `medium` size. This can be changed with the `colClassName` property. The standard `className` value will be added: in this way it is possible to add custom classes without the need to repeat the size classes or to put two of them with contradictory values. <Canvas> <Story name="Default"> <div> <Row className="m-b-20"> <Col style={{ backgroundColor: '#EEE' }}> <span className="p-10 display-inline-block">First Column</span> </Col> <Col style={{ backgroundColor: '#E2E2E2' }}> <span className="p-10 display-inline-block">Second Column</span> </Col> </Row> <Row> <Col colClassName="col-xs-12 col-sm-3" style={{ backgroundColor: '#EEE' }}> <div> <span className="p-10 display-inline-block">First</span> </div> </Col> <Col colClassName="col-xs-12 col-sm-3" style={{ backgroundColor: '#E2E2E2' }}> <span className="p-10 display-inline-block">Second</span> </Col> <Col colClassName="col-xs-12 col-sm-3" style={{ backgroundColor: '#EEE' }}> <span className="p-10 display-inline-block">Third</span> </Col> <Col colClassName="col-xs-12 col-sm-3" style={{ backgroundColor: '#E2E2E2' }}> <span className="p-10 display-inline-block">Fourth</span> </Col> </Row> </div> </Story> </Canvas> ## Row Props <ArgsTable of={Row} /> ## Col Props <ArgsTable of={Col} /> <file_sep>/packages/ui/src/components/forms/dropzone/Dropzone.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { FormsStoryWrapper } from '../FormsStoryWrapper'; import { Field } from '../field/Field'; import { Dropzone } from './Dropzone'; import { DropzoneFile } from './DropzoneFiles'; <Meta title="Forms/Components/Dropzone" component={Dropzone} /> # Dropzone Dropzone component is a wrapper around `react-dropzone` library. It allows to create an upload area which works with both Drag and Drop or classic "click here" browser. <Canvas> <Story name="Default"> <FormsStoryWrapper initialState={{ full_name: '' }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Documents"> <Dropzone initialFiles={[ { name: 'First file.pdf' }, { name: 'My profile picture.jpg' }, ]} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Customizing messages The Drop area message can be customized with `dragMessage`. <Canvas> <Story name="Custom Messages"> <FormsStoryWrapper initialState={{ full_name: '' }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Documents"> <Dropzone dragMessage="Drag the files here and they will be added below" initialFiles={[ { name: 'First file.pdf' }, { name: 'My profile picture.jpg' }, ]} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> `dragMessage` controls the base message for both active and inactive status. If you need to customize each separately, you can set `dragActiveMessage` and `dragInactiveActiveMessage`: <Canvas> <Story name="Specific Messages"> <FormsStoryWrapper initialState={{ full_name: '' }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Documents"> <Dropzone dragActiveMessage="Drop the file!" dragInactiveMessage="Drag a file in this zone here" initialFiles={[ { name: 'First file.pdf' }, { name: 'My profile picture.jpg' }, ]} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Maximum number of files By default, there is no limit on the number of files that can be uploaded. Sometimes however we need to specify a maximum number, i.e. when we need a single attachment. This can be done with `maxFiles` property: <Canvas> <Story name="Max Files"> <FormsStoryWrapper initialState={{ full_name: '' }}> {({ state, setState }) => { return ( <div style={{ width: 400 }}> <Field label="Documents"> <Dropzone maxFiles={1} initialFiles={[{ name: 'First file.pdf' }]} /> </Field> </div> ); }} </FormsStoryWrapper> </Story> </Canvas> ## Dropzone Props <ArgsTable of={Dropzone} /> ## DropzoneFile Props <ArgsTable of={DropzoneFile} /> <file_sep>/packages/ui/src/components/navbar-menu/NavbarMenu.types.ts import { TagType } from '../../utils/sharedTypes'; export type NavbarMenuItemProps = { label: React.ReactNode; description?: React.ReactNode; className?: string; tag?: TagType; labelProps?: React.HTMLProps<HTMLDivElement>; descriptionProps?: React.HTMLProps<HTMLDivElement>; }; export interface NavbarMenuProps extends React.ComponentPropsWithRef<React.ElementType> { title?: React.ReactNode; /** A list of entries whose props are valid `NavbarMenuItem` props. */ entries: Array<NavbarMenuItemProps>; className?: string; /** Properties passed to `NavbarMenuTitle` component. */ titleProps?: React.HTMLProps<HTMLDivElement>; } export interface NavbarMenuTitleProps extends React.ComponentPropsWithRef<React.ElementType> { children?: React.ReactNode; className?: string; } <file_sep>/packages/website-next/content/blog/another-post.mdx --- title: Another Post isPublished: true postDate: '2021-09-01' author: borrow-ui description: Another blog post, with one component --- This is another blog post loaded from an mdx file. As well as the other posts, we can use our component library! <Tabs tabs={[ { label: 'First tab', content: `This is JSX content, not MDX` }, { label: 'Second tab', content: `Again, not an MDX content here` }, ]} /> <div className="m-t-20"> This content is in JSX inside a div, and we can use other components too, link a{' '} <Button mean="neutral-reverse" onClick={() => alert('clicked')}> Button </Button> </div> <file_sep>/packages/ui/src/components/menu/Menu.types.ts interface EntryMenu { type: 'entry'; label: React.ReactNode; props?: React.HTMLAttributes<HTMLDivElement>; } interface EntryDivider { type: 'divider'; } export type EntryMenuType = EntryMenu | EntryDivider; export interface MenuProps extends React.ComponentPropsWithoutRef<React.ElementType> { children?: React.ReactNode; className?: string; entries?: Array<EntryMenuType>; } export interface MenuEntryProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; className?: string; disabled?: boolean; onClick?: React.MouseEventHandler; } <file_sep>/packages/ui/src/components/responsive/Responsive.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Lorem } from '../lorem/Lorem'; import { Responsive } from './Responsive'; <Meta title="Components/Responsive" component={Responsive} /> # Responsive `Responsive` is a wrapper around `Media` component from [`react-media`](https://github.com/ReactTraining/react-media). If the CSS media query changes, the `matches` prop is updated accordingly. The wrapper has been created in order to provide default queries, that can be changed in `Responsive` component file. The following text will have different class applied based on size: - "small" query: `color-accent`; - "medium" query: `color-primary`; - "large" query: no class. Default queries constant is defined as follows, and can be customized with `queries` prop: ```jsx const DEFAULT_QUERIES = { small: '(max-width: 599px)', medium: '(min-width: 600px) and (max-width: 1199px)', large: '(min-width: 1200px)', }; ``` <Canvas> <Story name="Default"> <Responsive> {(matches) => ( <div className={ matches.small ? 'color-accent' : matches.medium ? 'color-primary' : '' } > <Lorem /> </div> )} </Responsive> </Story> </Canvas> ## Responsive Props For the difference between `queries` and `query`, [read here](https://github.com/ReactTraining/react-media#query-vs-queries). <ArgsTable of={Responsive} /> <file_sep>/packages/ui/src/components/sidebar-menu/SidebarMenu.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Lorem } from '../lorem/Lorem'; import { SidebarMenu, SidebarMenuTitle, SidebarMenuEntry } from './SidebarMenu'; <Meta title="Components/SidebarMenu" component={SidebarMenu} /> # SidebarMenu `SidebarMenu` component is used to create vertical menus inside sidebars. It exposes three sub-components, `Title`, `Entry` and `Divider`. Entry can be set active via `isActive` prop. <Canvas> <Story name="Default"> <div style={{ display: 'flex', width: '100%' }}> <div style={{ minWidth: 300, height: '100%' }}> <SidebarMenu padded={true}> <SidebarMenu.Title>Section Title 1</SidebarMenu.Title> <SidebarMenu.Entry isActive={true}>Active entry</SidebarMenu.Entry> <SidebarMenu.Entry>Entry 2</SidebarMenu.Entry> <SidebarMenu.Entry>Entry 3</SidebarMenu.Entry> <SidebarMenu.Separator /> <SidebarMenu.Title>Section Title 2</SidebarMenu.Title> <SidebarMenu.Entry>Entry 4</SidebarMenu.Entry> <SidebarMenu.Title>Section Title 3</SidebarMenu.Title> <SidebarMenu.Entry>Entry 5</SidebarMenu.Entry> <SidebarMenu.Entry>Entry 6</SidebarMenu.Entry> </SidebarMenu> </div> <div className="p-l-20 p-r-20 p-b-20"> <h2 className="m-t-10">With a Sidebar Menu</h2> <Block className="overflow-auto h-400"> <Lorem /> </Block> </div> </div> </Story> </Canvas> ## SidebarMenu Props <ArgsTable of={SidebarMenu} /> ## SidebarMenu.Title Props <ArgsTable of={SidebarMenuTitle} /> ## SidebarMenu.Entry Props <ArgsTable of={SidebarMenuEntry} /> <file_sep>/packages/ui/src/components/button/Button.types.ts import { SIZES } from '../../config'; import { TagType } from '../../utils/sharedTypes'; import { IconProps } from '../icon/Icon.types'; type MEANS_NORMAL = | 'primary' | 'secondary' | 'positive' | 'negative' | 'warning' | 'accent' | 'neutral' | 'neutral-dark'; type MEANS_REVERSE = `${MEANS_NORMAL}-reverse`; type ButtonMeans = MEANS_NORMAL | MEANS_REVERSE; export const BUTTON_MODIFIERS = ['shadowed', 'separated', 'icon', ...SIZES] as const; export type ButtonModifiers = typeof BUTTON_MODIFIERS[number]; export interface ButtonProps extends React.ComponentPropsWithoutRef<React.ElementType> { className?: string; /** Disable the button. */ disabled?: boolean; /** Defines the mean of the button. */ mean?: ButtonMeans; /** Controls the size of the button. */ size?: typeof SIZES[number]; /** Removes the shadow to make the button looks flat. */ flat?: boolean; /** Adds a margin. */ separated?: boolean; /** Reserved prop, can override behaviour of the other flags. */ modifiers?: ButtonModifiers[]; /** Icon to be rendered. */ icon?: string; /** Props for the icon Component. */ iconProps?: IconProps; /** Use a different tag from `button`. */ tag?: TagType; children?: React.ReactNode; } <file_sep>/packages/ui/src/components/text/Monospace.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Monospace } from './Monospace'; <Meta title="Components/Typography/Monospace" component={Monospace} /> # Monospace `Monospace` component can be used to render monospace text. <Canvas> <Story name="Default"> This line contains <Monospace>monospaced text</Monospace> wrapped in normal text. </Story> </Canvas> ## Monospace Props <ArgsTable of={Monospace} /> <file_sep>/packages/ui/src/components/forms/constants.types.ts type FieldVerticalLayout = 'vertical'; type FieldHorizontalLayout = 'horizontal'; export type FieldLayoutType = FieldVerticalLayout | FieldHorizontalLayout; export type FieldVerticalAlignmentType = 'top' | 'middle' | 'bottom'; export type FieldLabelAlignmentType = 'left' | 'center' | 'right'; <file_sep>/packages/website-next/pages/index.js import Head from 'next/head'; import { Home } from '../components/home/Home'; export default function Main() { return ( <> <Head> <title>borrow-ui</title> <meta name="description" content="A component library starter kit" /> <link rel="icon" href="/favicon.ico" /> </Head> <Home /> </> ); } <file_sep>/packages/ui/src/components/tile/Tile.stories.mdx import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Block } from '../block/Block'; import { Icon } from '../icon/Icon'; import { Tile } from './Tile'; import './tile-story.scss'; <Meta title="Components/Tile" component={Tile} /> # Tile A tile is a container with two parts: content and description. Tile's content is passed as `children`, and the description is specified with the `description` prop. <Canvas> <Story name="Default"> <div className="storybook-container"> <div style={{ display: 'flex', width: '100%' }}> <Tile description="A tile description"> <Icon name="home" size="huge" /> </Tile> <Tile description="A tile with predefined background" withBackground={true}> <Icon name="home" size="huge" /> </Tile> </div> </div> </Story> </Canvas> Tiles can be wrapped by `Block` component to create an outstanding effect: <Canvas> <Story name="Wrapped inside Block"> <div className="storybook-container"> <div style={{ display: 'flex', width: '100%' }}> <Block outstanding={true} style={{ width: 200 }} className="m-r-10"> <Tile description="A tile wrapped in a block"> <Icon name="home" size="huge" /> </Tile> </Block> <Block outstanding={true} style={{ width: 200 }} className="tile-block-hover-example m-r-10" > <Tile description="A tile wrapped in a block with hover effect"> <Icon name="home" size="bigger" /> </Tile> </Block> </div> </div> </Story> </Canvas> ## Tile Props <ArgsTable of={Tile} /> <file_sep>/packages/ui/src/components/link/Link.types.ts import { TagType } from '../../utils/sharedTypes'; export interface LinkProps extends React.ComponentPropsWithoutRef<React.ElementType> { children: React.ReactNode; className?: string; /** Use a different tag then the one configured in main settings. */ tag?: TagType; underline?: boolean; } <file_sep>/packages/ui/src/components/modal/Modal.stories.mdx import { Fragment } from 'react'; import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs'; import { Button } from '../button/Button'; import { Lorem } from '../lorem/Lorem'; import { Modal, ModalWindow } from './Modal'; <Meta title="Components/Modal" component={Modal} /> # Modal Modals are a common way to render content that needs attention, requires an action or show more information about an element (i.e. a detailed entry of a table). The `Modal` component expects two props, both functions: - `Trigger`: a function that returns an element used to trigger the modal. - `getModalWindowProps`: a function that returns an object with valid `ModalWindow` props. Both functions have one argument: an object with a `setVisible` property. This is a function that takes a boolean as argument and can make the modal visible or not. <Canvas> <Story name="Default"> <div> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary"> Open Modal </Button> )} getModalWindowProps={() => ({ title: 'Modal demo title', content: <Lorem paragraphs={3} />, })} /> </div> </Story> </Canvas> ## Modal Parts The modal is composed of different parts: a title, the content and the footer. The first two are always rendered, while the footer is optional. <Canvas> <Story name="Modal Parts"> <div> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary"> Modal without footer </Button> )} getModalWindowProps={() => ({ title: 'Modal without footer', content: <Lorem paragraphs={3} />, })} /> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary-reverse"> Modal with footer </Button> )} getModalWindowProps={({ setVisible }) => ({ title: 'Modal with footer', content: <Lorem paragraphs={3} />, footer: ( <Fragment> <span className="color-accent">Some text here</span> <Button size="small" onClick={() => setVisible(false)}> Close </Button> </Fragment> ), })} /> </div> </Story> </Canvas> ## Modal Size By default the modal window has the width set to 70% and height set to 400px. The two initial values can be specified by `startHeight` and `startWidth` props. Both values can be numbers (that will be rendered as pixels) or string values. The height must be represented only as pixels (either number or string) abecause the value is used to calculate the modal content height automatically in presence or abscence of footer. The modal can also be maximized by default. This can be prevented by setting `canMaximize` prop to false. <Canvas> <Story name="Modal Size"> <div> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary"> Initial 400 x 300 </Button> )} getModalWindowProps={() => ({ title: 'Modal without footer', content: <Lorem paragraphs={3} />, startHeight: 300, startWidth: 400, })} /> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary-reverse"> Initial 50% x 300 </Button> )} getModalWindowProps={({ setVisible }) => ({ title: 'Modal with footer', content: <Lorem paragraphs={3} />, footer: ( <Fragment> <span className="color-accent">Some text here</span> <Button size="small" onClick={() => setVisible(false)}> Close </Button> </Fragment> ), startWidth: '50%', startHeight: '300px', canMaximize: false, })} /> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary-reverse"> Maximized </Button> )} getModalWindowProps={() => ({ title: 'Modal without footer', content: <Lorem paragraphs={3} />, maximized: true, })} /> </div> </Story> </Canvas> ## Close on escape By default, if Escape key is pressed the modal visibilty will be set to `false`. To prevent this, pass `closeOnEscape` prop with `false` value. <Canvas> <Story name="ESC to close"> <div> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary"> Open Modal without Esc </Button> )} getModalWindowProps={() => ({ title: 'Modal demo title', content: <Lorem paragraphs={3} />, closeOnEscape: false, })} /> </div> </Story> </Canvas> ## Disable Close icon In some circumstances the modal should not be closed, for example when calling an API. The buttons can be disabled manually, but the close icon is always visibile. To hide the icon, set the `showCloseIcon` prop to `false`: <Canvas> <Story name="Without close icon"> <div> <Modal Trigger={({ setVisible }) => ( <Button onClick={() => setVisible(true)} mean="primary"> Open Modal </Button> )} getModalWindowProps={({ setVisible }) => ({ title: 'Modal demo title', content: <Lorem paragraphs={3} />, footer: ( <> <span /> <Button onClick={() => setVisible(false)}>Close</Button> </> ), showCloseIcon: false, })} /> </div> </Story> </Canvas> ## Modal Props <ArgsTable of={Modal} /> ## ModalWindow Props <ArgsTable of={ModalWindow} /> <file_sep>/packages/dashboard/src/components/layout/Header.js /** * Dashboard main header uses Navbar component. * Ideally this shuold not have the same link of the sidebar, * but the purpose of this demo is to demonstrate the usage * of main components. * * The first component of the Navbar is the SidebarTrigger, * which controls the main sidebar. */ import { Link, Navbar, NavbarLink, SidebarTrigger } from '@borrow-ui/ui'; import packageJson from '../../../package.json'; export function Header() { return ( <Navbar fixed={true} left={[ <SidebarTrigger />, { headerLabel: ( <NavbarLink tag={Link} to="/"> Home </NavbarLink> ), name: 'home', }, { headerLabel: ( <NavbarLink tag={Link} to="/books"> Books </NavbarLink> ), name: 'books', }, { headerLabel: ( <NavbarLink tag={Link} to="/movies"> Movies </NavbarLink> ), name: 'movie', }, ]} right={[<span className="m-r-10">{packageJson.version}</span>]} /> ); }
16d7055606b9eab2cc0e2f1de2d9cb7adb8c7f61
[ "Markdown", "TypeScript", "JavaScript" ]
150
TypeScript
borrow-ui/borrow-ui
2c1914cc762cd27a29511d880ac2fc6b57bb8f8a
c268f4a4ec051e44b605ca6d32d8cfb40fa2c0ac
refs/heads/master
<file_sep>var data2009 = [["Social Security, Unemployment, and Labor Spending", 1.22], ["Income due to Individual Income Taxes", 0.915], ["National Defense Spending", 0.661]]; var data2016 = [["Social Security, Unemployment, and Labor Spending", 1.31], ["Income due to Individual Income Taxes", 1.46], ["National Defense Spending", 0.541]]; var chart = d3.select(".chart"); var bar = chart.selectAll("div"); var barUpdate = bar.data(data2009); var barEnter = barUpdate.enter().append("div"); var is2009 = true; var swapButton = document.getElementById("swap"); var title = document.getElementById("title"); var makeBars = function(){ var d; if(is2009){ title.innerHTML = "2009 National Budget" is2009 = false; d = data2009 } else{ title.innerHTML = "2016 National Budget" is2009 = true; d = data2016 } bar = chart.selectAll("div"); barUpdate = bar.data(d); barUpdate.transition().duration(3000).style("width", function(d) { return d[1] * 500 + "px";}) barEnter.text(function(d) { return d[0] + ": $" + d[1] + " Trillion"; }); }; makeBars(); swapButton.addEventListener("click", makeBars);
2559ca421a0267c0ccbbdd302752ffcbaf1120eb
[ "JavaScript" ]
1
JavaScript
JamesSmith1202/14_softdev2
163322cea4725a8b67f939a18a963bf31842c56b
9f8a449217ea369889096a80ede1b1a59981fcd6
refs/heads/master
<repo_name>domibarton/workshop<file_sep>/cars.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Cars library for our Python workshop. ''' import sys class CarDrivingException(Exception): pass class Car(object): def __init__(self): self.started = False self.color = 'black' self.doors = 5 def start_car(self): self.started = True def stop_car(self): self.started = False def drive(self): if self.started: return 'yeah I\'m driving' else: raise CarDrivingException('Engine isn\'t started!') <file_sep>/workshop.py #!/usr/bin/env python # -*- coding: utf-8 -*- from cars import Car # # car.drive() # -> error when not started # my_car = Car() my_other_car = Car() my_other_car.color = 'red' print my_car.drive() print my_car.color print my_car.doors print my_other_car.color print my_other_car.doors
f895b5a45e11c6b9b4bdad8ddfc1b8f46f665c51
[ "Python" ]
2
Python
domibarton/workshop
3d5baa93a91dbb0bc740cd405ef54738a644da58
931e9cc804d1f89b1de4182c72fa3d5af99fac99
refs/heads/master
<repo_name>ajain09/CodeChef<file_sep>/SafeRobots/saferobo.java import java.util.*; class saferobo { public static void main (String[] args) throws java.lang.Exception { try{ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { String s = sc.next(); int sa = sc.nextInt(); int sb = sc.nextInt(); int apos = s.indexOf("A"); int bpos = s.indexOf("B"); int res = 0; for (int j = apos; j < bpos; j++) { if (apos < bpos) { apos += sa; bpos -= sb; } if (apos == bpos) { res = 1; break; } } if (res == 1) { System.out.println("unsafe"); } else { System.out.println("safe"); } } sc.close(); }catch(Exception e){} } } <file_sep>/LinearChess/LinearChess.java import java.util.*; class linchess { public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int j = 0; j < t; j++) { int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } int min = 100000001, ans = 0, p = -1; for (int i = 0; i < n; i++) { if (k % arr[i] == 0) { ans = k / arr[i]; if (ans < min) { min = ans; p = arr[i]; } } } System.out.println(p); } sc.close(); } catch (Exception e) { } } }<file_sep>/HardSequence/hrdseq.java import java.util.*; public class hrdseq { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t > 0 && t <= 128) { int n = sc.nextInt(); int[] arr = new int[n + 1]; arr[0] = 0; arr[1] = 0; int count = 0; for (int i = 1; i < n; i++) { for (int j = i - 1; j >= 0; j--) { if (arr[j] == arr[i]) { arr[i + 1] = i - j; break; } if (j == 0 && arr[i] != 0) { arr[i + 1] = 0; } } } for (int i = 0; i < n; i++) { if (arr[i] == arr[n - 1]) { count++; } } System.out.println(count); t--; sc.close(); } } } <file_sep>/ChainReaction/Reaction.java import java.util.*; class Codechef { public static void main (String[] args) throws java.lang.Exception { try{ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int row = sc.nextInt(); int col = sc.nextInt(); int[][] grid = new int[row][col]; int state = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { int count = 0; grid[i][j] = sc.nextInt(); if(i+1<row) count++; if(i-1>=0) count++; if(j+1<col) count++; if(j-1>=0) count++; if(count<=grid[i][j]) state=1; } } //Parth is super cool if (state == 0) System.out.println("Stable"); else System.out.println("Unstable"); } }catch (Exception e){} } } <file_sep>/MatrixTrace/TRACE.java import java.util.*; import java.lang.*; import java.io.*; class TRACE { public static void main(String[] args) throws java.lang.Exception { try { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int arr[][] = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = sc.nextInt(); } } int sum[][] = new int[n][n]; for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { int num = 0; if (j > 0 && k > 0) num += sum[j - 1][k - 1]; num += arr[j][k]; sum[j][k] = num; } } int max = 0; for (int j = 0; j < n; j++) { max = Math.max(max, sum[j][n - 1]); } for (int j = 0; j < n; j++) { max = Math.max(max, sum[n - 1][j]); } System.out.println(max); sc.close(); } } catch (Exception e) { } } } <file_sep>/Medel/Medel.java import java.util.*; import java.lang.*; import java.io.*; class Medel { public static void main (String[] args) throws java.lang.Exception { try{ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t > 0) { int n = sc.nextInt(); int[] arr = new int[n]; int max = 0, imax = 0; int min = 110, imin = 0; for (int i = 0; i < n; i++) { int a = sc.nextInt(); arr[i] = a; if (a > max) { max = a; imax = i; } if (a < min) { min = a; imin = i; } } if (imax > imin) { System.out.println(min + " " + max); } else { System.out.println(max + " " + min); } t--; } sc.close(); }catch(Exception e){} } }
d2f4fd556ca0d53b8b17325686172a2504b13df5
[ "Java" ]
6
Java
ajain09/CodeChef
39634efcff59227e8866af1eb0bbc60e8ccbf06a
259c609c9182d75c0b732bd71ffb8d624e875841
refs/heads/master
<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { CookieService } from 'ngx-cookie-service'; import { NgxSpinnerService } from 'ngx-spinner'; import { AuthenticationService } from 'src/app/authentication.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { hide = true; loginForm!: FormGroup; eror: any; profileInfo: any; token: any; headers= new HttpHeaders() .set('Content-Type', 'application/json') .set('Authorization', 'Bearer {this.token}'); constructor( private formBuilder: FormBuilder, private authService: AuthenticationService, private http: HttpClient, private router: Router, private spinner: NgxSpinnerService, private cookie: CookieService ) { } showSpinner() { this.spinner.show(undefined, { fullScreen: true, bdColor: "rgba(0, 0, 0, 0.8)", size: "large", color: "#fff", type: "square-jelly-box"}); setTimeout(() => { this.spinner.hide(); }, 1050); } ngOnInit(): void { this.loginForm = this.formBuilder.group({ email: new FormControl('', [Validators.required]), password: new FormControl('', [Validators.required]) }); } onSubmit(){ this.http.post('http://64.227.98.119/api/users/login', JSON.stringify(this.loginForm.value)).subscribe( (res:any) => { console.log(res.token); localStorage.setItem('token', res.token); this.authService.authenticate(res.token); this.cookie.set('token', res.token); this.router.navigate(['/']); }, err=>{ this.eror = err.error.error; console.log(err.error.error); } ) console.log(JSON.stringify(this.loginForm.value)); this.showSpinner(); this.loginForm.reset(); } } <file_sep>import { Injectable } from '@angular/core'; import { Courses } from './courses'; @Injectable({ providedIn: 'root' }) export class CartService { items: Courses[] = []; totalPrice = 0; addToCart(course: Courses){ this.items.push(course); } getItems() { return this.items } setPrice(price: number){ this.totalPrice += price; } getPrice(){ return this.totalPrice } clearCart() { this.items = []; return this.items } constructor() { } } <file_sep>import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { CookieService } from 'ngx-cookie-service'; @Injectable({ providedIn: 'root' }) export class AuthenticationService { public authenticated = new BehaviorSubject<boolean>(this.cookieService.check('token')); rememberCode: any; userProfile: any; role: any; visibility: any; constructor( private cookieService: CookieService ) { } public authenticate(token: string) { this.authenticated.next(true); } public deauthenticate() { this.authenticated.next(false); this.cookieService.delete('token'); localStorage.clear(); } public setVisibility(){ this.visibility = false; } public removeVisibility() { this.visibility = true; } public getVisibility(){ return this.visibility; } public setCode(code: number){ this.rememberCode = code; } public getCode() { return this.rememberCode; } public setProfile(userProf: any){ this.userProfile = userProf; } public getProfile(){ return this.userProfile; } public setRole(role: string) { this.role = role; } public getRole() { return this.role; } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit, ViewChild } from '@angular/core'; import { MatPaginator } from '@angular/material/paginator'; import { Router } from '@angular/router'; import { CookieService } from 'ngx-cookie-service'; import { SubscriptionLike } from 'rxjs'; import { AuthenticationService } from 'src/app/authentication.service'; import { CartService } from 'src/app/cart.service'; import { CourseService } from 'src/app/course.service'; import { Courses } from '../../courses'; import { CoursesHome } from './courses'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { @ViewChild(MatPaginator) paginator!: MatPaginator; purchased = false; created = false; kurs: any; kursevi: CoursesHome[] = []; bought: number[] = []; kupljen: Array<number> = []; kupljen2: Array<number> = []; zbir: any; totalLength: any; page: number =1; role = localStorage.getItem('role'); user: any; courses: any; coursesHome: any; coursesHome2: any; loggedIn: any; createdAt: any; programmingCourses: any; graphCourses: any; webDevCourses: any; subscription: SubscriptionLike | undefined; token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); searchTerm!: string; term!: string; constructor( public auth: AuthenticationService, private http: HttpClient, private cookieService: CookieService, private courseService: CourseService, private router: Router, public cart: CartService ) { } async ngOnInit() { if (!localStorage.getItem('foo')) { localStorage.setItem('foo', 'no reload') location.reload() } else { localStorage.removeItem('foo') } if(!this.token){ this.loggedIn = false } else { this.loggedIn = true } //Uzimam kurseve da uporedim je li kupljen ili ne if(!this.token) { console.log("no user...") } else { if(this.role === 'teacher' ) { this.http.get('http://64.227.98.119/api/courses/teacher/my', {'headers': this.headers}).subscribe( (res: any) => { console.log(res.courses) this.coursesHome = res.courses; } ) } else { this.http.get('http://64.227.98.119/api/courses/student/orders/me', {'headers': this.headers}).subscribe( (res: any) => { let ordersLenght = res.orders.length; let courseLength = res.orders[0]?.Courses.length; for(let i=0; i <= ordersLenght; i++) { let orderLenght = res?.orders[i]?.Courses?.length; for(let j=0; j <= orderLenght; j++) { this.kurs = res.orders[i].Courses[j] if(this.kurs != undefined) { this.kursevi.push(this.kurs) } } } this.coursesHome = this.kursevi console.log(this.coursesHome) } ) } } this.user = this.auth.getProfile(); await this.courseService.getCourses().subscribe( (res: any) => { console.log(res.courses.length); // this.length = res.courses.length this.totalLength = res.courses.length console.log(res.courses); this.courses = res.courses; }, err => { console.log(err); } ); this.courseService.getCourseByCat('programming').subscribe( (res: any) => { console.log(res.courses.length) this.programmingCourses = res.courses }, err => { console.log(err); } ); this.courseService.getCourseByCat('graphic-design').subscribe( (res: any) => { console.log(res.courses.length) this.graphCourses = res.courses }, err => { console.log(err); } ); this.courseService.getCourseByCat('web-dev').subscribe( (res: any) => { // console.log(res.courses) this.webDevCourses = res.courses }, err => { console.log(err); } ); } seeMore(productId: any) { console.log(productId) localStorage.setItem('courseID', productId) this.courseService.setCourseID(productId); this.router.navigate(['/course-details']) } AddToCart(course: Courses){ this.cart.addToCart(course); this.cart.setPrice(course.Price); console.log(course.Price) let x = document.getElementById("snackbar")!; x.className = "show"; setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000); } isBought(id: any){ let isb = false; for(let i=0; i< this.coursesHome.length; i++) { if(id == this.coursesHome[i].ID) { isb = true; break } } return isb; } startCourse(id: any) { this.courseService.setID(id); this.router.navigate(['/course-page']) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { CartService } from 'src/app/cart.service'; @Component({ selector: 'app-cart', templateUrl: './cart.component.html', styleUrls: ['./cart.component.css'] }) export class CartComponent implements OnInit { courses = this.cart.getItems(); price: any; totalPrice = 0; courseExist = false; constructor( private cart: CartService ) { } ngOnInit(): void { console.log(this.cart.getItems()); this.price = this.cart.getPrice(); if(this.price != 0) { this.courseExist = true; } console.log(this.price) } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { MatSnackBar } from '@angular/material/snack-bar'; import { DomSanitizer } from '@angular/platform-browser'; import { NgbRatingConfig } from '@ng-bootstrap/ng-bootstrap'; import { CourseService } from 'src/app/course.service'; @Component({ selector: 'app-start-course', templateUrl: './start-course.component.html', styleUrls: ['./start-course.component.css'], providers: [NgbRatingConfig], styles: [` .star { font-size: 1.5rem; color: #b0c4de; } .filled { color: #1e90ff; } .bad { color: #deb0b0; } .filled.bad { color: #ff1e1e; } `] }) export class StartCourseComponent implements OnInit { token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); rating =3; id: any; course: any; Link: any; link: any; videoUrl: any; ratingForm = this.formBuilder.group({ rating: '' }) constructor( private courseService: CourseService, private sanitizer: DomSanitizer, private formBuilder: FormBuilder, private _snackbar: MatSnackBar, private http: HttpClient, config: NgbRatingConfig ) { config.max = 5; config.readonly = false; } ngOnInit(): void { this.id = this.courseService.getID(); this.courseService.getCourseById(this.id).subscribe( (res: any) => { console.log(res.course.Course); this.course = res.course.Course; this.Link = this.course.Link; // console.log(this.link) var regExp = /^https?\:\/\/(?:www\.youtube(?:\-nocookie)?\.com\/|m\.youtube\.com\/|youtube\.com\/)?(?:ytscreeningroom\?vi?=|youtu\.be\/|vi?\/|user\/.+\/u\/\w{1,2}\/|embed\/|watch\?(?:.*\&)?vi?=|\&vi?=|\?(?:.*\&)?vi?=)([^#\&\?\n\/<>"']*)/i; var match = this.Link.match(regExp); const ID = (match && match[1].length == 11) ? match[1] : false; this.link = 'https://www.youtube.com/embed/' + ID; this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.link); console.log(ID); console.log(this.videoUrl) }, err => { console.log(err); } ) } Clicked() { console.log("Rating with: " + this.rating) this.ratingForm.setValue({rating: this.rating}) this.http.post('http://64.227.98.119/api/courses/student/rate/' + this.id, JSON.stringify(this.ratingForm.value), {'headers': this.headers}).subscribe( res => { console.log(res) this._snackbar.open('Course rated!', 'Close!') }, err => { console.log(err) } ) } } <file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NavbarComponent } from './components/navbar/navbar.component'; import { HomeComponent } from './components/home/home.component'; import { HttpClientModule } from '@angular/common/http'; import {MatCardModule} from '@angular/material/card'; import {MatIconModule} from '@angular/material/icon'; import {MatButtonModule} from '@angular/material/button'; import {MatBadgeModule} from '@angular/material/badge'; import {MatInputModule} from '@angular/material/input'; import { LoginComponent } from './components/login/login.component'; import { SignupComponent } from './components/signup/signup.component'; import { FooterComponent } from './components/footer/footer.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgxSpinnerModule } from 'ngx-spinner'; import { RememberCodeComponent } from './components/remember-code/remember-code.component'; import { ProfileComponent } from './components/profile/profile.component'; import { CookieService } from 'ngx-cookie-service'; import { EditProfileComponent } from './components/edit-profile/edit-profile.component'; import { RestartPassComponent } from './components/restart-pass/restart-pass.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { CreateCourseComponent } from './components/create-course/create-course.component'; import { AboutComponent } from './components/about/about.component'; import { MyCoursesComponent } from './components/my-courses/my-courses.component'; import { CartComponent } from './components/cart/cart.component'; import { CourseDetalisComponent } from './components/course-detalis/course-detalis.component'; import { PayComponent } from './components/pay/pay.component'; import { WebDesignComponent } from './components/web-design/web-design.component'; import {MatTabsModule} from '@angular/material/tabs'; import { StartCourseComponent } from './components/start-course/start-course.component'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { ThankYouComponent } from './components/thank-you/thank-you.component'; import { ContactComponent } from './components/contact/contact.component'; import { ThankYouContactComponent } from './components/thank-you-contact/thank-you-contact.component'; import { MatPaginatorModule } from '@angular/material/paginator'; import { MatOptionModule } from '@angular/material/core'; import { NgxPaginationModule } from 'ngx-pagination'; import { ApprooveComponent } from './components/approove/approove.component'; import { DialogComponentComponent } from './components/dialog-component/dialog-component.component'; import { MatDialogModule } from '@angular/material/dialog'; import { ConfirmationDialogComponent } from './components/confirmation-dialog/confirmation-dialog.component'; import { ProgrammingComponent } from './programming/programming.component'; import { GraphicDesignComponent } from './graphic-design/graphic-design.component'; import { BecomeTeacherComponent } from './components/become-teacher/become-teacher.component'; import { UpdateComponent } from './components/update/update.component'; import { Ng2SearchPipeModule } from 'ng2-search-filter'; import { SearchComponent } from './search/search.component'; @NgModule({ declarations: [ AppComponent, NavbarComponent, HomeComponent, LoginComponent, SignupComponent, FooterComponent, RememberCodeComponent, ProfileComponent, EditProfileComponent, RestartPassComponent, CreateCourseComponent, AboutComponent, MyCoursesComponent, CartComponent, CourseDetalisComponent, PayComponent, WebDesignComponent, StartCourseComponent, ThankYouComponent, ContactComponent, ThankYouContactComponent, ApprooveComponent, DialogComponentComponent, ConfirmationDialogComponent, ProgrammingComponent, GraphicDesignComponent, BecomeTeacherComponent, UpdateComponent, SearchComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, NgxSpinnerModule, HttpClientModule, MatCardModule, MatButtonModule, MatIconModule, MatBadgeModule, MatInputModule, NgbModule, MatTabsModule, MatSnackBarModule, MatPaginatorModule, MatOptionModule, NgxPaginationModule, MatDialogModule, Ng2SearchPipeModule ], exports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, NgxSpinnerModule, HttpClientModule, MatCardModule, MatButtonModule, MatIconModule, MatBadgeModule, MatInputModule, NgbModule, ], providers: [ CookieService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>export interface Courses { Author: string, AuthorRef: string, Category: string, CreatedAt: string, DeletedAt: string, Description: string, ID: number, Image: string, Link: string, Price: number, Title: string, UpdatedAt: string, created: false, purchased: false } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CourseService { page = 1; id: any; courseID: any; constructor( private http: HttpClient ) { } public setPage(page: any){ this.page = page; } public getCourses() { return this.http.get('http://64.227.98.119/api/courses?page=1'); } public getCourse(){ let courseId = localStorage.getItem('courseID'); return this.http.get('http://64.227.98.119/api/courses/' + courseId); } public getCourseByCat(category: string) { return this.http.get('http://64.227.98.119/api/courses/category/' + category) } public setID(id: any) { this.id = id; } public setCourseID(id: any) { this.courseID = id; } public getCourseID() { return this.courseID; } public getID() { return this.id } public getCourseById(id: any) { return this.http.get('http://64.227.98.119/api/courses/' + id); } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthenticationService } from 'src/app/authentication.service'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-edit-profile', templateUrl: './edit-profile.component.html', encapsulation: ViewEncapsulation.None, styles: [` .dark-modal .modal-content { background-color: #292b2c; color: white; } .dark-modal .close { color: white; } .light-blue-backdrop { background-color: #5cb3fd; } `], styleUrls: ['./edit-profile.component.css'] }) export class EditProfileComponent implements OnInit { closeResult: string | undefined; token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); user: any; editForm = this.formBuilder.group({ name: '', surname: '', image: '' }); eror: any; message: any; constructor( public auth: AuthenticationService, private formBuilder: FormBuilder, private http: HttpClient, private router: Router, private modalService: NgbModal ) { } onSubmit(){ // console.log(JSON.stringify(this.editForm.value)); this.http.put('http://64.227.98.119/api/users/private/profile/edit', JSON.stringify(this.editForm.value), {'headers': this.headers}).subscribe( (res: any) => { console.log(res) this.message = res.ok; }, err => { console.log(err); this.eror = err.error.error; } ) } ngOnInit(): void { this.user = this.auth.getProfile(); } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit, Version } from '@angular/core'; import { Router } from '@angular/router'; import { AuthenticationService } from 'src/app/authentication.service'; import { CourseService } from 'src/app/course.service'; import {Courses} from './courses'; import {MatDialog} from '@angular/material/dialog'; import { DialogComponentComponent } from '../dialog-component/dialog-component.component'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component'; import { MatSnackBar } from '@angular/material/snack-bar'; @Component({ selector: 'app-my-courses', templateUrl: './my-courses.component.html', styleUrls: ['./my-courses.component.css'] }) export class MyCoursesComponent implements OnInit { version = Version; user: any; token = localStorage.getItem('token'); courses: any; kurs: any; role = localStorage.getItem('role'); message: any; duzina: any; searchTerm!: string; term!: string; items: Courses[] = []; headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); constructor( private auth: AuthenticationService, private http: HttpClient, private courseService: CourseService, private router: Router, private dialog: MatDialog, private snackBar: MatSnackBar ) { } ngOnInit(): void { this.user = this.auth.getProfile() if(this.role != 'student' ) { this.http.get('http://192.168.3.11/api/courses/teacher/my', {'headers': this.headers}).subscribe( (res: any) => { console.log(res.courses.length) this.courses = res.courses; this.duzina = res.courses.length; } ) } else { this.http.get('http://64.227.98.119/api/courses/student/orders/me', {'headers': this.headers}).subscribe( (res: any) => { let ordersLenght = res.orders.length; let courseLength = res.orders[0].Courses.length; for(let i=0; i <= ordersLenght; i++) { let orderLenght = res?.orders[i]?.Courses?.length; for(let j=0; j <= orderLenght; j++) { this.kurs = res.orders[i].Courses[j] if(this.kurs != undefined) { this.items.push(this.kurs) } } } this.courses = this.items console.log(this.courses) } ) } } openDialog(id: any) { const dialogRef = this.dialog.open(ConfirmationDialogComponent, { data: { message: 'Are you sure you want to delete Course?', buttonText: { ok: 'Delete', cancel: 'Cancel' } } }) const snack = this.snackBar.open('Deleting course?', 'Close', { duration: 3000, }); dialogRef.afterClosed().subscribe((confirmed: boolean) => { if (confirmed) { snack.dismiss(); this.http.delete('http://6192.168.3.11/api/courses/teacher/delete/' + id, {'headers': this.headers}).subscribe( (res: any) => { console.log(res.ok) this.message = res.ok }, err => { console.log(err) } ) snack.dismiss(); this.snackBar.open('Course deleted!', 'Close!', { duration: 2000, }); this.router.navigate(['/home']) } }); } startCourse(id: any) { this.courseService.setID(id); this.router.navigate(['/course-page']) } Update(id: any) { this.courseService.setCourseID(id) this.router.navigate(['/update']) } } <file_sep>import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BecomeTeacherComponent } from './become-teacher.component'; describe('BecomeTeacherComponent', () => { let component: BecomeTeacherComponent; let fixture: ComponentFixture<BecomeTeacherComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ BecomeTeacherComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(BecomeTeacherComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ContactService { private api = 'https://mailthis.to/kambo' constructor( private http: HttpClient ) { } PostMessage(input: any) { return this.http.post(this.api, input, {responseType: 'text'}) // .subscribe( // (res) => { // return res // }, // err => { // return err // } // ) } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { CookieService } from 'ngx-cookie-service'; import { AuthenticationService } from 'src/app/authentication.service'; @Component({ selector: 'app-restart-pass', templateUrl: './restart-pass.component.html', styleUrls: ['./restart-pass.component.css'] }) export class RestartPassComponent implements OnInit { user: any; token = localStorage.getItem('token'); resetForm = this.formBuilder.group({ resetCode: '', newPassword: '' }); eror: any; profileInfo: any; message: any; headers= new HttpHeaders() .set('Content-Type', 'application/json') .set('Authorization', `Bearer ${this.token}`); constructor( public auth: AuthenticationService, private formBuilder: FormBuilder, private http: HttpClient, private cookies: CookieService, ) { } ngOnInit(): void { this.user = this.auth.getProfile(); } onSubmit(){ this.http.put('http://64.227.98.119/api/users/private/password/reset', JSON.stringify(this.resetForm.value), {'headers': this.headers}).subscribe( (res: any) => { console.log(res) this.message = res.ok; }, err => { this.eror = err.error.error console.log(err.error.error) } ) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthenticationService } from 'src/app/authentication.service'; @Component({ selector: 'app-remember-code', templateUrl: './remember-code.component.html', styleUrls: ['./remember-code.component.css'] }) export class RememberCodeComponent implements OnInit { code: any; constructor( private authentication: AuthenticationService, private router: Router ) { } ngOnInit(): void { this.code = this.authentication.getCode(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthenticationService } from 'src/app/authentication.service'; import { CartService } from 'src/app/cart.service'; import { CourseService } from 'src/app/course.service'; @Component({ selector: 'app-web-design', templateUrl: './web-design.component.html', styleUrls: ['./web-design.component.css'], }) export class WebDesignComponent implements OnInit { courses: any; role = localStorage.getItem('role') error: any; searchTerm!: string; term!: string; constructor( private courseService: CourseService, public auth: AuthenticationService, private cart: CartService, private router: Router ) { } ngOnInit(): void { this.courseService.getCourseByCat('web-dev').subscribe( (res: any) => { console.log(res.courses.length) this.courses = res.courses }, (err: any) => { console.log(err); this.error = err.err; } ); } seeMore(id: any) { localStorage.setItem('courseID', id) this.courseService.setCourseID(id); this.router.navigate(['/course-details']) } AddToCart(course: any) { this.cart.addToCart(course); this.cart.setPrice(course.Price); console.log(course.Price) let x = document.getElementById("snackbar")!; x.className = "show"; setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000); } } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AboutComponent } from './components/about/about.component'; import { ApprooveComponent } from './components/approove/approove.component'; import { BecomeTeacherComponent } from './components/become-teacher/become-teacher.component'; import { CartComponent } from './components/cart/cart.component'; import { ContactComponent } from './components/contact/contact.component'; import { CourseDetalisComponent } from './components/course-detalis/course-detalis.component'; import { CreateCourseComponent } from './components/create-course/create-course.component'; import { EditProfileComponent } from './components/edit-profile/edit-profile.component'; import { HomeComponent } from './components/home/home.component'; import { LoginComponent } from './components/login/login.component'; import { MyCoursesComponent } from './components/my-courses/my-courses.component'; import { PayComponent } from './components/pay/pay.component'; import { ProfileComponent } from './components/profile/profile.component'; import { RememberCodeComponent } from './components/remember-code/remember-code.component'; import { RestartPassComponent } from './components/restart-pass/restart-pass.component'; import { SignupComponent } from './components/signup/signup.component'; import { StartCourseComponent } from './components/start-course/start-course.component'; import { ThankYouContactComponent } from './components/thank-you-contact/thank-you-contact.component'; import { ThankYouComponent } from './components/thank-you/thank-you.component'; import { UpdateComponent } from './components/update/update.component'; import { WebDesignComponent } from './components/web-design/web-design.component'; import { GraphicDesignComponent } from './graphic-design/graphic-design.component'; import { ProgrammingComponent } from './programming/programming.component'; import { SearchComponent } from './search/search.component'; const routes: Routes = [ {path: '', redirectTo: 'home', pathMatch: 'full'}, {path: 'home', component: HomeComponent}, {path: 'login', component: LoginComponent}, {path: 'remember-code', component: RememberCodeComponent}, {path: 'signup', component: SignupComponent}, {path: 'profile', component: ProfileComponent}, {path: 'edit-profile', component: EditProfileComponent}, {path: 'restart-password', component: RestartPassComponent}, {path: 'create-course', component: CreateCourseComponent}, {path: 'about', component: AboutComponent}, {path: 'cart', component: CartComponent}, {path: 'my-courses', component: MyCoursesComponent}, {path: 'course-details', component: CourseDetalisComponent}, {path: 'pay', component: PayComponent}, {path: 'web-design', component: WebDesignComponent}, {path: 'course-page', component: StartCourseComponent}, {path: 'thank-you', component: ThankYouComponent}, {path: 'contact', component: ContactComponent}, {path: 'thank-you-for-contact', component: ThankYouContactComponent}, {path: 'approove', component: ApprooveComponent, data: {title: 'Change user role', toolbar: false}}, {path: 'programming', component: ProgrammingComponent}, {path: 'graphic-design', component: GraphicDesignComponent}, {path: 'become-a-teacher', component: BecomeTeacherComponent}, {path: 'update', component: UpdateComponent}, {path: 'search', component: SearchComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { NgbRatingConfig } from '@ng-bootstrap/ng-bootstrap'; import { CartService } from 'src/app/cart.service'; import { CourseService } from 'src/app/course.service'; import { Courses } from '../../courses'; import {MatSnackBar} from '@angular/material/snack-bar'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Router } from '@angular/router'; import { AuthenticationService } from 'src/app/authentication.service'; @Component({ selector: 'app-course-detalis', templateUrl: './course-detalis.component.html', styleUrls: ['./course-detalis.component.css'], providers: [NgbRatingConfig], styles: [` .star { font-size: 1.5rem; color: #b0c4de; } .filled { color: #1e90ff; } .bad { color: #deb0b0; } .filled.bad { color: #ff1e1e; } `] }) export class CourseDetalisComponent implements OnInit { course: any; clicked = false; rating: any; readonly = false; currentRate: any; courseID: any; isti = false; authen: any; postoji:number = 0; role: any; coursesHome: any; kurs: any; kursevi: any[] = []; token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); constructor( public auth: AuthenticationService, public courseService: CourseService, private cart: CartService, private router: Router, private http: HttpClient, private _snackBar: MatSnackBar, config: NgbRatingConfig ) { config.max = 5; config.readonly = true; } async ngOnInit() { if(!this.token){ console.log("no user...") } else { this.authen = true } console.log(this.authen) this.role = await localStorage.getItem('role'); console.log(this.role) if(!this.token){ console.log("no user...") } else { //Uzimam kurseve da uporedim je li kupljen ili ne if(this.role != 'student' ) { this.http.get('http://64.227.98.119/api/courses/teacher/my', {'headers': this.headers}).subscribe( (res: any) => { console.log(res.courses) this.coursesHome = res.courses; } ) } else { this.http.get('http://64.227.98.119/api/courses/student/orders/me', {'headers': this.headers}).subscribe( (res: any) => { let ordersLenght = res.orders.length; let courseLength = res.orders[0].Courses.length; for(let i=0; i <= ordersLenght; i++) { let orderLenght = res?.orders[i]?.Courses?.length; for(let j=0; j <= orderLenght; j++) { this.kurs = res.orders[i].Courses[j] if(this.kurs != undefined) { this.kursevi.push(this.kurs) } } } this.coursesHome = this.kursevi } ) } } this.courseID = this.courseService.getCourseID(); console.log(this.courseID) //Uzimam kurs i prikazujem ga na stranici this.courseService.getCourse().subscribe( (res: any) => { console.log(res.course) this.course = res.course.Course this.currentRate = res.course.Rating; this.rating = res.course.Rating; console.log(this.currentRate); if(!this.token){ console.log("no user...") } else { for(let i=0; i < this.coursesHome.length; i++) { if(this.course.ID == this.coursesHome[i].ID) { console.log("ID je isti " + this.coursesHome[i].ID + " && " + this.course.ID) this.isti = true; this.postoji = this.course.ID } else { console.log("ID nije isti " + this.coursesHome[i].ID + " && " + this.course.ID) this.isti = false } } } }, err => { console.log(err) } ) } startCourse(id: any) { this.courseService.setID(id); this.router.navigate(['/course-page']) } openSnackBar(message: string, action: string, course: any) { this._snackBar.open(message, action); this.cart.addToCart(course); this.cart.setPrice(course.Price); } login() { this.router.navigate(['/login']); } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { NgxSpinnerService } from 'ngx-spinner'; import { CartService } from 'src/app/cart.service'; import { Courses } from './courses'; @Component({ selector: 'app-pay', templateUrl: './pay.component.html', styleUrls: ['./pay.component.css'] }) export class PayComponent implements OnInit { price: any; eror: any; message: any; items: Courses[] = []; token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); constructor( private http: HttpClient, private cart: CartService, private spinner: NgxSpinnerService, private router: Router ) { } ngOnInit(): void { this.price = this.cart.getPrice() -10; this.items = this.cart.getItems(); } showSpinner() { this.spinner.show(undefined, { fullScreen: true, bdColor: "rgba(0, 0, 0, 0.8)", size: "large", color: "#fff", type: "square-jelly-box"}); setTimeout(() => { this.spinner.hide(); }, 2000); } pay() { console.log(this.items) this.showSpinner() this.http.post('http://64.227.98.119/api/courses/student/order', {"courses": this.items, "totalPrice": this.price}, {'headers': this.headers}).subscribe( (res: any) => { console.log(res) this.message = res.ok this.router.navigate(['/thank-you']) }, err => { console.log(err.error.error); this.eror = err.error.error } ) } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Router } from '@angular/router'; import { NgxSpinnerService } from 'ngx-spinner'; import { AuthenticationService } from 'src/app/authentication.service'; @Component({ selector: 'app-create-course', templateUrl: './create-course.component.html', styleUrls: ['./create-course.component.css'], styles: [` :host >>> .alert-custom { color: #99004d; background-color: #f169b4; border-color: #800040; } `] }) export class CreateCourseComponent implements OnInit { eror: any; message: any; isCompleted = false; categories: string[] = ['web-dev', 'programming', 'graphic-design']; createCourseForm!: FormGroup; token = localStorage.getItem('token'); user: any; headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); constructor( private formBuilder: FormBuilder, private http: HttpClient, private spinner: NgxSpinnerService, private auth: AuthenticationService, private router: Router, private snackbar: MatSnackBar ) { } ngOnInit(): void { this.createCourseForm = this.formBuilder.group({ title: '', description: '', price: '', image: '', link: '', author: `${localStorage.getItem('name')}`, category: '', }); this.user = this.auth.getProfile(); localStorage.setItem('name', JSON.stringify(this.user.name)); } showSpinner() { this.spinner.show(undefined, { fullScreen: true, bdColor: "rgba(0, 0, 0, 0.8)", size: "large", color: "#fff", type: "square-jelly-box"}); setTimeout(() => { this.spinner.hide(); }, 2000); } onSubmit() { console.log(this.createCourseForm.value); console.log(JSON.stringify(this.createCourseForm.value)); this.showSpinner(); const snack = this.snackbar.open('Course Created', 'Close', { duration: 3000, }); this.http.post('http://192.168.127.12/api/courses/teacher/create', JSON.stringify(this.createCourseForm.value), {'headers': this.headers}).subscribe( (res: any) => { console.log(res.ok); this.message = res.ok; this.router.navigate(['/home']) }, err => { console.log(err); this.eror = err.statusText; } ); this.createCourseForm.reset(); } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CartService } from '../cart.service'; import { CoursesHome } from '../components/home/courses'; import { CourseService } from '../course.service'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css'] }) export class SearchComponent implements OnInit { courses: any; searchTerm!: string; term!: string; role = localStorage.getItem('role'); coursesHome: any; kurs: any; kursevi: CoursesHome[] = []; loggedIn: any; token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); constructor( private courseService: CourseService, private http: HttpClient, private cart: CartService, private router: Router ) { } ngOnInit(): void { if(!this.token){ this.loggedIn = false } else { this.loggedIn = true } this.courseService.getCourses().subscribe( (res: any) => { console.log(res.courses.length); console.log(res.courses); this.courses = res.courses; }, err => { console.log(err); } ); //Uzimam kurseve da uporedim je li kupljen ili ne if(!this.token) { console.log("no user...") } else { if(this.role === 'teacher' ) { this.http.get('http://6172.16.58.3/api/courses/teacher/my', {'headers': this.headers}).subscribe( (res: any) => { console.log(res.courses) this.coursesHome = res.courses; } ) } else { this.http.get('http://6172.16.58.3/api/courses/student/orders/me', {'headers': this.headers}).subscribe( (res: any) => { let ordersLenght = res.orders.length; let courseLength = res.orders[0]?.Courses.length; for(let i=0; i <= ordersLenght; i++) { let orderLenght = res?.orders[i]?.Courses?.length; for(let j=0; j <= orderLenght; j++) { this.kurs = res.orders[i].Courses[j] if(this.kurs != undefined) { this.kursevi.push(this.kurs) } } } this.coursesHome = this.kursevi console.log(this.coursesHome) } ) } } } AddToCart(course: any) { this.cart.addToCart(course); this.cart.setPrice(course.Price); console.log(course.Price) let x = document.getElementById("snackbar")!; x.className = "show"; setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000); } seeMore(productId: any) { console.log(productId) localStorage.setItem('courseID', productId) this.courseService.setCourseID(productId); this.router.navigate(['/course-details']) } startCourse(id: any) { this.courseService.setID(id); this.router.navigate(['/course-page']) } isBought(id: any){ let isb = false; for(let i=0; i< this.coursesHome.length; i++) { if(id == this.coursesHome[i].ID) { isb = true; break } } return isb; } } <file_sep>export interface Created { created: false }<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthenticationService } from './authentication.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'udemy-frontend'; visibility: any; role: any; user: any; token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); constructor( private auth: AuthenticationService, private http: HttpClient, private router: Router ){ } ngOnInit(): void { if(this.token != undefined) { this.http.get('http://172.16.31.10/api/users/private/me', {'headers': this.headers}).subscribe( (res: any) => { // this.cookieService.set('profile', res.userProfile); console.log(res.userProfile); this.user = res.userProfile; console.log(this.user.role) this.role = this.user.role; if (this.user.role == 'admin') { this.visibility = false; this.router.navigate(['/approove']); } this.auth.setRole(res.userProfile.role); localStorage.setItem('role', this.user.role) this.auth.setProfile(res.userProfile); this.auth.authenticate(res.token); }, err => { console.log(err) } ); } this.visibility = this.auth.getVisibility(); } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthenticationService } from 'src/app/authentication.service'; import { CartService } from 'src/app/cart.service'; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit { cartItems: any; user: any; role: any; token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Authorization', `Bearer ${this.token}`) .set('Content-Type', 'application/json'); constructor( public AuthenticationService: AuthenticationService, public cart: CartService, private http: HttpClient, private router: Router ) { } ngOnInit(): void { if(this.token != undefined) { this.http.get('http://192.168.127.12/api/users/private/me', {'headers': this.headers}).subscribe( (res: any) => { // this.cookieService.set('profile', res.userProfile); console.log(res.userProfile); this.user = res.userProfile; console.log(this.user.role) this.role = this.user.role; if (this.user.role == 'admin') { this.router.navigate(['/approove']); } this.AuthenticationService.setRole(res.userProfile.role); localStorage.setItem('role', this.user.role) this.AuthenticationService.setProfile(res.userProfile); this.AuthenticationService.authenticate(res.token); }, err => { console.log(err) } ); } this.cartItems = this.cart.getItems(); } logout() { this.AuthenticationService.deauthenticate(); localStorage.clear(); } } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { NgxSpinnerService } from 'ngx-spinner'; import { AuthenticationService } from 'src/app/authentication.service'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { hide = true; signupForm!: FormGroup; roles: string[] = ['student', 'teacher']; choosenRole: any; eror: any; headers= new HttpHeaders() .set('Content-Type', 'application/json'); constructor( private formBuilder: FormBuilder, private http: HttpClient, private router: Router, private spinner: NgxSpinnerService, private authentication: AuthenticationService ) { } showSpinner() { this.spinner.show(undefined, { fullScreen: true, bdColor: "rgba(0, 0, 0, 0.8)", size: "large", color: "#fff", type: "square-jelly-box"}); setTimeout(() => { this.spinner.hide(); }, 1050); } ngOnInit(): void { this.signupForm = this.formBuilder.group({ email: new FormControl('', [Validators.required]), name: new FormControl('', [Validators.required]), surname: new FormControl('', [Validators.required]), password: new FormControl('', [Validators.required]), image: new FormControl('', [Validators.required]), role: new FormControl('', [Validators.required]), }) } onSubmit(){ this.http.post('http://64.227.98.119/api/users/signup', JSON.stringify(this.signupForm.value)).subscribe( (res:any) => { console.log(res.resetCode); this.authentication.setCode(res.resetCode); this.router.navigate(['/remember-code']); this.showSpinner(); }, err=>{ console.log(err.error.error); this.eror = err.error.error; } ) this.showSpinner(); this.signupForm.reset(); } }<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Router } from '@angular/router'; import { AuthenticationService } from 'src/app/authentication.service'; @Component({ selector: 'app-approove', templateUrl: './approove.component.html', styleUrls: ['./approove.component.css'] }) export class ApprooveComponent implements OnInit { approoveForm!: FormGroup token = localStorage.getItem('token'); headers= new HttpHeaders() .set('Content-Type', 'application/json') .set('Authorization', `Bearer ${this.token}`) constructor( private formBuilder: FormBuilder, private http: HttpClient, private auth: AuthenticationService, private router: Router, private snackbar: MatSnackBar ) { } ngOnInit(): void { this.auth.setVisibility() this.approoveForm = this.formBuilder.group({ email: new FormControl('', [Validators.required]) }) } onSubmit(){ this.http.put('http://64.227.98.119/api/users/private/change', JSON.stringify(this.approoveForm.value), {'headers': this.headers}).subscribe( res => { console.log(res) this.auth.removeVisibility(); this.snackbar.open('Role change succes!', 'Close!', { duration: 3000, }) }, err => { console.log(err) } ) } logout() { this.auth.deauthenticate() localStorage.clear() this.router.navigate(["/login"]) } }
a6855d789726128207b074b338b0f7e97c079721
[ "TypeScript" ]
26
TypeScript
kamberk/udemy-frontend
adac2e9f219c5b89703d1c2891f1724896489ea4
58f8347eaa6366d6cc80cfb6a1d5ff80d7df816f
refs/heads/master
<repo_name>Luckz/statman-gauge<file_sep>/test/gauge-test.js /*jslint node: true */ "use strict"; var Gauge = require('../lib/Gauge'); var mocha = require('mocha'); var assert = require('assert'); var should = require('should'); describe('gauge', function () { it('explicit construct', function () { var gauge = new Gauge('metric-name'); should.exist(gauge); }); it('implicit construct', function () { var gauge = Gauge('metric-name'); should.exist(gauge); }); it('gauge returns name', function () { var gauge = new Gauge('metric-name'); gauge.name().should.equal('metric-name'); }); it('gauge value initializes to 0', function () { var gauge = new Gauge('metric-name'); gauge.value().should.equal(0); }); it('gauge value increments from 0 to 1', function () { var gauge = new Gauge('metric-name'); gauge.increment(); gauge.value().should.equal(1); }); it('gauge increments by specified value', function () { var gauge = new Gauge('metric-name'); gauge.set(10); gauge.increment(2); gauge.value().should.equal(12); }); it('gauge value decrements from 0 to -1', function () { var gauge = new Gauge('metric-name'); gauge.decrement(); gauge.value().should.equal(-1); }); it('gauge decrements by specified value', function () { var gauge = new Gauge('metric-name'); gauge.decrement(2); assert.equal(-2, gauge.value()); }); it('gauge can be set to specified value', function () { var gauge = new Gauge('metric-name'); gauge.set(5); gauge.value().should.equal(5); }); it('gauge can be set then incremented', function () { var gauge = new Gauge('metric-name'); gauge.set(5); gauge.increment(); gauge.value().should.equal(6); }); it('gauge can be set then decremented', function () { var gauge = new Gauge('metric-name'); gauge.set(5); gauge.decrement(); gauge.value().should.equal(4); }); it('gauge can be incremented more than once', function () { var gauge = new Gauge('metric-name'); gauge.set(5); gauge.increment(); gauge.increment(); gauge.value().should.equal(7); }); it('gauge can be decremented more than once', function () { var gauge = new Gauge('metric-name'); gauge.set(5); gauge.decrement(); gauge.decrement(); gauge.value().should.equal(3); }); function testSetWithInvalidInput(input) { var gauge = new Gauge('metric-name'); assert.throws(function () { gauge.set(input); }, Error, "`set` should throw exception if passed non-numeric value"); } it('unable to set to string', function () { var input = "str"; testSetWithInvalidInput(input); }); it('unable to set to null', function () { var input = null; testSetWithInvalidInput(input); }); it('unable to set to undefined', function () { var input; testSetWithInvalidInput(input); }); it('gauge can utilize a custom function to represent value', function () { var customValueFunction = function () { return 5; }; var gauge = new Gauge('metric-name', customValueFunction); assert.equal(5, gauge.value()); }); it('gauge will not access a non-function for custom value', function () { assert.throws(function () { var gauge = new Gauge('metric-name', 5); }); }); it('with two gauges, values are independent', function () { var gaugeA = new Gauge('metric-name'); gaugeA.set(5); gaugeA.increment(); gaugeA.increment(); gaugeA.decrement(); var gaugeB = new Gauge('metric-name'); gaugeB.set(10); gaugeB.increment(); gaugeB.decrement(); gaugeB.decrement(); assert.equal(6, gaugeA.value()); assert.equal(9, gaugeB.value()); }); describe('toString', function() { it('with name', function () { var gauge = new Gauge('metric-name'); gauge.set(5); gauge.toString().should.equal('[metric-name: 5]'); }); it('without name', function () { var gauge = new Gauge(); gauge.set(5); gauge.toString().should.equal('[5]'); }); }); }); <file_sep>/README.md # statman-gauge [![Build Status](https://travis-ci.org/jasonray/statman-gauge.svg?branch=master)](https://travis-ci.org/jasonray/statman-gauge) [![on npm](http://img.shields.io/npm/v/statman-gauge.svg?style=flat)](https://www.npmjs.org/package/statman-gauge) [![Greenkeeper badge](https://badges.greenkeeper.io/jasonray/statman-gauge.svg)](https://greenkeeper.io/) `statman-gauge` is one of the metrics from the [`statman`](https://github.com/jasonray/statman) library. Loosely based upon [codehale metric package](http://metrics.codahale.com/getting-started/#gauges), a gauge is an instantaneous measurement metric. This can be use to capture things like the size of a queue, number of messages processed, or some other interesting thing within your system. **WARNING!!** if you look at the word `gauge` long enough, it looks misspelled ## Install it! ### Option 1: access directly Install using npm: ``` bash npm install statman-gauge ``` Reference in your app: ``` javascript var Gauge = require('statman-gauge'); var gauge = Gauge('gauge-name'); ``` ### Option 2: access from `statman` Install using npm: ``` bash npm install statman ``` Reference in your app: ``` javascript var statman = require('statman'); var gauge = statman.Gauge('gauge-name'); ``` ## Use it! ### Constructor + Gauge() => create instance of a gauge + Gauge(name) => create instance of a gauge with name + Gauge(name, f()) => create instance of a gauge with name, where f is a function that returns the value for the gauge ### Increment + increment() => increment value by 1 + increment(value) => increment by value ``` javascript gauge.increment(); //increment by 1 gauge.increment(10); //increment by 10 ``` ### Decrement + decrement() => decrement value by 1 + decrement(value) => decrement by value ``` javascript gauge.decrement(); //decrement by 1 gauge.decrement(10); //decrement by 10 ``` ### Set + set(value) => set value of gauge ``` javascript gauge.set(5); ``` ### Value + value() => get the value of the gauge ``` javascript gauge.value(); ``` ### Example: Suppose that we want to create a gauage that measures that size of a queue. The below indicates how to register this. #### Method 1 (use gauge directly) ``` javascript var Gauge = require('statman-gauge'); var gauge = Gauge('queueSize'); function enqueue(message) { data.push(message); gauge.increment(); } function dequeue() { data.pop(message); gauge.decrement(); } ``` #### Method 2 (use gauge via statman) ``` TODO ``` #### Method 3 (use custom value function) ``` javascript var Gauge = require('statman-gauge'); var gauge = Gauge('queueSize', function() { return data.size(); }); function enqueue(message) { data.push(message); } function dequeue() { data.pop(message); } ``` ## Build it! - Make sure that you have `node` and `npm` installed - Clone source code to you local machine - Setup dependencies: `npm install` - run tests: `npm test`
457b33ad58c23ca83d2bcc515242c00cc7e77b64
[ "JavaScript", "Markdown" ]
2
JavaScript
Luckz/statman-gauge
c229aa634605a3779dd068ffc9a8f88d3df40b30
f7f9952b6dcfe59c1fa7293bba127bd88c6292df
refs/heads/master
<repo_name>negimohit1209/Redux_101<file_sep>/src/store/reducers/result.js import * as actionTypes from '../action/actionTypes'; import {updateObject} from '../utility'; const initialState = { results: [] } const deleteResult = (state, action) => { const updatedState = state.results.filter((result) => result.id !== action.resultElementId); return updateObject(state, {results: updatedState}) } const reducer = (state= initialState, action) => { switch(action.type){ case actionTypes.STORE_RESULT: return updateObject(state, {results: state.results.concat({ val: action.result , id: new Date()})}) case actionTypes.DELETE_RESULT: return deleteResult(state, action) default: return state; } } export default reducer;
93057e5726c72b37f36640e03c27c7afe0b7126b
[ "JavaScript" ]
1
JavaScript
negimohit1209/Redux_101
fd090e3c9e00cf87c54e72d5ea6eea402377aa89
7fecb15c33f4752a360b1d923da9bda75c3dd1f7
refs/heads/master
<file_sep>package com.example.ricardocampos.camera import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.provider.MediaStore import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* class MainActivity : AppCompatActivity() { private val REQUEST_IMAGE_CAPTURE = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) fab.setOnClickListener { view -> val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (takePictureIntent.resolveActivity(packageManager) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK && data != null) { val extras = data.extras val imageBitmap = extras.get("data") as Bitmap mImageView.setImageBitmap(imageBitmap) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } }
bac5d52e52043beeaf7898a7f0389a274cfd1d05
[ "Kotlin" ]
1
Kotlin
ricamgar/CameraPermission
7debbf7acf6f42835465f5b162a7e89e579b7854
49f59c6144a1281ed996fcf253eab674e542c334
refs/heads/main
<repo_name>aldillapramesta/DompetKu<file_sep>/API/registerAPI.php <?php require_once 'connection.php'; $response = array(); if(isset($_GET['apicall'])){ switch($_GET['apicall']){ case 'signup': if(isTheseParametersAvailable(array('username','password','fullname','city','wallet'))){ $username = $_POST['username']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $fullname = $_POST['fullname']; $city = $_POST['city']; $wallet = 0; // $stmt = $conn->prepare("SELECT id_user FROM users WHERE username =:username"); // $params = array( // ":username" => $username, // ); // $stmt->execute($params); // $stmt->store_result(); $sql = "SELECT id_user FROM users WHERE username=:username"; $stmt = $db->prepare($sql); $params = array( ":username" => $username, ); $stmt->execute($params); //$stmt->store_result(); if($stmt->rowCount() > 0){ $response['error'] = true; $response['message'] = 'User already registered'; // //$stmt->close(); } else{ // $stmt = $conn->prepare("INSERT INTO users (username, password, fullname, city, wallet) VALUES (?, ?, ?, ?, ?)"); // $stmt->bind_param("ssss", $username, $password, $fullname, $city, $wallet); $sql = "INSERT INTO users (username, password, fullname, city, wallet) VALUES ('$username', '$password', '$fullname', '$city', '$wallet')"; $stmt = $db->prepare($sql); if($stmt->execute()){ // $stmt = $conn->prepare("SELECT id_user, id_user, username, fullname, city, wallet FROM users WHERE username = ?"); // $stmt->bind_param("s",$username); $sql = "SELECT * FROM users WHERE username=:username"; $stmt = $db->prepare($sql); $params = array( ":username" => $username, ); $stmt->execute($params); //$stmt->bind_result($userid, $id, $username, $fullname, $city, $wallet); $user = $stmt->fetch(PDO::FETCH_ASSOC); // $user = array( // 'id'=>$id, // 'username'=>$username, // 'fullname'=>$fullname, // 'city'=>$city, // 'wallet'=>$wallet, // ); //$stmt->close(); $response['error'] = false; $response['message'] = 'User registered successfully'; $response['user'] = $user; } } } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; // case 'change_password': // if(isTheseParametersAvailable(array('userid','oldpassword','newpassword'))){ // $userid = $_POST['userid']; // $oldpassword = md5($_POST['oldpassword']); // $newpassword = md5($_POST['newpassword']); // $stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id = ? AND user_password = ?"); // $stmt->bind_param("ss", $userid, $oldpassword); // $stmt->execute(); // $stmt->store_result(); // if($stmt->num_rows > 0){ // $stmt = $conn->prepare ("UPDATE user SET user_password='".$newpassword."' where user_id='".$userid."'"); // //$stmt->bind_param("ss", $userid); // if($stmt->execute()){ // $response['error'] = false; // $response['message'] = 'Password successfully changed'; // $response['user'] = $userid; // } // } // else{ // $response['error'] = true; // $response['message'] = 'Password is not match'; // $stmt->close(); // } // } // else{ // $response['error'] = true; // $response['message'] = 'required parameters are not available user id' .$_POST['userid']. 'old psswrd ' .$_POST['oldpassword'] . ' new password ' .$_POST['newpassword'] ; // } // break; case 'login': if(isTheseParametersAvailable(array('username', 'password'))){ $username = $_POST['username']; $password = $_POST['password']; $sql = "SELECT * FROM users WHERE username =:username"; $stmt = $db->prepare($sql); $params = array( ":username" => $username, ); $stmt->execute($params); $user = $stmt->fetch(PDO::FETCH_ASSOC); if(password_verify($password, $user["password"])){ $response['error'] = false; $response['message'] = 'Login successfull'; $response['user'] = $user; } else{ $response['error'] = true; $response['message'] = 'Invalid username or password '; } } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'add_pendapatan': if(isTheseParametersAvailable(array('id_user', 'nominal', 'tanggal'))){ $id_user = $_POST['id_user']; $jenis = 'pendapatan'; $nominal = $_POST['nominal']; $tanggal = $_POST['tanggal']; $sql = "INSERT INTO history (id_user, jenis, nominal, tanggal) VALUES ('$id_user', '$jenis', '$nominal', '$tanggal')"; $stmt = $db->prepare($sql); $stmt->execute(); $sql = "SELECT * FROM users WHERE id_user=:id_user"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ); $stmt->execute($params); $user = $stmt->fetch(PDO::FETCH_ASSOC); $sql = "UPDATE users SET wallet=:wallet WHERE id_user=:id_user"; $stmt = $db->prepare($sql); $params = array( ":wallet" => ($user['wallet'] + $nominal), ":id_user" => $id_user, ); $stmt->execute($params); $sql = "SELECT * FROM history WHERE id_user=:id_user"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ); $stmt->execute($params); $list = $stmt->fetch(PDO::FETCH_ASSOC); $response['error'] = false; $response['message'] = 'Data pendapatan berhasil ditambahkan!'; $response['list'] = $list; } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'list_pendapatan': if(isTheseParametersAvailable(array('id_user'))){ $id_user = $_POST['id_user']; $sql = "SELECT * FROM history WHERE id_user =:id_user AND jenis =:jenis"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ":jenis" => 'pendapatan', ); $stmt->execute($params); if($stmt->rowCount() == 0){ $response['error'] = true; $response['message'] = 'List pendapatan kosong!'; } else{ while($list = $stmt->fetch(PDO::FETCH_ASSOC)){ //$response['error'] = false; $response[] = $list; } //$response['message'] = 'Terdapat '.$stmt->rowCount().' list pendapatan'; } //echo json_encode(array("list"=>$response)); } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'add_pengeluaran': if(isTheseParametersAvailable(array('id_user', 'nominal', 'kegiatan'))){ $id_user = $_POST['id_user']; $jenis = 'pengeluaran'; $nominal = $_POST['nominal']; $kegiatan = $_POST['kegiatan']; $sql = "INSERT INTO history (id_user, jenis, nominal, kegiatan) VALUES ('$id_user', '$jenis', '$nominal', '$kegiatan')"; $stmt = $db->prepare($sql); $stmt->execute(); $sql = "SELECT * FROM users WHERE id_user=:id_user"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ); $stmt->execute($params); $user = $stmt->fetch(PDO::FETCH_ASSOC); $sql = "UPDATE users SET wallet=:wallet WHERE id_user=:id_user"; $stmt = $db->prepare($sql); $params = array( ":wallet" => ($user['wallet'] - $nominal), ":id_user" => $id_user, ); $stmt->execute($params); $sql = "SELECT * FROM history WHERE id_user=:id_user"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ); $stmt->execute($params); $list = $stmt->fetch(PDO::FETCH_ASSOC); $response['error'] = false; $response['message'] = 'Data pengeluaran berhasil ditambahkan!'; $response['list'] = $list; } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'list_pengeluaran': if(isTheseParametersAvailable(array('id_user'))){ $id_user = $_POST['id_user']; $sql = "SELECT * FROM history WHERE id_user =:id_user AND jenis =:jenis"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ":jenis" => 'pengeluaran', ); $stmt->execute($params); if($stmt->rowCount() == 0){ $response['error'] = true; $response['message'] = 'List pengeluaran kosong!'; } else{ while($list = $stmt->fetch(PDO::FETCH_ASSOC)){ $response[] = $list; } //$response['error'] = false; //$response['message'] = 'Terdapat '.$stmt->rowCount().' list pengeluaran'; } } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'add_wishlist': if(isTheseParametersAvailable(array('id_user', 'wish', 'tahun', 'harga'))){ $id_user = $_POST['id_user']; $wish = $_POST['wish']; $tahun = $_POST['tahun']; $harga = $_POST['harga']; $sql = "INSERT INTO wishlist (id_user, wish, tahun, harga) VALUES ('$id_user', '$wish', '$tahun', '$harga')"; $stmt = $db->prepare($sql); $stmt->execute(); $sql = "SELECT * FROM wishlist WHERE id_user=:id_user"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ); $stmt->execute($params); $list = $stmt->fetch(PDO::FETCH_ASSOC); $response['error'] = false; $response['message'] = 'Wishlist berhasil ditambahkan!'; $response['list'] = $list; } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'wishlist': if(isTheseParametersAvailable(array('id_user'))){ $id_user = $_POST['id_user']; $sql = "SELECT * FROM wishlist WHERE id_user =:id_user"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ); $stmt->execute($params); if($stmt->rowCount() == 0){ $response['error'] = true; $response['message'] = 'Wishlist kosong!'; } else{ while($list = $stmt->fetch(PDO::FETCH_ASSOC)){ $response[] = $list; } //$response['error'] = false; //$response['message'] = 'Terdapat '.$stmt->rowCount().' wishlist'; } } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; case 'list_history': if(isTheseParametersAvailable(array('id_user'))){ $id_user = $_POST['id_user']; $sql = "SELECT * FROM history WHERE id_user =:id_user"; $stmt = $db->prepare($sql); $params = array( ":id_user" => $id_user, ); $stmt->execute($params); if($stmt->rowCount() == 0){ $response['error'] = true; $response['message'] = 'Wishlist kosong!'; } else{ while($list = $stmt->fetch(PDO::FETCH_ASSOC)){ $response[] = $list; } //$response['error'] = false; //$response['message'] = 'Terdapat '.$stmt->rowCount().' wishlist'; } } else{ $response['error'] = true; $response['message'] = 'required parameters are not available'; } break; default: $response['error'] = true; $response['message'] = 'Invalid Operation Called'; } } else{ $response['error'] = true; $response['message'] = 'Invalid API Call'; } header('Content-Type: application/json'); echo json_encode($response); function isTheseParametersAvailable($params){ foreach($params as $param){ if(!isset($_POST[$param])){ return false; } } return true; } ?> <file_sep>/app/src/main/java/com/arga/dompetku/SharedPrefManager.java package com.arga.dompetku; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import java.text.DateFormat; import java.util.Date; public class SharedPrefManager { private static final String SHARED_PREF_NAME = "dompetku"; private static final String KEY_USERNAME = "keyusername"; private static final String KEY_FULLNAME = "keyfullname"; private static final String KEY_CITY = "keycity"; private static final String KEY_WALLET = "keywallet"; private static final String KEY_ID_USER = "keyiduser"; private static final String KEY_ID_HISTORY = "keyidhistory"; private static final String KEY_JENIS = "keyjenis"; private static final String KEY_NOMINAL = "keynominal"; private static final String KEY_TANGGAL = "keytanggal"; private static final String KEY_KEGIATAN = "keykegiatan"; private static final String KEY_ID_WISHLIST = "keyidwishlist"; private static final String KEY_WISH = "keywish"; private static final String KEY_TAHUN = "keytahun"; private static final String KEY_HARGA = "keyharga"; private static com.arga.dompetku.SharedPrefManager mInstance; private static Context ctx; private SharedPrefManager(Context context) { ctx = context; } public static synchronized com.arga.dompetku.SharedPrefManager getInstance(Context context) { if (mInstance == null) { mInstance = new com.arga.dompetku.SharedPrefManager(context); } return mInstance; } //this method will store the user data in shared preferences public void userLogin(User user) { SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(KEY_ID_USER, user.getId()); editor.putString(KEY_USERNAME, user.getUsername()); editor.putString(KEY_FULLNAME, user.getFullname()); editor.putString(KEY_CITY, user.getCity()); editor.putInt(KEY_WALLET, user.getWallet()); editor.apply(); } public void addHistory(History history){ SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(KEY_ID_HISTORY, history.getId_history()); editor.putInt(KEY_ID_USER, history.getId_user()); editor.putString(KEY_JENIS, history.getJenis()); editor.putInt(KEY_NOMINAL, history.getNominal()); editor.putString(KEY_TANGGAL, history.getTanggal()); editor.putString(KEY_KEGIATAN, history.getKegiatan()); editor.apply(); } public History getListHistory(){ SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return new History( sharedPreferences.getInt(KEY_ID_HISTORY, -1), sharedPreferences.getInt(KEY_ID_USER, -1), sharedPreferences.getString(KEY_JENIS, null), sharedPreferences.getInt(KEY_NOMINAL, -1), sharedPreferences.getString(KEY_TANGGAL, null), sharedPreferences.getString(KEY_KEGIATAN, null) ); } public void addWishlist(Wishlist wishlist){ SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(KEY_ID_WISHLIST, wishlist.getId_wishlist()); editor.putInt(KEY_ID_USER, wishlist.getId_user()); editor.putString(KEY_WISH, wishlist.getWish()); editor.putInt(KEY_TAHUN, wishlist.getTahun()); editor.putInt(KEY_HARGA, wishlist.getHarga()); editor.apply(); } public Wishlist getWishlist(){ SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return new Wishlist( sharedPreferences.getInt(KEY_ID_WISHLIST, -1), sharedPreferences.getInt(KEY_ID_USER, -1), sharedPreferences.getString(KEY_WISH, null), sharedPreferences.getInt(KEY_TAHUN, -1), sharedPreferences.getInt(KEY_HARGA, -1) ); } //this method will checker whether user is already logged in or not public boolean isLoggedIn() { SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return sharedPreferences.getString(KEY_USERNAME, null) != null; } //this method will give the logged in user public User getUser() { SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return new User( sharedPreferences.getInt(KEY_ID_USER, -1), sharedPreferences.getString(KEY_USERNAME, null), sharedPreferences.getString(KEY_FULLNAME, null), sharedPreferences.getString(KEY_CITY, null), sharedPreferences.getInt(KEY_WALLET, -1) ); } //this method will logout the user public void logout() { SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.apply(); ctx.startActivity(new Intent(ctx, LoginActivity.class)); } }<file_sep>/app/src/main/java/com/arga/dompetku/ProfilActivity.java package com.arga.dompetku; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class ProfilActivity extends AppCompatActivity { ImageView btnHome, btnSetting, btnWallet; TextView fullname, username, city; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_profil); if(SharedPrefManager.getInstance(this).isLoggedIn()){ btnHome = findViewById(R.id.imageViewHome7); btnSetting = findViewById(R.id.imageViewSetting7); btnWallet = findViewById(R.id.imageViewWallet7); fullname = findViewById(R.id.viewFullName); username = findViewById(R.id.viewUsername); city = findViewById(R.id.viewCity); User user = SharedPrefManager.getInstance(this).getUser(); fullname.setText(String.valueOf(user.getFullname())); username.setText(String.valueOf(user.getUsername())); city.setText(String.valueOf(user.getCity())); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ProfilActivity.this, MainActivity.class); startActivity(intent); } }); btnWallet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ProfilActivity.this, WalletActivity.class); startActivity(intent); } }); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ProfilActivity.this, SettingActivity.class); startActivity(intent); } }); } else{ Intent intent = new Intent(ProfilActivity.this, LoginActivity.class); startActivity(intent); finish(); } } } <file_sep>/app/src/main/java/com/arga/dompetku/SettingActivity.java package com.arga.dompetku; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; public class SettingActivity extends AppCompatActivity { ImageView btnInformation, btnLogout, btnHome, btnWallet, btnProfile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); if(SharedPrefManager.getInstance(this).isLoggedIn()){ btnInformation = findViewById(R.id.imageViewInformation); btnLogout = findViewById(R.id.imageViewLogout); btnHome = findViewById(R.id.imageViewHome6); btnWallet = findViewById(R.id.imageViewWallet6); btnProfile = findViewById(R.id.imageViewProfile6); User user = SharedPrefManager.getInstance(this).getUser(); //btnLogout.setOnClickListener(this); //btnInformation.setOnClickListener(this); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SettingActivity.this, MainActivity.class); startActivity(intent); } }); btnWallet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SettingActivity.this, WalletActivity.class); startActivity(intent); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SettingActivity.this, ProfilActivity.class); startActivity(intent); } }); btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPrefManager.getInstance(getApplicationContext()).logout(); } }); btnInformation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SettingActivity.this, InformationActivity.class); startActivity(intent); } }); } else{ Intent intent = new Intent(SettingActivity.this, LoginActivity.class); startActivity(intent); finish(); } } // public void onClick(View view){ // if(view.equals(btnLogout)){ // SharedPrefManager.getInstance(getApplicationContext()).logout(); // } // else if(view.equals(btnInformation)){ // SettingActivity.this.finish(); // SettingActivity.this.startActivity(new Intent(SettingActivity.this.getApplicationContext(), InformationActivity.class)); // } // } } <file_sep>/app/src/main/java/com/arga/dompetku/AddPengeluaranActivity.java package com.arga.dompetku; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; public class AddPengeluaranActivity extends AppCompatActivity { EditText etNominal, etKegiatan; ImageView btnHome, btnWallet, btnSetting, btnProfile; Button btnSubmit; Integer id_user; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_pengeluaran_baru); if(SharedPrefManager.getInstance(this).isLoggedIn()){ etNominal = findViewById(R.id.imageView20); etKegiatan = findViewById(R.id.imageView21); btnHome = findViewById(R.id.imageViewHome10); btnWallet = findViewById(R.id.imageViewWallet10); btnSetting = findViewById(R.id.imageViewSetting10); btnProfile = findViewById(R.id.imageViewProfile10); btnSubmit = findViewById(R.id.button1); User user = SharedPrefManager.getInstance(this).getUser(); id_user = user.getId(); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { addPengeluaran(); AddPengeluaranActivity.this.finish(); AddPengeluaranActivity.this.startActivity(new Intent(AddPengeluaranActivity.this.getApplicationContext(), MainActivity.class)); } catch (ParseException e) { e.printStackTrace(); } } }); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddPengeluaranActivity.this, MainActivity.class); startActivity(intent); } }); btnWallet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddPengeluaranActivity.this, WalletActivity.class); startActivity(intent); } }); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddPengeluaranActivity.this, SettingActivity.class); startActivity(intent); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddPengeluaranActivity.this, ProfilActivity.class); startActivity(intent); } }); } else{ Intent intent = new Intent(AddPengeluaranActivity.this, LoginActivity.class); startActivity(intent); finish(); } } private void addPengeluaran() throws ParseException { String stringNominal = etNominal.getText().toString().trim(); if(TextUtils.isEmpty(stringNominal)){ etNominal.setError("Silahkan masukkan pendapatan anda"); etNominal.requestFocus(); return; } final Integer nominal = Integer.parseInt(stringNominal); final String kegiatan = etKegiatan.getText().toString().trim(); if(TextUtils.isEmpty(kegiatan)){ etKegiatan.setError("Silahkan masukkan kegiatan anda"); etKegiatan.requestFocus(); return; } StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_ADD_PENGELUARAN, new Response.Listener<String>(){ @Override public void onResponse(String response) { //Toast.makeText(AddPengeluaranActivity.this.getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show(); //System.out.print(response.toString()); try{ //Log.i("tagconvertstr", "["+response+"]"); JSONObject obj = new JSONObject(response); if (!obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); //getting the user from the response JSONObject listJson = obj.getJSONObject("list"); //creating a new user object History list = new History( listJson.getInt("id_history"), listJson.getInt("id_user"), listJson.getString("jenis"), listJson.getInt("nominal"), null, listJson.getString("kegiatan") ); SharedPrefManager.getInstance(getApplicationContext()).addHistory(list); } else{ Toast.makeText(AddPengeluaranActivity.this.getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e){ e.printStackTrace(); } } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error){ Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("id_user", id_user.toString()); params.put("nominal", nominal.toString()); params.put("kegiatan", kegiatan); return params; } }; VolleySingleton.getInstance(this).addToRequestQueue(stringRequest); } } <file_sep>/app/src/main/java/com/arga/dompetku/WalletActivity.java package com.arga.dompetku; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.Date; public class WalletActivity extends AppCompatActivity { ImageView btnHome, btnSetting, btnProfile; TextView wallet, tanggal; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_wallet); if(SharedPrefManager.getInstance(this).isLoggedIn()){ wallet = findViewById(R.id.textViewWallet2); btnHome = findViewById(R.id.imageViewHome5); btnSetting = findViewById(R.id.imageViewSetting5); btnProfile = findViewById(R.id.imageViewProfile5); tanggal = findViewById(R.id.textView2); User user = SharedPrefManager.getInstance(this).getUser(); wallet.setText("Rp." + String.valueOf(user.getWallet())); Date date = new Date(); tanggal.setText(date.toString()); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(WalletActivity.this, MainActivity.class); startActivity(intent); } }); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(WalletActivity.this, SettingActivity.class); startActivity(intent); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(WalletActivity.this, ProfilActivity.class); startActivity(intent); } }); } else{ Intent intent = new Intent(WalletActivity.this, LoginActivity.class); startActivity(intent); finish(); } } } <file_sep>/app/src/main/java/com/arga/dompetku/InformationActivity.java package com.arga.dompetku; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; public class InformationActivity extends AppCompatActivity { ImageView btnHome, btnWallet, btnSetting, btnProfile; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_information); if(SharedPrefManager.getInstance(this).isLoggedIn()){ btnHome = findViewById(R.id.imageViewHome8); btnWallet = findViewById(R.id.imageViewWallet8); btnSetting = findViewById(R.id.imageViewSetting8); btnProfile = findViewById(R.id.imageViewProfile8); User user = SharedPrefManager.getInstance(this).getUser(); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(InformationActivity.this, MainActivity.class); startActivity(intent); } }); btnWallet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(InformationActivity.this, WalletActivity.class); startActivity(intent); } }); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(InformationActivity.this, SettingActivity.class); startActivity(intent); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(InformationActivity.this, ProfilActivity.class); startActivity(intent); } }); } else{ Intent intent = new Intent(InformationActivity.this, LoginActivity.class); startActivity(intent); finish(); } } } <file_sep>/app/src/main/java/com/arga/dompetku/ListPengeluaranActivity.java package com.arga.dompetku; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ListPengeluaranActivity extends AppCompatActivity { ListView listView; List<History> pengeluaranList; Integer id_user; Button btnBack; ImageView btnHome, btnWallet, btnSetting, btnProfile; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_daftar_pengeluaran); listView = (ListView) findViewById(R.id.listPengeluaran); btnBack = findViewById(R.id.button5); btnHome = findViewById(R.id.imageViewHome13); btnWallet = findViewById(R.id.imageViewWallet13); btnSetting = findViewById(R.id.imageViewSetting13); btnProfile = findViewById(R.id.imageViewProfile13); pengeluaranList = new ArrayList<>(); showPengeluaran(); User user = SharedPrefManager.getInstance(this).getUser(); id_user = user.getId(); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListPengeluaranActivity.this, PengeluaranActivity.class); startActivity(intent); } }); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListPengeluaranActivity.this, MainActivity.class); startActivity(intent); } }); btnWallet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListPengeluaranActivity.this, WalletActivity.class); startActivity(intent); } }); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListPengeluaranActivity.this, SettingActivity.class); startActivity(intent); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListPengeluaranActivity.this, ProfilActivity.class); startActivity(intent); } }); } private void showPengeluaran(){ StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LIST_PENGELUARAN, new Response.Listener<String>(){ @Override public void onResponse(String response) { //Toast.makeText(LoginActivity.this.getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show(); //System.out.print(response.toString()); try{ JSONArray array = new JSONArray(response); //Toast.makeText(ListPendapatanActivity.this.getApplicationContext(), array.getString("message"), Toast.LENGTH_SHORT).show(); //Log.i("tagconvertstr", "["+response+"]"); //JSONArray array = obj.getJSONArray(""); for(int i = 0; i < array.length(); i++){ JSONObject pendObj = array.getJSONObject(i); History peng = new History(pendObj.getInt("nominal"), pendObj.getString("kegiatan")); pengeluaranList.add(peng); } PendapatanAdapter adapter = new PendapatanAdapter(pengeluaranList, getApplicationContext()); listView.setAdapter(adapter); } catch (JSONException e){ e.printStackTrace(); } } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error){ Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("id_user", id_user.toString()); return params; } }; VolleySingleton.getInstance(this).addToRequestQueue(stringRequest); } } <file_sep>/app/src/main/java/com/arga/dompetku/WishlistAdapter.java package com.arga.dompetku; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; public class WishlistAdapter extends ArrayAdapter<Wishlist> { private List<Wishlist> wishList; private Context mCtx; public WishlistAdapter(List<Wishlist> P, Context c){ super(c, R.layout.list_wishlist, P); this.wishList = P; this.mCtx = c; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(mCtx); View view = inflater.inflate(R.layout.list_wishlist,null,true); TextView kegiatan = (TextView) view.findViewById(R.id.textKegiatan); TextView tahun = (TextView) view.findViewById(R.id.textTahun); TextView nominal = (TextView) view.findViewById(R.id.textNominal1); Wishlist wishlist = wishList.get(position); kegiatan.setText(wishlist.getWish()); tahun.setText(String.valueOf(wishlist.getTahun())); nominal.setText(String.valueOf(wishlist.getHarga())); return view; } } <file_sep>/app/src/main/java/com/arga/dompetku/ListWishlistActivity.java package com.arga.dompetku; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ListWishlistActivity extends AppCompatActivity { ListView listView; List<Wishlist> wishList; Integer id_user; Button btnBack; ImageView btnHome, btnWallet, btnSetting, btnProfile; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_daftar_wishlist); listView = (ListView) findViewById(R.id.listWishlist); btnBack = findViewById(R.id.button6); btnHome = findViewById(R.id.imageViewHome14); btnWallet = findViewById(R.id.imageViewWallet14); btnSetting = findViewById(R.id.imageViewSetting14); btnProfile = findViewById(R.id.imageViewProfile14); wishList = new ArrayList<>(); showWishlist(); User user = SharedPrefManager.getInstance(this).getUser(); id_user = user.getId(); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListWishlistActivity.this, WishlistActivity.class); startActivity(intent); } }); btnHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListWishlistActivity.this, MainActivity.class); startActivity(intent); } }); btnWallet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListWishlistActivity.this, WalletActivity.class); startActivity(intent); } }); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListWishlistActivity.this, SettingActivity.class); startActivity(intent); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ListWishlistActivity.this, ProfilActivity.class); startActivity(intent); } }); } private void showWishlist(){ StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_WISHLIST, new Response.Listener<String>(){ @Override public void onResponse(String response) { //Toast.makeText(LoginActivity.this.getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show(); //System.out.print(response.toString()); try{ JSONArray array = new JSONArray(response); //Toast.makeText(ListPendapatanActivity.this.getApplicationContext(), array.getString("message"), Toast.LENGTH_SHORT).show(); //Log.i("tagconvertstr", "["+response+"]"); //JSONArray array = obj.getJSONArray(""); for(int i = 0; i < array.length(); i++){ JSONObject pendObj = array.getJSONObject(i); Wishlist peng = new Wishlist(pendObj.getString("wish"), pendObj.getInt("tahun"), pendObj.getInt("harga")); wishList.add(peng); } WishlistAdapter adapter = new WishlistAdapter(wishList, getApplicationContext()); listView.setAdapter(adapter); } catch (JSONException e){ e.printStackTrace(); } } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error){ Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("id_user", id_user.toString()); return params; } }; VolleySingleton.getInstance(this).addToRequestQueue(stringRequest); } } <file_sep>/app/src/main/java/com/arga/dompetku/MainActivity.java package com.arga.dompetku; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView fullname, wallet; ImageView btnWishlist, btnPendapatan, btnPengeluaran, btnHistory, btnWallet, btnSetting, btnProfile; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); if(SharedPrefManager.getInstance(this).isLoggedIn()){ fullname = findViewById(R.id.textViewFullname); wallet = findViewById(R.id.textViewWallet); btnWishlist = findViewById(R.id.imageViewWishlist); btnPendapatan = findViewById(R.id.imageViewPendapatan); btnPengeluaran = findViewById(R.id.imageViewPengeluaran); btnHistory = findViewById(R.id.imageViewHistory); btnWallet = findViewById(R.id.imageViewWallet); btnSetting = findViewById(R.id.imageViewSetting); btnProfile = findViewById(R.id.imageViewProfile); User user = SharedPrefManager.getInstance(this).getUser(); SharedPrefManager.getInstance(this).userLogin(user); fullname.setText(String.valueOf(user.getFullname())); wallet.setText("Rp." + String.valueOf(user.getWallet())); btnWishlist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WishlistActivity.class); startActivity(intent); } }); btnPendapatan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, PendapatanActivity.class); startActivity(intent); } }); btnPengeluaran.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, PengeluaranActivity.class); startActivity(intent); } }); btnHistory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ListHistory.class); startActivity(intent); } }); btnWallet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WalletActivity.class); startActivity(intent); } }); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SettingActivity.class); startActivity(intent); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ProfilActivity.class); startActivity(intent); } }); } else{ Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); finish(); } } }
c30b82adc5e2162759274b18c07c86b6341fbac9
[ "Java", "PHP" ]
11
PHP
aldillapramesta/DompetKu
9056952372cacc85c30573e5f043b44081140f37
b8752b42f6ff6b2174aeb2d1d07115733ea385e2
refs/heads/master
<file_sep>/*RoboticHand v1*/ #include <Encoder.h> // Change these pin numbers to the pins connected to your encoder. // Best Performance: both pins have interrupt capability // Good Performance: only the first pin has interrupt capability // Low Performance: neither pin has interrupt capability Encoder U1(20, 30); //UpRight Encoder U2(21, 31); //UPLeft Encoder D1(32, 33); //DownRight Encoder D2(34, 35); //DownLeft //Hbridges // U1 #Firstbranch Right int ENA=4;//pwm int IN1=22; int IN2=23; // U2 #Secondbrach Left int ENB=5;//pwm int IN3=24; int IN4=25; // D1 Right int ENC=6;//pwm int IN5=26; int IN6=27; // D2 Left int END=7;//pwm int IN7=28; int IN8=29; //Buttons int But1=40; //main int But2=39; //middle int But3=28; //grip //variables byte byteRead; int u=0; int j=0; int k=0; int pwmspeed=0; // //Initialisation void setup() { Serial.begin(115200); Serial.println("Test begin:"); pinMode(ENA,OUTPUT); //Pwm U1 pinMode(ENB,OUTPUT); //Pwm U2 pinMode(ENC,OUTPUT); //Pwm D1 pinMode(END,OUTPUT); //Pwm D1 pinMode(IN1,OUTPUT); //U1 pinMode(IN2,OUTPUT); //U1 pinMode(IN3,OUTPUT); //U2 pinMode(IN4,OUTPUT); //U2 pinMode(IN5,OUTPUT); //D1 pinMode(IN6,OUTPUT); //D1 pinMode(IN7,OUTPUT); //D2 pinMode(IN8,OUTPUT); //D2 pinMode(But1,INPUT_PULLUP); //main pinMode(But2,INPUT_PULLUP); //middle pinMode(But2,INPUT_PULLUP); //grip //Setting All Enable To Low digitalWrite(ENA,LOW); digitalWrite(ENB,LOW); digitalWrite(ENC,LOW); digitalWrite(END,LOW); } long positionLeft = -999; long positionRight = -999; void loop() { /*j=20000; k=1; MoveD1D2(j,k); delay(3000);*/ /* check if data has been sent from the computer: */ //if (Serial.available()) { Serial.println("waiting first num"); // read the most recent byte byteRead = Serial.read(); u=byteRead-48; Serial.write(byteRead); //ECHO the value that was read, back to the serial port. /* Serial.println("waiting second num"); Serial.write(byteRead); byteRead = Serial.read(); Serial.println("waiting third num"); Serial.write(byteRead); j=byteRead-48; byteRead = Serial.read(); Serial.write(byteRead); k=byteRead-48;*/ //} Serial.println("secondif"); if(u==1) { MoveU1(200,1); Serial.println("moving U1down"); } else if(u==2) { MoveU1(200,2); Serial.println("moving U1up"); } else if(u==3) { MoveU2(200,1); Serial.println("moving U2down"); } else if(u==4) { MoveU2(200,2); Serial.println("moving U2up"); } else if (u==5) { MoveD1D2(200,1); Serial.println("moving D1D2down"); } else if (u==6) { MoveD1D2(200,2); Serial.println("moving D1D2up"); } /*long newLeft, newRight; newLeft = RLeft.read(); newRight = RRight.read(); if (newLeft != positionLeft || newRight != positionRight) { Serial.print("Left = "); Serial.print(newLeft); Serial.print(", Right = "); Serial.print(newRight); Serial.println(); positionLeft = newLeft; positionRight = newRight; } // if a character is sent from the serial monitor, // reset both back to zero. if (Serial.available()) { Serial.read(); Serial.println("Reset both knobs to zero"); RLeft.write(0); RRight.write(0); }*/ } void MoveU1(int x, int y){ //x=steps,y=witchwaytoturn(1=right=down,2=left=up) Serial.println("mpika"); if(y==1) { Serial.println("11111111"); digitalWrite(IN1,HIGH); //high-down/low-up digitalWrite(IN2,LOW); //low-down/high-up int pos = U1.read(); int finalpos=pos+x; while(pos<=finalpos) { pos = U1.read(); if((finalpos-pos)>100) { analogWrite(ENA,200); pos = U1.read(); } else { analogWrite(ENA,170); pos = U1.read(); } } } else if (y==2) { Serial.println("222222222222"); digitalWrite(IN1,LOW); //high-down/low-up digitalWrite(IN2,HIGH); //low-down/high-up int pos = U1.read(); int finalpos=pos-x; while(pos>=finalpos && digitalRead(But1)==HIGH) { pos = U1.read(); if((pos-finalpos)>100) { analogWrite(ENA,200); pos = U1.read(); } else { analogWrite(ENA,170); pos = U1.read(); } } } else { return; } analogWrite(ENA,0); if(digitalRead(But1)==LOW) { U1.write(0); } return; } void MoveU2(int x, int y){ //x=steps,y=witchwaytoturn(1=right=down,2=left=up) if(y==1) { digitalWrite(IN3,HIGH); //high-down/low-up digitalWrite(IN4,LOW); //low-down/high-up int pos = U2.read(); int finalpos=pos-x; while(pos>=finalpos && digitalRead(But2)==HIGH) { pos = U2.read(); if((pos-finalpos)>100) { analogWrite(ENB,200); pos = U2.read(); } else { analogWrite(ENB,170); pos = U2.read(); } } } else if (y==2) { digitalWrite(IN3,LOW); //high-down/low-up digitalWrite(IN4,HIGH); //low-down/high-up int pos = U2.read(); int finalpos=pos+x; while(pos<=finalpos) { pos = U2.read(); if((finalpos-pos)>100) { analogWrite(ENB,200); pos = U2.read(); } else { analogWrite(ENB,170); pos = U2.read(); } } } else { return; } analogWrite(ENB,0); if(digitalRead(But2)==LOW) { U2.write(0); } return; } void MoveD1D2(int x, int y){ //x=steps,y=witchwaytoturn(1=right=down,2=left=up) int pos1=0; int pos2=0; if(y==1) { digitalWrite(IN5,HIGH); //high-down/low-up digitalWrite(IN6,LOW); //low-down/high-up digitalWrite(IN7,HIGH); //high-down/low-up digitalWrite(IN8,LOW); //low-down/high-up int finalpos1=pos1+x; int finalpos2=pos2+x; while(pos1<=finalpos1 && pos2<=finalpos2) { pos1 = D1.read(); pos2 = D2.read(); if((finalpos1-pos1)>100 && (finalpos2-pos2)>100) { analogWrite(ENC,200); analogWrite(END,200); pos1 = D1.read(); pos2 = D2.read(); } else { analogWrite(ENC,170); analogWrite(END,170); pos1 = D1.read(); pos2 = D2.read(); } } } else if (y==2) { digitalWrite(IN5,LOW); //high-down/low-up digitalWrite(IN6,HIGH); //low-down/high-up digitalWrite(IN7,LOW); //high-down/low-up digitalWrite(IN8,HIGH); //low-down/high-up int finalpos1=pos1-x; int finalpos2=pos2-x; while(pos1>=finalpos1 && pos2>=finalpos2 && digitalRead(But3)==HIGH) { pos1 = D1.read(); pos2 = D2.read(); if((pos1-finalpos1)>100 &&(pos2-finalpos2)>100) { analogWrite(ENC,200); analogWrite(END,200); pos1 = D1.read(); pos2 = D2.read(); } else { analogWrite(ENC,170); analogWrite(END,170); pos1 = D1.read(); pos2 = D2.read(); } } } else { return; } analogWrite(ENC,0); analogWrite(END,0); if(digitalRead(But3)==LOW) { D1.write(0); D1.write(0); } return; } void SafeZone() { while(digitalRead(But1)!=LOW && digitalRead(But2)!=LOW && digitalRead(But3)!=LOW) { // statement analogWrite(ENA,0); analogWrite(ENB,0); analogWrite(ENC,0); analogWrite(END,0); if(digitalRead(But1)==HIGH && digitalRead(But2)==HIGH && digitalRead(But3)==HIGH) { digitalWrite(IN1,LOW); //high-down/low-up digitalWrite(IN2,HIGH); //low-down/high-up analogWrite(ENA,200); } else if(digitalRead(But2)==HIGH && digitalRead(But3)==HIGH) { digitalWrite(IN1,HIGH); //high-down/low-up digitalWrite(IN2,LOW); //low-down/high-up analogWrite(ENB,200); } else if (digitalRead(But3)==HIGH) { digitalWrite(IN5,LOW); //high-down/low-up digitalWrite(IN6,HIGH); //low-down/high-up digitalWrite(IN7,LOW); //high-down/low-up digitalWrite(IN8,HIGH); //low-down/high-up analogWrite(ENC,200); analogWrite(END,200); } else if (digitalRead(But3)==LOW) { MoveD1D2(250,1); } } analogWrite(ENA,0); analogWrite(ENB,0); analogWrite(ENC,0); analogWrite(END,0); U1.write(0); U2.write(0); D1.write(0); D2.write(0); }
b5ff41b47c0e024acec78a935f85aeef2cfea345
[ "C++" ]
1
C++
kwdi/robotichand_robo2000
50984e59057f717df786ad551876631c394d09a9
11d0c18b89b7a8d189e4180ff72987135e09fea9
refs/heads/master
<file_sep>import React from "react"; import Project from "./Project/Project"; import "./Projects.scss"; function Projects() { return ( <div className="projects" id="projects"> <h1 className="projects__title">PROJECTS</h1> <div className="container"> <Project title="Scientify" image="Scientify" github="https://github.com/adina-hub/MyExperiment/tree/develop" website="https://myexperiment-c6404.web.app/" /> <Project title="Linkedin Clone" image="LinkedinClone" align="right" github="https://github.com/AndreiManea/linkedin-clone" website="https://linkedin-clone-4fb93.web.app/" /> <Project title="Pizza Noastra" image="Pizza Noastra" github="https://github.com/AndreiManea/Pizza-Noastra" website="https://pizzanoastra.ro/acasa" /> <Project title="COVID-19 Tracker" image="COVID19 Tracker" align="right" github="https://github.com/AndreiManea/COVID19-Tracker" website="https://covid19-tracker-a0829.web.app/" /> <Project title="Spotify Clone" image="Spotify Clone" github="https://github.com/AndreiManea/Spotify-Clone" website="https://spotify-clone-a04f0.web.app/" /> </div> </div> ); } export default Projects; <file_sep>import React from "react"; import "./Project.scss"; import GitHubIcon from "@material-ui/icons/GitHub"; import LanguageIcon from "@material-ui/icons/Language"; function Project({ image, title, align, github, website }) { return ( <div className="projectWrapper"> {align ? ( <div className="project project--right"> <div className="project__container"> <h2 className="project__title project__title--right">{title}</h2> <div className="project__buttons"> <a href={github} className="project__button" target="_blank"> <GitHubIcon /> GitHub </a> <a href={website} className="project__button" target="_blank"> <LanguageIcon /> Website </a> </div> </div> <div className="image-container"> <img src={require(`../../../assets/Images/${image}.png`)} alt="" className="image-container__image" /> <div className="image-container__info"> <a href={github} className="icon" target="_blank"> <GitHubIcon /> <h3 className="icon__title icon__title-github">GitHub</h3> </a> <a href={website} className="icon" target="_blank"> <LanguageIcon /> <h3 className="icon__title">Website</h3> </a> </div> </div> </div> ) : ( <div className="project"> <div className="image-container"> <img src={require(`../../../assets/Images/${image}.png`)} alt="" className="image-container__image" /> <div className="image-container__info"> <a href={github} className="icon" target="_blank"> <GitHubIcon /> <h3 className="icon__title icon__title-github">GitHub</h3> </a> <a href={website} className="icon" target="_blank"> <LanguageIcon /> <h3 className="icon__title">Website</h3> </a> </div> </div> <div className="project__container"> <h2 className="project__title">{title}</h2> <div className="project__buttons"> <a href={github} className="project__button" target="_blank"> <GitHubIcon /> GitHub </a> <a href={website} className="project__button" target="_blank"> <LanguageIcon /> Website </a> </div> </div> </div> )} </div> ); } export default Project; <file_sep>import React from "react"; import "./Skills.scss"; function Skills() { return ( <div className="skills" id="skills"> <img src={require("../../assets/Images/Skills.svg")} alt="" className="skills__image" /> <div className="info"> <h1 className="info__title">SKILLS</h1> <p className="info__description"> When it comes to skills, depending on the project, I like to create websites or applications using the technologies in the illustration. </p> <p className="info__description"> If I had to pick a favorite, that would be <span style={{ color: "#08FDD8" }}> React.js </span> because of the community and support behind it. </p> </div> </div> ); } export default Skills; <file_sep>import React from "react"; import "./Experience.scss"; function Experience() { return ( <div className="experience" id="experience"> <h1 className="experience__title">EXPERIENCE</h1> <img src={require("../../assets/Images/Experience.svg")} alt="" className="experience__image" /> </div> ); } export default Experience; <file_sep>import React, { useEffect, useRef, useState } from "react"; import "./Navbar.scss"; import { Squash as Hamburger } from "hamburger-react"; import { Link, animateScroll as scroll } from "react-scroll"; import { TweenMax, Power3 } from "gsap"; import GitHubIcon from "@material-ui/icons/GitHub"; import InstagramIcon from "@material-ui/icons/Instagram"; import LinkedInIcon from "@material-ui/icons/LinkedIn"; function Navbar() { const [active, setActive] = useState(false); let navbar = useRef(null); useEffect(() => { TweenMax.to(navbar, 1, { opacity: 1, delay: 2, ease: Power3.easeOut, }); }, []); return ( <div className="navbar-mobile" ref={(el) => (navbar = el)}> <div className="navbar-mobile__button"> <Hamburger size={40} toggled={active} toggle={setActive} /> </div> <div className={active ? "navbar-mobile__menu" : "navbar-mobile__menu--hide"} > <Link to="about" spy={true} smooth={true} offset={0} duration={500} onClick={() => setActive(false)} className="navbar-mobile__link" > About </Link> <Link to="experience" spy={true} smooth={true} offset={window.innerWidth > 768 ? -140 : 0} duration={500} onClick={() => setActive(false)} className="navbar-mobile__link" > Experience </Link> <Link to="projects" spy={true} smooth={true} offset={window.innerWidth > 768 ? -100 : 0} duration={500} onClick={() => setActive(false)} className="navbar-mobile__link" > Projects </Link> <Link to="skills" spy={true} smooth={true} offset={0} onClick={() => setActive(false)} duration={800} className="navbar-mobile__link" > Skills </Link> <Link to="contact" spy={true} smooth={true} offset={0} duration={1000} onClick={() => setActive(false)} className="navbar-mobile__link" > Contact </Link> <div className="navbar-mobile__social-media"> <a className="navbar-mobile__icon-link" href="https://github.com/AndreiManea" target="_blank" > <GitHubIcon className="navbar-mobile__icon" /> </a> <a className="navbar-mobile__icon-link" href="https://www.instagram.com/andrei.codes/" target="_blank" > <InstagramIcon className="navbar-mobile__icon" /> </a> <a className="navbar-mobile__icon-link" href="https://www.linkedin.com/in/andrei-manea-b422b8170/" target="_blank" > <LinkedInIcon className="navbar-mobile__icon" /> </a> </div> </div> </div> ); } export default Navbar; <file_sep>import React, { useRef, useEffect } from "react"; import ArrowForwardIcon from "@material-ui/icons/ArrowForward"; import GitHubIcon from "@material-ui/icons/GitHub"; import InstagramIcon from "@material-ui/icons/Instagram"; import LinkedInIcon from "@material-ui/icons/LinkedIn"; import { TweenMax, Power3 } from "gsap"; import { Link, animateScroll as scroll } from "react-scroll"; import "./Hero.scss"; function Hero() { let animate = { title: useRef(null), description: useRef(null), portofolioLink: useRef(null), portofolioImage1: useRef(null), portofolioImage2: useRef(null), }; useEffect(() => { TweenMax.to(animate.title, 1, { opacity: 1, delay: 0.5, ease: Power3.easeOut, }); TweenMax.to(animate.description, 1, { opacity: 1, delay: 0.8, ease: Power3.easeOut, }); TweenMax.to(animate.portofolioLink, 1, { opacity: 1, delay: 1.1, ease: Power3.easeOut, }); TweenMax.to(animate.portofolioImage1, 1, { opacity: 0.75, delay: 1.4, ease: Power3.easeOut, }); TweenMax.to(animate.portofolioImage2, 1, { opacity: 0.75, delay: 1.7, ease: Power3.easeOut, }); }, []); return ( <div className="hero"> <div className="navbar"> <Link to="about" spy={true} smooth={true} offset={0} duration={500} className="navbar__link" > About </Link> <Link to="experience" spy={true} smooth={true} offset={window.innerWidth > 768 ? -140 : 0} duration={500} className="navbar__link" > Experience </Link> <Link to="projects" spy={true} smooth={true} offset={window.innerWidth > 768 ? -100 : 0} duration={500} className="navbar__link" > Projects </Link> <Link to="skills" spy={true} smooth={true} offset={0} duration={800} className="navbar__link" > Skills </Link> <Link to="contact" spy={true} smooth={true} offset={0} duration={1000} className="navbar__link" > Contact </Link> </div> <div className="sidebar"> <a className="sidebar__link" href="https://github.com/AndreiManea" target="_blank" > <GitHubIcon /> </a> <a className="sidebar__link" href="https://www.instagram.com/andrei.codes/" target="_blank" > <InstagramIcon /> </a> <a className="sidebar__link" href="https://www.linkedin.com/in/andrei-manea-b422b8170/" target="_blank" > <LinkedInIcon /> </a> </div> <div className="hero__center"> <div className="banner"> <h1 className="banner__title" ref={(el) => (animate.title = el)}> <NAME> </h1> <h3 className="banner__description" ref={(el) => (animate.description = el)} > FULL-STACK DEVELOPER </h3> </div> <div className="portofolio"> <div className="portofolio__link-wrapper" ref={(el) => (animate.portofolioLink = el)} > <Link to="projects" spy={true} smooth={true} offset={-100} duration={500} className="portofolio__link" > <span>See My Portofolio </span> <ArrowForwardIcon /> </Link> </div> <div className="portofolio__images"> <Link to="projects" spy={true} smooth={true} offset={-100} duration={500} > <img src={require("../../assets/Images/Pizza Noastra.png")} ref={(el) => (animate.portofolioImage1 = el)} /> </Link> <Link to="projects" spy={true} smooth={true} offset={-100} duration={500} > <img src={require("../../assets/Images/COVID19 Tracker.png")} ref={(el) => (animate.portofolioImage2 = el)} /> </Link> </div> </div> </div> </div> ); } export default Hero; <file_sep>import React from "react"; import "./About.scss"; import GetAppIcon from "@material-ui/icons/GetApp"; function About() { return ( <div className="about" id="about"> <div className="about__divider"></div> <div className="container"> <div className="container__left"> <div className="image"> <div className="image__photo" alt=""></div> <div className="image__background"></div> </div> </div> <div className="container__right"> <div className="information"> <h3 className="information__section">ABOUT</h3> <h2 className="information__title">PASSIONATE</h2> <p className="information__description"> Freshly BSc computer science graduate, if there's one thing I love doing, that would be designing and developing websites. Through my career, I've always tried to improve and be better. I'm a fast learner with a lot of potential and room for growth. </p> <p className="information__description information__description--last"> Besides the technical part of this industry, I think it's very important to be empathic and compassionate. This helped me breathe more life into my websites and designs because I could better understand the problems or the requirements customers had. </p> <a href="/Andrei_Manea_Resume.pdf" download> <button className="information__CV"> <GetAppIcon /> Download Resume </button> </a> </div> </div> </div> </div> ); } export default About; <file_sep># Portofolio <p>Portofolio website built using <strong>React.js </strong>. </p> <p><strong> Styling </strong> was done using <strong> SCSS </strong>. </p> <p><strong>Packages</strong> used: </p> <ul> <li><strong>react-scroll</strong> for smooth scrolling on the links</li> <li><strong>gsap</strong> for text animations</li> <li><strong>emailjs-com</strong> for making Contact Form work and send email to me</li> <li><strong>formik</strong> for handling Contact Form input</li> <li><strong>yup</strong> for Contact Form error handling and better structuring with formik </li> <li><strong>node-sass</strong> in order to be able to use .scss files </ul> <p><strong>Deployment</strong> done using <strong>Firebase</strong>.</p> <p><strong>Live Link:</strong> https://portofolio-9021f.web.app/</p> <file_sep>import React, { useState } from "react"; import "./Contact.scss"; import { useFormik } from "formik"; import emailjs from "emailjs-com"; import * as Yup from "yup"; function Contact() { const [messageSent, setMessageSent] = useState(null); const validationSchema = Yup.object({ name: Yup.string().required("Name field required"), email: Yup.string() .email("Invalid email format") .required("Email field required"), subject: Yup.string().required("Subject field required"), message: Yup.string() .min(30, "Message should be atleast 30 characters") .required("Message field required"), }); const formik = useFormik({ initialValues: { name: "", email: "", subject: "", message: "", }, onSubmit: (values) => { setMessageSent( <p className="form__message-sent"> Message Sent, thank you for your interest :) </p> ); setTimeout(() => { setMessageSent(null); }, 1500); emailjs.send(serviceId, templateId, values, userId).then( (response) => { console.log("SUCCESS!", response.status, response.text); }, (error) => { console.log("FAILED...", error); } ); formik.resetForm(); }, validationSchema, }); const serviceId = "service_997d53r"; const templateId = "template_hcdo0oe"; const userId = "user_yKAWvujYWjBNocDgFstNW"; return ( <div className="contact"> <div className="info"> <h1 className="info__title">Contact me</h1> <p className="info__description"> I am interested in freelance opportunities - especially ambitious or large projects. However, if you have other requests or questions, don’t hesitate to contact me using the form below either and I'll get back to you as soon as possible. </p> <form action="" className="form" onSubmit={formik.handleSubmit}> <div className="form__container"> <div className="form__control"> <input type="text" name="name" value={formik.values.name} className="form__name" placeholder="Name" onChange={formik.handleChange} onBlur={formik.handleBlur} /> <p className={ formik.touched.name && formik.errors.name ? "form__error--show" : "form__error" } > {formik.touched.name && formik.errors.name ? formik.errors.name : "."} </p> </div> <div className="form__control form__control--email"> <input type="email" name="email" value={formik.values.email} className="form__email" placeholder="Email" onChange={formik.handleChange} onBlur={formik.handleBlur} /> <p className={ formik.touched.email && formik.errors.email ? "form__error--show" : "form__error" } > {formik.touched.email && formik.errors.email ? formik.errors.email : "."} </p> </div> </div> <input type="text" name="subject" value={formik.values.subject} className="form__subject" placeholder="Subject" onChange={formik.handleChange} onBlur={formik.handleBlur} /> <p className={ formik.touched.subject && formik.errors.subject ? "form__error--show" : "form__error" } > {formik.touched.subject && formik.errors.subject ? formik.errors.subject : "."} </p> <textarea row="10" cols="40" name="message" value={formik.values.message} className="form__text-area" placeholder="Message" onChange={formik.handleChange} onBlur={formik.handleBlur} ></textarea> <p className={ formik.touched.message && formik.errors.message ? "form__error--show" : "form__error" } > {formik.touched.message && formik.errors.message ? formik.errors.message : "."} </p> <button id="contact" className="form__send" type="submit"> SEND </button> {messageSent} </form> </div> <div className="contact__image--wrapper"> <div alt="" className="contact__image"></div> </div> </div> ); } export default Contact;
f54768927fcd392e1bd71c6997a2172a75f59a37
[ "JavaScript", "Markdown" ]
9
JavaScript
AndreiManea/Portofolio
3f447932ce8862253fe58aea7ff64115c8efb097
dcd8c4d43df978cd879a4b51fabab379a9ecb808
refs/heads/main
<file_sep>const UTTT = require('@socialgorithm/ultimate-ttt').default; const ME = require("@socialgorithm/ultimate-ttt/dist/model/constants").ME; const OPPONENT = require("@socialgorithm/ultimate-ttt/dist/model/constants").OPPONENT; const getCloseablePositions = require("./utilsminimax"); const Move = require('./Move.js'); class GameLogic { constructor(player, size = 3){ if(!player || player < ME || player > OPPONENT){ throw new Error('Invalid player'); } this.startTime = Date.now(); this.size = size; this.player = player; this.opponent = 1 - player; this.maxTime = 100 this.maxDepth = 3; this.init(); } /* ----- Required methods ----- */ init(){ this.game = new UTTT(this.size); } addOpponentMove(board, move) { try { this.game = this.game.addOpponentMove(board, move); } catch (e) { console.error('-------------------------------'); console.error("\n"+'AddOpponentMove: Game probably already over when adding', board, move, e); console.error("\n"+this.game.prettyPrint()); console.error("\n"+this.game.stateBoard.prettyPrint(true)); console.error('-------------------------------'); throw new Error(e); } } addMove(board, move){ try { this.game = this.game.addMyMove(board, move); } catch (e) { console.error('-------------------------------'); console.error("\n"+'AddMyMove: Game probably already over when adding', board, move, e); console.error("\n"+this.game.prettyPrint()); console.error("\n"+this.game.stateBoard.prettyPrint(true)); console.error('-------------------------------'); throw new Error(e); } } getMove(){ const validBoards = this.game.getValidBoards(); /** * Try to find either winning or losing positions * These are when you/opponent have 2 in a row and there's one unoccupied place * Algo prefers moving there first and then falls back to the first available position */ if(validBoards.length === 1){ console.log("MINIMAX COMMENCES"); const boardMiniMax = this.game.board[validBoards[0][0]][validBoards[0][1]]; return { board: validBoards[0], move: this.findPosition(boardMiniMax) } } if(validBoards.length === 9){ const boardFirstMove = this.game.board[validBoards[4][0]][validBoards[4][1]]; console.log("FIRST MOVE MIDDLE"); return{ board: validBoards[4], move: this.findPositionFirstMove(boardFirstMove) } } const weightedMoves = validBoards.map((boardCoords) => { const board = this.game.board[boardCoords[0]][boardCoords[1]].board; const opponentWinningPositions = getCloseablePositions(board, this.opponent); if (opponentWinningPositions.length > 0) { return { board: boardCoords, move: opponentWinningPositions[0].coordinates }; } const myWinningPositions = getCloseablePositions(board, this.player); if (myWinningPositions.length > 0) { return { board: boardCoords, move: myWinningPositions[0].coordinates } } return null }).filter(move => move != null); if (weightedMoves.length > 0) { return weightedMoves[0] } //fall back to the first available logic var board = this.game.board[validBoards[0][0]][validBoards[0][1]]; return { board: validBoards[0], move: this.findPositionFirstAvailable(board) }; } timeout() { // YOU HAVE TIMED OUT // YOU MAY WANT TO RESPOND // return (Date.now() - this.startTime < this.maxTime - 5) ? false : true return false } // RESULT IS "win" | "lose" | "tie" // MOVE WILL TELL YOU LAST MOVE IF LOST gameOver(result, move) { // GAME IS OVER, OPPONENT WONT CHANGE } // RESULT IS "win" | "lose" | "tie" // MOVE WILL TELL YOU LAST MOVE IF LOST matchOver(result, move) { // MATCH IS OVER, OPPONENT MAY CHANGE } /* ---- Non required methods ----- */ /** * Get a random position to play in a board * @param board Board identifier [row, col] * @returns {[number,number]} Position coordinates [row, col] */ findPosition(board) { if (board.isFull() || board.isFinished()) { console.error('This board is full/finished', board); console.error(board.prettyPrint()); return; } const validMoves = board.getValidMoves(); if (validMoves.length === 0) { // this case should never happen :) throw new Error('Error: There are no moves available on this board'); } else{ var moveArray = []; validMoves.forEach((move,index) =>{ moveArray.push(new Move(0,board,index)); }); var bestNode; var scoreMap = new Map() if(this.player){ console.log('player : us ? :' + this.player); bestNode = this.minimax(moveArray,5,-Infinity,Infinity, true, board, scoreMap); } else if(this.opponent){ console.log('player : opp ? :' + this.player); bestNode = this.minimax(moveArray,5,-Infinity,Infinity, false,board, scoreMap); } var maxValue = 0; var bestKey = 4; console.log(scoreMap) for (let key of scoreMap.keys()) { var value = scoreMap.get(key) if( value > maxValue){ bestKey = key } maxValue = (!maxValue || maxValue < value) ? value : maxValue; console.log('max value: ' + maxValue) } console.log('best move: ' + bestKey) return validMoves[bestKey]; } } findPositionFirstAvailable(board) { if (board.isFull() || board.isFinished()) { console.error('This board is full/finished', board); console.error(board.prettyPrint()); return; } const validMoves = board.getValidMoves(); if (validMoves.length === 0) { // this case should never happen :) throw new Error('Error: There are no moves available on this board'); } // return validMoves[Math.floor(Math.random() * validMoves.length)]; return validMoves[0]; } findPositionFirstMove(board) { if (board.isFull() || board.isFinished()) { console.error('This board is full/finished', board); console.error(board.prettyPrint()); return; } const validMoves = board.getValidMoves(); if (validMoves.length === 0) { // this case should never happen :) throw new Error('Error: There are no moves available on this board'); } // return validMoves[Math.floor(Math.random() * validMoves.length)]; return validMoves[4]; } minimax(moves, currentDepth, alpha, beta, maximizingPlayer,board, scoreMap){ var bestScore; console.log('minimax') // if (this.timeout() === false){ console.log('timeout') if(currentDepth === 0 || moves.length === 0){ // evaluate console.log('down') bestScore = this.evaluate(board); return bestScore; } if(maximizingPlayer){ //let bestScore = -Infinity; for(var move in moves){ bestScore = Math.max(bestScore, this.minimax(move, currentDepth - 1, alpha, beta, false, board, scoreMap)) alpha = Math.max(alpha, bestScore) console.log('max') console.log('move: ' + move + ' score: ' + bestScore) console.log('current move minimax: ' + move + ' score: ' + bestScore) scoreMap.set(move, bestScore) if(bestScore >= beta){ return; } } return bestScore; }else{ //let bestScore = Infinity let bestNode; for(var move in moves){ bestScore = Math.min(bestScore, this.minimax(move, currentDepth - 1, alpha, beta, true, board, scoreMap)) scoreMap.set(move, bestScore) console.log('min') console.log('move: ' + move + ' score: ' + bestScore) console.log('current move minimax: ' + move + ' score: ' + bestScore) beta = Math.min(beta, bestScore) if (bestScore <= alpha){ return; } } return bestScore; } // }else{ // return; // } } evaluate(board) { var score = 0; // Evaluate score for each of the 8 lines (3 rows, 3 columns, 2 diagonals) score += this.evaluateLine(0, 0, 0, 1, 0, 2, board); // row 0 score += this.evaluateLine(1, 0, 1, 1, 1, 2, board); // row 1 score += this.evaluateLine(2, 0, 2, 1, 2, 2, board); // row 2 score += this.evaluateLine(0, 0, 1, 0, 2, 0, board); // col 0 score += this.evaluateLine(0, 1, 1, 1, 2, 1, board); // col 1 score += this.evaluateLine(0, 2, 1, 2, 2, 2, board); // col 2 score += this.evaluateLine(0, 0, 1, 1, 2, 2, board); // diagonal score += this.evaluateLine(0, 2, 1, 1, 2, 0, board); // alternate diagonal return score; } evaluateLine(row1, col1, row2, col2, row3, col3, board) { var score = 0; const validMoves = board.getValidMoves(); // board = [undef] // First cell if (validMoves[row1][col1] === this.player) { score = 1; } else if (validMoves[row1][col1] === this.opponent) { score = -1; } // Second cell if (validMoves[row2][col2] === this.player) { if (score == 1) { // cell1 is mySeed score = 10; } else if (score == -1) { // cell1 is oppSeed return 0; } else { // cell1 is empty score = 1; } } else if (validMoves[row2][col2] === this.opponent) { if (score == -1) { // cell1 is oppSeed score = -10; } else if (score == 1) { // cell1 is mySeed return 0; } else { // cell1 is empty score = -1; } } // Third cell if (validMoves[row3][col3] === this.player) { if (score > 0) { // cell1 and/or cell2 is mySeed score *= 10; } else if (score < 0) { // cell1 and/or cell2 is oppSeed return 0; } else { // cell1 and cell2 are empty score = 1; } } else if (validMoves[row3][col3] === this.opponent) { if (score < 0) { // cell1 and/or cell2 is oppSeed score *= 10; } else if (score > 1) { // cell1 and/or cell2 is mySeed return 0; } else { // cell1 and cell2 are empty score = -1; } } return score; } } module.exports = GameLogic;<file_sep>module.exports = class Move { // class methods constructor(value, board, index) { this.miniMaxValue = value; this.boardToPlay = board; this.index = index; } get getValue() { return this._value; } set setValue(value) { this._value = value; } get getBoard(){ return this._boardToPlay; } set setBoard(board){ this._boardToPlay = board; } get getIndex(){ return this._index; } set setIndex(index){ this._index = index; } };
955bf2788c1b88e2f059a2fb1b2bb8635afea788
[ "JavaScript" ]
2
JavaScript
liangel02/UltimateTicTacToe
d715da7d634cba9b886d6913bc961e0be486304e
87286a1d3b7dfa89ef6602f433f27eb6ec26cc88
refs/heads/master
<file_sep>//wait until the HTML document is ready $(document).ready(function(){ //select all the slides (array) var slides = $('.slide'); //set the index slide (number) var slideIndex = 0; //what's the current slide?(indexing into an array) var currentSlide = slides[slideIndex]; //hide all slides slides.hide(); //show the first one slides.first().show(); //when a user clicks next (function) $('.next').click(function(){ $(currentSlide).hide(); slideIndex++; if (slideIndex > 4){ slideIndex = 0; } currentSlide = slides[slideIndex]; $(currentSlide).show(); }); //when a user clicks previous (function) $('.previous').click(function(){ $(currentSlide).hide(); slideIndex--; if(slideIndex < 0){ slideIndex = 4; } currentSlide = slides[slideIndex]; $(currentSlide).show(); }); });
b83118ebb2028cf24f153b02047b20acccff2324
[ "JavaScript" ]
1
JavaScript
cmiller1213/gallery-updated
4a943c95566148575a073ca37e804320dc8a60a3
cbfc9663611836a328bfe5e6667c89a1cc803661
refs/heads/master
<file_sep>$(function(){ $.ajax({ type:"get", url:"http://127.0.0.1:3000/api/getindexmenu", dataType:"json", success:function(data){ //把数据变成html片段 将数据和模板结合起来生成html片段 var html = template("menu-template",data); $("#menu").html(html); //把最后几个div隐藏起来 $("#menu > .row > div:nth-last-of-type(-n+4)").css({ height:"0px" }); var normalHeight = $("#menu > .row > div:nth-of-type(8)").height(); //设置点击事件,一定是要在这个元素存在的情况之下进行设置 $("#menu > .row > div:nth-of-type(8) > a").click(function(){ //最后一个元素的高度是一直在变化的,所以我们只有在点击事件这个触发条件发生的时候再去获取最新的最后一个元素的高度 var lastElementHeight = $("#menu > .row > div:last-of-type").height(); //判断当前的状态 if(lastElementHeight == 0) { $("#menu > .row > div:nth-last-of-type(-n+4)").css({ height:normalHeight + "px" }); } else { $("#menu > .row > div:nth-last-of-type(-n+4)").css({ height:"0px" }); } return false; }); } }); $.ajax({ type:"get", url:"http://127.0.0.1:3000/api/getmoneyctrl", dataType:"json", success:function(data){ var html = template("product-list-template",data); $("#recommend > .recommend-list").html(html); } }); // var btn; // btn.onclick = function(){ // //xxxxxxx // function haha(){ // } // haha(); // }; // haha(); // window.onload = function(){ // function hehe(){ // } // hehe(); // } // hehe(); }); <file_sep>$(function() { //模拟一下网络的延迟 //以下的代码是国内折扣真实的实现代码 // setTimeout(function(){ // $.ajax({ // url:"http://127.0.0.1:3000/api/getinlanddiscount", // dataType:"json", // success:function(data){ // console.log(data); // var html = template("inlanddiscount-product-list-template",data); // $("#product > .product-list").html(html); // //隐藏加载中的效果 // $("#product > .loading-info > img").css({ // display:"none" // }); // $("#product > .loading-info > .loading-tips").css({ // display:"block" // }); // } // }); // },2000); //-------------------------------------------------------------------- //以下的代码是为了实现滑动加载下一页的效果,而使用另外一个接口,分类下的商品列表接口 var pageId = 1; var totalPage = 0; var isLoading = false; //在界面的入口函数中,要调用一次getProductList,把第一页的数据加载出来 getProductList(); //考虑在什么时机对pageId进行+1的操作,+1完之后,再次的获取服务器的数据 //时机?什么时候能够滑动到界面的底部 $(window).scroll(function() { //怎么知道滚动到底部了 // 完整的高度=可见区域的高度+滚动的高度 var totalHeight = $(document).height(); var visibleHeight = $(window).height(); // console.log(totalHeight,visibleHeight); var scrollTop = $(window).scrollTop(); var footerHeight = $("#footer").height() if (visibleHeight + scrollTop >= totalHeight - footerHeight) { //console.log("加载图片完全显示出来了"); if (!isLoading) { if (pageId >= totalPage) { $("#product > .loading-info > img").css({ display: "none" }); $("#product > .loading-info > .loading-tips").css({ display: "block" }); } else { pageId = pageId + 1; getProductList(); } } } }); //$().click(); function getProductList() { isLoading = true; setTimeout(function() { $.ajax({ url: "http://127.0.0.1:3000/api/getproductlist", dataType: "json", data: { categoryid: 0, pageid: pageId }, success: function(data) { console.log(data); var html = template("inlanddiscount-product-list-template", data); $("#product > .product-list").append(html); totalPage = Math.ceil(data.totalCount / data.pagesize); isLoading = false; //隐藏加载中的效果 // $("#product > .loading-info > img").css({ // display: "none" // }); // $("#product > .loading-info > .loading-tips").css({ // display: "block" // }); } }); }, 2000); } });<file_sep>$(function(){ var categoryId = getUrlParams("categoryid"); console.log("categoryId=" + categoryId); var pageId = 1; getProductList(categoryId,pageId); function getProductList(categoryid,pageid) { $.ajax({ url:"http://127.0.0.1:3000/api/getproductlist", dataType:"json", data:{categoryid:categoryid,pageid:pageid}, success:function(data){ console.log(data); var html = template("product-list-template",data); $("#product > .product-list").html(html); var totalPage = Math.ceil(data.totalCount / data.pagesize); var optionTag = ''; for(var i=0;i<totalPage;i++) { if((i+1)==pageId) { optionTag += '<option value='+(i+1)+' selected>'+(i+1)+ '/'+ totalPage + '</option>'; } else { optionTag += '<option value='+(i+1)+'>'+(i+1)+ '/'+ totalPage + '</option>'; } } $("select").html(optionTag); goTop(); $(".prev-page").unbind("click").bind("click",function(){ if(pageId <= 1) { alert("当前界面已经是第一页了"); } else { pageId = parseInt(pageId) - 1; getProductList(categoryId,pageId); } return false; }); $(".next-page").unbind("click").bind("click",function(){ if(pageId >= totalPage) { alert("当前界面已经是最后一页了"); } else { pageId = parseInt(pageId) + 1; getProductList(categoryId,pageId); } return false; }); $("select").unbind("change").bind("change",function(){ //console.log("onchange"); //在这个时机中,去获取我们所选中的那个页码的数据 //select的value就是我们所选中的那个option中的value值 pageId = $(this).val(); getProductList(categoryId,pageId); }); } }); } });<file_sep>$(function() { var productId = getUrlParams("myid"); var categoryId = ""; $.ajax({ url: "http://127.0.0.1:3000/api/getproduct", dataType: "json", data: { productid: productId }, success: function(data) { var displayName = data.result[0].productName.substring(0, 3); var productNameLiTag = '<li class="active">' + displayName + '</li>'; // $(".breadcrumb").append(productNameLiTag); categoryId = data.result[0].categoryId; $.ajax({ url: "http://127.0.0.1:3000/api/getcategorybyid", dataType: "json", data: { categoryid: categoryId }, success: function(data) { console.log(data); var categoryNameLiTag = '<li><a href="category_product_list.html?categoryid='+categoryId+'">'+data.result[0].category+'</a></li>'; $(".breadcrumb").append(categoryNameLiTag); $(".breadcrumb").append(productNameLiTag); } }); //console.log(data); } }); });<file_sep>$(function() { var isShopOpened = false; var isAreaOpened = false; $(".shop").click(function() { if (isShopOpened) { closeShopContent(); } else { openShopContent(); } return false; }); $(".area").click(function() { if (isAreaOpened) { closeAreaContent(); } else { openAreaContent(); } return false; }); var clickedShopId = 0; var clickedAreaId = 0; $.ajax({ url: "http://127.0.0.1:3000/api/getgsshop", dataType: "json", success: function(data) { var shopHtml = template("shop-content-template", data); $(".shop-content").html(shopHtml); $(".shop-content > a").click(function() { $(".shop-content > a").removeClass("haha"); $(this).addClass("haha"); clickedShopId = this.dataset["shopId"]; $(".shop").text($(this).text()); closeShopContent(); getProductList(); return false; }); clickedShopId = data.result[0].shopId; var firstShopName = data.result[0].shopName; $(".shop").text(firstShopName); $(".shop-content > a:first-of-type").addClass("haha"); $.ajax({ url: "http://127.0.0.1:3000/api/getgsshoparea", dataType: "json", success: function(data) { var areaHtml = template("area-content-template", data); $(".area-content").html(areaHtml); $(".area-content > a").click(function() { $(".area-content > a").removeClass("haha"); $(this).addClass("haha"); clickedAreaId = this.dataset["areaId"]; $(".area").text($(this).text()); closeAreaContent(); getProductList(); return false; }); clickedAreaId = data.result[0].areaId; var firstAreaName = data.result[0].areaName; $(".area").text(firstAreaName); $(".area-content > a:first-of-type").addClass("haha"); getProductList(); } }); } }); function getProductList() { $.ajax({ url: urlPrefix + "/api/getgsproduct", dataType: "json", data: { shopid: clickedShopId, areaid: clickedAreaId }, success: function(data) { console.log(data); //将数据和模板结合起来生成html片段,放到product-list里面去 } }); } //高内聚 低耦合 function openShopContent() { closeAreaContent(); $(".shop-content").css({ display: "block" }); $(".shop").addClass("opened"); isShopOpened = true; } function closeShopContent() { $(".shop-content").css({ display: "none" }); $(".shop").removeClass("opened"); isShopOpened = false; } function openAreaContent() { closeShopContent(); $(".area-content").css({ display: "block" }); $(".area").addClass("opened"); isAreaOpened = true; } function closeAreaContent() { $(".area-content").css({ display: "none" }); $(".area").removeClass("opened"); isAreaOpened = false; } });<file_sep># MMM 仿慢慢买商城 这几天没事用来玩的 <file_sep>$(function() { //需要对触摸事件进行监听 //事件序列: 按下(一个) 移动(n个) 抬起 (一个) var startX = 0; $("ul").on("touchstart", function(e) { startX = e.originalEvent.touches[0].clientX; }); $("ul").on("touchmove", function(e) { var moveX = e.originalEvent.touches[0].clientX; var offsetX = moveX - startX; //得到移动的偏移量 //获取当前已经偏移的值 在此基础之上,进行offsetX的增加 var oldTranslateX = 0; if ($("ul").css("transform") == "none") { oldTranslateX = 0; } else { oldTranslateX = parseInt($("ul").css("transform").split(",")[4]); } var newTranslateX = oldTranslateX + offsetX; console.log("newTranslateX=" + newTranslateX); //console.log(offsetX); $("ul").css({ transform: "translateX(" + newTranslateX + "px)", transition: "none" }); startX = moveX; //在此需要对startX进行重新的赋值 }); $("ul").on("touchend", function(e) { console.log("抬起"); //判断当前的translateX是否在正常的范围内 var finalTranslateX = parseInt($("ul").css("transform").split(",")[4]); var maxTranslateX = -$("ul").width() + $(".baicaijia-title").width(); if (finalTranslateX > 0) { finalTranslateX = 0; } else if (finalTranslateX < maxTranslateX) { finalTranslateX = maxTranslateX; } $("ul").css({ transform: "translateX(" + finalTranslateX + "px)", transition: "transform 500ms" }); }); $.ajax({ url: "http://127.0.0.1:3000/api/getbaicaijiatitle", dataType: "json", success: function(data) { console.log(data); var html = template("baicaijia-title-template", data); $(".baicaijia-title > ul").html(html); //默认将数据中的第0项的商品列表加载出来 getProductList(data.result[0].titleId); $("ul").width(100 * data.result.length); $("ul > li:first-of-type > a").addClass("haha"); $("ul > li > a").click(function() { $("ul > li > a").removeClass("haha"); $(this).addClass("haha"); var targetTitleId = this.dataset["titleId"]; getProductList(targetTitleId); return false; }); } }); function getProductList(titleId) { $.ajax({ url: "http://127.0.0.1:3000/api/getbaicaijiaproduct", dataType: "json", data: { titleid: titleId }, success: function(data) { //得到数据时候,使用模板,将html生成 //生成的html放到product-list里面来 } }); } });
81e555b77d3c4915e1ee7c1d98d66d4944409d29
[ "JavaScript", "Markdown" ]
7
JavaScript
OneHugh/MMM
80be4c2aa6bff4d5a77789513fe0521f07574312
6b2ca6b1933d575e54e6d88f7e79dd11199cc4cb
refs/heads/master
<file_sep><?php echo "<table border>"; for ($lig=1; $lig < 11 ; $lig++) { echo "<tr></tr>"; echo "<th>table de $lig</th>"; for ($col=1; $col < 11; $col++) { $res = $lig * $col; echo "<td>"."$lig * $col = " . $res."</td>"; } } echo "</table>";
bc285f612099a25b01edf2b7f2c1b9ee79fdbfe3
[ "PHP" ]
1
PHP
franck5/table_multipli
6c7261e09140ce7e149260f55059473fcaf9386d
b8f29fb098b34b1776df4bb2b8186ed836a025fb
refs/heads/master
<file_sep>/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.di.trans.steps.gpload; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; // // The "designer" notes of the Greenplum bulkloader: // ---------------------------------------------- // // - "Enclosed" is used in the loader instead of "optionally enclosed" as optionally // encloses kind of destroys the escaping. // - A Boolean is output as Y and N (as in the text output step e.g.). If people don't // like this they can first convert the boolean value to something else before loading // it. // - Filters (besides data and datetime) are not supported as it slows down. // // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Performs a bulk load to an Greenplum table. * * Based on (copied from) <NAME>'s Oracle Bulk Loader step * * @author <NAME>, <NAME>, <NAME> * @since 28-mar-2008, 17-dec-2010 */ public class GPLoad extends BaseStep implements StepInterface { private static Class<?> PKG = GPLoadMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private static String INDENT = " "; private static String GPLOAD_YAML_VERSION = "VERSION: 1.0.0.1"; private static String SINGLE_QUOTE = "'"; private static String OPEN_BRACKET = "["; private static String CLOSE_BRACKET = "]"; private static String SPACE_PADDED_DASH = " - "; private static String COLON = ":"; private static char DOUBLE_QUOTE = '"'; Process gploadProcess = null; private GPLoadMeta meta; protected GPLoadData data; private GPLoadDataOutput output = null; /* * Local copy of the transformation "preview" property. We only forward the rows * upon previewing, we don't do any of the real stuff. */ private boolean preview = false; // // This class continually reads from the stream, and sends it to the log // if the logging level is at least basic level. // private final class StreamLogger extends Thread { private InputStream input; private String type; StreamLogger(InputStream is, String type) { this.input = is; this.type = type + ">"; } public void run() { try { final BufferedReader br = new BufferedReader(new InputStreamReader(input)); String line; while ((line = br.readLine()) != null) { // Only perform the concatenation if at basic level. Otherwise, // this just reads from the stream. if (log.isBasic()) { logBasic(type + line); } } } catch (IOException ioe) { ioe.printStackTrace(); } } } public GPLoad(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } /** * Get the contents of the control file as specified in the meta object * * @param meta * the meta object to model the control file after * * @return a string containing the control file contents */ public String getControlFileContents(GPLoadMeta meta, RowMetaInterface rm) throws KettleException { String[] tableFields = meta.getFieldTable(); boolean[] matchColumn = meta.getMatchColumn(); boolean[] updateColumn = meta.getUpdateColumn(); // TODO: All this validation could be placed in it's own method, // table name validation DatabaseMeta databaseMeta = meta.getDatabaseMeta(); String schemaName = meta.getSchemaName(); String targetTableName = meta.getTableName(); // TODO: What is schema name to a GreenPlum database? // Testing has been with an empty schema name // We will set it to an empty string if it is null // If it is not null then we will process what it is if (schemaName == null) { schemaName = ""; } if (targetTableName == null) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.TargetTableNameMissing")); } targetTableName = environmentSubstitute(targetTableName).trim(); if (Const.isEmpty(targetTableName)) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.TargetTableNameMissing")); } // Schema name should be unquoted (gpload yaml parse error) schemaName = environmentSubstitute(schemaName); if (Const.isEmpty(schemaName)) { schemaName = databaseMeta.getPreferredSchemaName(); } if (Const.isEmpty(schemaName)) { schemaName = ""; } else { schemaName = "\"" + schemaName + "\"."; } if (meta.islowertables()) { targetTableName = schemaName.toLowerCase() + "\"" + targetTableName.toLowerCase() + "\""; } else { targetTableName = schemaName + "\"" + targetTableName + "\""; } String loadAction = meta.getLoadAction(); // match and update column verification if (loadAction.equalsIgnoreCase(GPLoadMeta.ACTION_MERGE) || loadAction.equalsIgnoreCase(GPLoadMeta.ACTION_UPDATE)) { // throw an exception if we don't have match columns if (matchColumn == null) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.MatchColumnsNeeded")); } if (!meta.hasMatchColumn()) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.MatchColumnsNeeded")); } // throw an exception if we don't have any update columns if (updateColumn == null) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.UpdateColumnsNeeded")); } if (!meta.hasUpdateColumn()) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.UpdateColumnsNeeded")); } } // data file validation String dataFilename = meta.getDataFile(); if (!Const.isEmpty(dataFilename)) { dataFilename = environmentSubstitute(dataFilename).trim(); } if (Const.isEmpty(dataFilename)) { throw new KettleException(BaseMessages.getString(PKG, "GPload.Exception.DataFileMissing")); } // delimiter validation String delimiter = meta.getDelimiter(); if (!Const.isEmpty(delimiter)) { delimiter = environmentSubstitute(delimiter).trim(); } if (Const.isEmpty(delimiter)) { throw new KettleException(BaseMessages.getString(PKG, "GPload.Exception.DelimiterMissing")); } // Now we start building the contents StringBuffer contents = new StringBuffer(1000); // Source: GP Admin Guide 3.3.6, page 635: contents.append(GPLoad.GPLOAD_YAML_VERSION).append(Const.CR); contents.append("DATABASE: "); contents.append(environmentSubstitute(databaseMeta.getDatabaseName())); contents.append(Const.CR); contents.append("USER: ").append(environmentSubstitute(databaseMeta.getUsername())).append(Const.CR); contents.append("HOST: ").append(environmentSubstitute(databaseMeta.getHostname())).append(Const.CR); contents.append("PORT: ").append(environmentSubstitute(databaseMeta.getDatabasePortNumberString())) .append(Const.CR); contents.append("GPLOAD:").append(Const.CR); contents.append(GPLoad.INDENT).append("INPUT: ").append(Const.CR); contents.append(GPLoad.INDENT).append("- SOURCE: ").append(Const.CR); // Add a LOCAL_HOSTS section // We first check to see if the array has any elements // if so we proceed with the string building - if not we do not add // LOCAL_HOSTNAME section. String[] localHosts = meta.getLocalHosts(); String stringLocalHosts = null; if (!Const.isEmpty(localHosts)) { StringBuilder sbLocalHosts = new StringBuilder(); String trimmedAndSubstitutedLocalHost; for (String localHost : localHosts) { trimmedAndSubstitutedLocalHost = environmentSubstitute(localHost.trim()); if (!Const.isEmpty(trimmedAndSubstitutedLocalHost)) { sbLocalHosts.append(GPLoad.INDENT).append(GPLoad.INDENT).append(GPLoad.SPACE_PADDED_DASH) .append(trimmedAndSubstitutedLocalHost).append(Const.CR); } } stringLocalHosts = sbLocalHosts.toString(); if (!Const.isEmpty(stringLocalHosts)) { contents.append(GPLoad.INDENT).append(GPLoad.INDENT).append("LOCAL_HOSTNAME: ").append(Const.CR) .append(stringLocalHosts); } } // Add a PORT section if we have a port String localhostPort = meta.getLocalhostPort(); if (!Const.isEmpty(localhostPort)) { localhostPort = environmentSubstitute(localhostPort).trim(); if (!Const.isEmpty(localhostPort)) { contents.append(GPLoad.INDENT).append(GPLoad.INDENT).append("PORT: ").append(localhostPort) .append(Const.CR); } } // TODO: Stream to a temporary file and then bulk load OR optionally stream to a // named pipe (like MySQL bulk loader) dataFilename = GPLoad.SINGLE_QUOTE + environmentSubstitute(dataFilename) + GPLoad.SINGLE_QUOTE; contents.append(GPLoad.INDENT).append(GPLoad.INDENT).append("FILE: ").append(GPLoad.OPEN_BRACKET) .append(dataFilename).append(GPLoad.CLOSE_BRACKET).append(Const.CR); String befsql = "drop table " + targetTableName + ";" + "create table " + targetTableName + " ("; // columns if (tableFields.length > 0) { contents.append(GPLoad.INDENT).append("- COLUMNS: ").append(Const.CR); for (String columnName : tableFields) { if (meta.islowertables()) { columnName = columnName.toLowerCase(); } if (meta.isautocreatetable()) { befsql = befsql + "\"" + columnName + "\" text,"; } contents.append(GPLoad.INDENT).append(GPLoad.INDENT).append(GPLoad.SPACE_PADDED_DASH) .append(databaseMeta.quoteField("'\"" + columnName + "\"'")).append(GPLoad.COLON) .append(Const.CR); } } // See also page 155 for formatting information & escaping // delimiter validation should have been perfomed contents.append(GPLoad.INDENT).append("- FORMAT: TEXT").append(Const.CR); // ESCAPE contents.append(GPLoad.INDENT).append("- ESCAPE: 'OFF'").append(Const.CR); // maxlinelength contents.append(GPLoad.INDENT).append("- MAX_LINE_LENGTH: ").append(Integer.parseInt(meta.getmaxlinelength())) .append(Const.CR); contents.append(GPLoad.INDENT).append("- DELIMITER: ").append(GPLoad.SINGLE_QUOTE).append(delimiter) .append(GPLoad.SINGLE_QUOTE).append(Const.CR); // if ( !Const.isEmpty( meta.getNullAs() ) ) { if (!Const.isEmpty(meta.getNullAs())) { contents.append(GPLoad.INDENT).append("- NULL_AS: ").append(GPLoad.SINGLE_QUOTE).append(meta.getNullAs()) .append(GPLoad.SINGLE_QUOTE).append(Const.CR); } // TODO: implement escape character // TODO: test what happens when a single quote is specified- can we specify a // single quiote within doubole quotes // then? String enclosure = meta.getEnclosure(); // For enclosure we do a null check. !Const.isEmpty will be true if the string // is empty. // it is ok to have an empty string if (enclosure != null) { enclosure = environmentSubstitute(meta.getEnclosure()); } else { enclosure = ""; } contents.append(GPLoad.INDENT).append("- QUOTE: ").append(GPLoad.SINGLE_QUOTE).append(enclosure) .append(GPLoad.SINGLE_QUOTE).append(Const.CR); contents.append(GPLoad.INDENT).append("- HEADER: FALSE").append(Const.CR); // ENCODING String encoding = meta.getEncoding(); if (!Const.isEmpty(encoding)) { contents.append(GPLoad.INDENT).append("- ENCODING: ").append(encoding).append(Const.CR); } // Max errors String maxErrors = meta.getMaxErrors(); if (maxErrors == null) { maxErrors = GPLoadMeta.MAX_ERRORS_DEFAULT; } else { maxErrors = environmentSubstitute(maxErrors); try { if (Integer.valueOf(maxErrors) < 0) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.MaxErrorsInvalid")); } } catch (NumberFormatException nfe) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.MaxErrorsInvalid")); } } contents.append(GPLoad.INDENT).append("- ERROR_LIMIT: ").append(maxErrors).append(Const.CR); String errorTableName = meta.getErrorTableName(); if (!Const.isEmpty(errorTableName)) { errorTableName = environmentSubstitute(errorTableName).trim(); if (!Const.isEmpty(errorTableName)) { contents.append(GPLoad.INDENT).append("- ERROR_TABLE: ").append(errorTableName).append(Const.CR); } } String truncate = meta.gettruncate(); if (!Const.isEmpty(truncate)) { contents.append(GPLoad.INDENT).append("PRELOAD:").append(Const.CR); contents.append(GPLoad.INDENT).append("- TRUNCATE: ").append(truncate).append(Const.CR); contents.append(GPLoad.INDENT).append("- REUSE_TABLES: TRUE ").append(Const.CR); } // -------------- OUTPUT section contents.append(GPLoad.INDENT).append("OUTPUT:").append(Const.CR); contents.append(GPLoad.INDENT).append("- TABLE: ").append("'" + targetTableName + "'").append(Const.CR); contents.append(GPLoad.INDENT).append("- MODE: ").append(loadAction).append(Const.CR); // TODO: MAPPING // add auto create table if (meta.isautocreatetable()) { befsql = befsql.substring(0, befsql.length() - 1) + ");"; } // do the following block if the load action is an update or merge if (loadAction.equals(GPLoadMeta.ACTION_UPDATE) || loadAction.equals(GPLoadMeta.ACTION_MERGE)) { // if we have match columns then add the specification if (meta.hasMatchColumn()) { contents.append(GPLoad.INDENT).append("- MATCH_COLUMNS: ").append(Const.CR); for (int i = 0; i < matchColumn.length; i++) { if (matchColumn[i]) { contents.append(GPLoad.INDENT).append(GPLoad.INDENT).append(GPLoad.SPACE_PADDED_DASH) .append(databaseMeta.quoteField(tableFields[i])).append(Const.CR); } } } // if we have update columns then add the specification if (meta.hasUpdateColumn()) { contents.append(GPLoad.INDENT).append("- UPDATE_COLUMNS: ").append(Const.CR); for (int i = 0; i < updateColumn.length; i++) { if (updateColumn[i]) { contents.append(GPLoad.INDENT).append(GPLoad.INDENT).append(GPLoad.SPACE_PADDED_DASH) .append(databaseMeta.quoteField(tableFields[i])).append(Const.CR); } } } // if we have an update condition String updateCondition = meta.getUpdateCondition(); if (!Const.isEmpty(updateCondition)) { // replace carriage returns with spaces and trim the whole thing updateCondition = updateCondition.replaceAll("[\r\n]", " ").trim(); // test the contents once again // the original contents may have just been linefeed/carriage returns if (!Const.isEmpty(updateCondition)) { // we'll write out what we have contents.append(GPLoad.INDENT).append("- UPDATE_CONDITION: ").append(GPLoad.DOUBLE_QUOTE) .append(updateCondition).append(GPLoad.DOUBLE_QUOTE).append(Const.CR); } } } return contents.toString(); } /** * Create a control file. * * @param filename * @param meta * @throws KettleException */ public void createControlFile(GPLoadMeta meta) throws KettleException { // 增加自动识别字段 if (!(meta.getFieldTable().length > 0)) { meta.setFieldTable(this.getInputRowMeta().getFieldNames()); } String filename = meta.getControlFile(); if (Const.isEmpty(filename)) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.NoControlFileSpecified")); } else { filename = environmentSubstitute(filename).trim(); if (Const.isEmpty(filename)) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.NoControlFileSpecified")); } } File controlFile = new File(filename); FileWriter fw = null; try { controlFile.createNewFile(); fw = new FileWriter(controlFile); fw.write(getControlFileContents(meta, getInputRowMeta())); } catch (IOException ex) { throw new KettleException(ex.getMessage(), ex); } finally { try { if (fw != null) { fw.close(); } } catch (Exception ignored) { // Ignore error } } } /** * Returns the path to the pathToFile. It should be the same as what was passed * but this method will check the file system to see if the path is valid. * * @param pathToFile * Path to the file to verify. * @param exceptionMessage * The message to use when the path is not provided. * @param checkExistence * When true the path's existence will be verified. * @return * @throws KettleException */ private String getPath(String pathToFile, String exceptionMessage, boolean checkExistenceOfFile) throws KettleException { // Make sure the path is not empty if (Const.isEmpty(pathToFile)) { throw new KettleException(exceptionMessage); } // make sure the variable substitution is not empty pathToFile = environmentSubstitute(pathToFile).trim(); if (Const.isEmpty(pathToFile)) { throw new KettleException(exceptionMessage); } FileObject fileObject = KettleVFS.getFileObject(pathToFile, getTransMeta()); try { // we either check the existence of the file if (checkExistenceOfFile) { if (!fileObject.exists()) { throw new KettleException( BaseMessages.getString(PKG, "GPLoad.Execption.FileDoesNotExist", pathToFile)); } } else { // if the file does not have to exist, the parent, or source folder, does. FileObject parentFolder = fileObject.getParent(); if (parentFolder.exists()) { return KettleVFS.getFilename(fileObject); } else { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.DirectoryDoesNotExist", parentFolder.getURL().getPath())); } } // if Windows is the OS if (Const.getOS().startsWith("Windows")) { return addQuotes(pathToFile); } else { return KettleVFS.getFilename(fileObject); } } catch (FileSystemException fsex) { throw new KettleException( BaseMessages.getString(PKG, "GPLoad.Exception.GPLoadCommandBuild", fsex.getMessage())); } } /** * Create the command line for GPLoad depending on the meta information * supplied. * * @param meta * The meta data to create the command line from * @param password * Use the real password or not * * @return The string to execute. * * @throws KettleException * Upon any exception */ public String createCommandLine(GPLoadMeta meta, boolean password) throws KettleException { StringBuffer sbCommandLine = new StringBuffer(300); if (Const.getOS().startsWith("Windows")) { sbCommandLine.append("cmd /c "); } // get path to the executable sbCommandLine.append(getPath(meta.getGploadPath(), BaseMessages.getString(PKG, "GPLoad.Exception.GPLoadPathMisssing"), true)); // get the path to the control file sbCommandLine.append(" -f "); sbCommandLine.append(getPath(meta.getControlFile(), BaseMessages.getString(PKG, "GPLoad.Exception.ControlFilePathMissing"), false)); // get the path to the log file, if specified String logfile = meta.getLogFile(); if (!Const.isEmpty(logfile)) { sbCommandLine.append(" -l "); sbCommandLine.append(getPath(meta.getLogFile(), BaseMessages.getString(PKG, "GPLoad.Exception.LogFilePathMissing"), false)); } sbCommandLine.append(" -V "); sbCommandLine.append(" --gpfdist_timeout 7200 "); return sbCommandLine.toString(); } public boolean execute(GPLoadMeta meta, boolean wait) throws KettleException { String commandLine = null; Runtime rt = Runtime.getRuntime(); int gpLoadExitVal = 0; try { commandLine = createCommandLine(meta, true); logBasic("Executing: " + commandLine); gploadProcess = rt.exec(commandLine); // any error message? StreamLogger errorLogger = new StreamLogger(gploadProcess.getErrorStream(), "ERROR"); // any output? StreamLogger outputLogger = new StreamLogger(gploadProcess.getInputStream(), "OUTPUT"); // kick them off errorLogger.start(); outputLogger.start(); if (wait) { // any error??? gpLoadExitVal = gploadProcess.waitFor(); logBasic(BaseMessages.getString(PKG, "GPLoad.Log.ExitValuePsqlPath", "" + gpLoadExitVal)); if (gpLoadExitVal != 0) { throw new KettleException( BaseMessages.getString(PKG, "GPLoad.Log.ExitValuePsqlPath", "" + gpLoadExitVal)); } } } catch (KettleException ke) { throw ke; } catch (Exception ex) { // Don't throw the message upwards, the message contains the password. throw new KettleException("Error while executing \'" + commandLine + "\'. Exit value = " + gpLoadExitVal); } return true; } public String[] getsql(GPLoadMeta meta) throws KettleException { // 增加自动识别字段 if (!(meta.getFieldTable().length > 0)) { meta.setFieldTable(this.getInputRowMeta().getFieldNames()); } String[] tableFields = meta.getFieldTable(); String schemaName = meta.getSchemaName(); String targetTableName = meta.getTableName(); DatabaseMeta databaseMeta = meta.getDatabaseMeta(); if (schemaName == null) { schemaName = ""; } if (targetTableName == null) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.TargetTableNameMissing")); } targetTableName = environmentSubstitute(targetTableName).trim(); if (Const.isEmpty(targetTableName)) { throw new KettleException(BaseMessages.getString(PKG, "GPLoad.Exception.TargetTableNameMissing")); } // Schema name should be unquoted (gpload yaml parse error) schemaName = environmentSubstitute(schemaName); if (Const.isEmpty(schemaName)) { schemaName = databaseMeta.getPreferredSchemaName(); } if (Const.isEmpty(schemaName)) { schemaName = ""; } else { schemaName = "\"" + schemaName + "\"."; } targetTableName = schemaName + "\"" + databaseMeta.quoteField(targetTableName) + "\""; String[] sqls = new String[2]; sqls[0] = "drop table " + targetTableName; String befsql = "create table " + targetTableName + " ("; if (tableFields.length > 0) { for (String columnName : tableFields) { befsql = befsql + "\"" + columnName + "\" text,"; } } if (meta.islowertables()) { befsql = befsql.toLowerCase(); } befsql = befsql.substring(0, befsql.length() - 1) + ");"; // meta, getInputRowMeta() sqls[1] = befsql; return sqls; } private void closeOutput() throws Exception { if (data.fifoStream != null) { // Close the fifo file... // data.fifoStream.close(); data.fifoStream = null; } if (data.gploadexec != null) { data.gploadexec.join(3000); Gploadexec gploadexecs = data.gploadexec; data.gploadexec = null; gploadexecs.checkExcn(); } } private SimpleDateFormat sdfDate = null; private SimpleDateFormat sdfDateTime = null; private int[] fieldNumbers = null; private String enclosure = null; private String delimiter = null; private void setparam(RowMetaInterface mi)throws KettleException { enclosure = meta.getEnclosure(); if (enclosure == null) { enclosure = ""; } else { enclosure = environmentSubstitute(enclosure); } delimiter = meta.getDelimiter(); if (delimiter == null) { throw new KettleException(BaseMessages.getString(PKG, "GPload.Exception.DelimiterMissing")); } else { delimiter = environmentSubstitute(delimiter); if (Const.isEmpty(delimiter)) { throw new KettleException(BaseMessages.getString(PKG, "GPload.Exception.DelimiterMissing")); } } // 增加自动识别字段 if (!(meta.getFieldStream().length > 0)) { meta.setFieldStream(mi.getFieldNames()); } // Setup up the fields we need to take for each of the rows // as this speeds up processing. fieldNumbers = new int[meta.getFieldStream().length]; for (int i = 0; i < fieldNumbers.length; i++) { fieldNumbers[i] = mi.indexOfValue(meta.getFieldStream()[i]); if (fieldNumbers[i] < 0) { throw new KettleException(BaseMessages.getString(PKG, "GPLoadDataOutput.Exception.FieldNotFound", meta.getFieldStream()[i])); } } sdfDate = new SimpleDateFormat("yyyy-MM-dd"); sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); } public void writeLinefifo(RowMetaInterface mi, Object[] row) throws KettleException { try { // Write the data to the output enclosure = meta.getEnclosure(); if (enclosure == null) { enclosure = ""; } else { enclosure = environmentSubstitute(enclosure); } delimiter = meta.getDelimiter(); if (delimiter == null) { throw new KettleException(BaseMessages.getString(PKG, "GPload.Exception.DelimiterMissing")); } else { delimiter = environmentSubstitute(delimiter); if (Const.isEmpty(delimiter)) { throw new KettleException(BaseMessages.getString(PKG, "GPload.Exception.DelimiterMissing")); } } ValueMetaInterface v = null; int number = 0; String endocing = meta.getwtencod(); for (int i = 0; i < fieldNumbers.length; i++) { // TODO: variable substitution if (i != 0) { data.fifoStream.write(delimiter.getBytes()); } number = fieldNumbers[i]; v = mi.getValueMeta(number); if (row[number] == null) { // TODO (SB): special check for null in case of Strings. data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(enclosure.getBytes()); } else { switch (v.getType()) { case ValueMetaInterface.TYPE_STRING: String s = mi.getString(row, number); // 替换特殊分割字符 // if ( s.indexOf( enclosure ) !=-1 ) { // s = createEscapedString( s, delimiter ); // } if (s != null) { s = s.replace("\r", "").replace("\n", "").replace(delimiter, meta.getwtreplace()).replace("\t", "") .replaceAll("\0x00", "").replaceAll("\u0000", ""); } // String s1=s.replace("\r", ""); // String s2=s1.replace("\n", ""); // String s3=s2.replace("\t", ""); // String s4 =s3.replace(delimiter, "gennlife"); data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(s.getBytes()); data.fifoStream.write(enclosure.getBytes()); break; case ValueMetaInterface.TYPE_INTEGER: Long l = mi.getInteger(row, number); if (meta.getEncloseNumbers()) { data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(String.valueOf(1).getBytes()); data.fifoStream.write(enclosure.getBytes()); } else { data.fifoStream.write(String.valueOf(1).getBytes()); } break; case ValueMetaInterface.TYPE_NUMBER: Double d = mi.getNumber(row, number); if (meta.getEncloseNumbers()) { data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(String.valueOf(d).getBytes()); data.fifoStream.write(enclosure.getBytes()); } else { data.fifoStream.write(String.valueOf(d).getBytes()); } break; case ValueMetaInterface.TYPE_BIGNUMBER: BigDecimal bd = mi.getBigNumber(row, number); if (meta.getEncloseNumbers()) { data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(String.valueOf(bd).getBytes()); data.fifoStream.write(enclosure.getBytes()); } else { data.fifoStream.write(String.valueOf(bd).getBytes()); } break; case ValueMetaInterface.TYPE_DATE: Date dt = mi.getDate(row, number); data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(sdfDate.format(dt).getBytes()); data.fifoStream.write(enclosure.getBytes()); break; case ValueMetaInterface.TYPE_BOOLEAN: Boolean b = mi.getBoolean(row, number); data.fifoStream.write(enclosure.getBytes()); if (b.booleanValue()) { data.fifoStream.write("Y".getBytes()); } else { data.fifoStream.write("N".getBytes()); } data.fifoStream.write(enclosure.getBytes()); break; case ValueMetaInterface.TYPE_BINARY: byte[] byt = mi.getBinary(row, number); // String string=""; // try { // string=new String(byt,endocing);} // catch (Exception e) { // TODO: handle exception // } // string=string.replace("\r", "").replace("\n", "").replace(delimiter, // "gennlife").replace("\t","").replaceAll("\0x00", "").replaceAll("\u0000", // ""); String string = output.bytesToHexString(byt); data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(string.getBytes()); data.fifoStream.write(enclosure.getBytes()); break; case ValueMetaInterface.TYPE_TIMESTAMP: Date time = mi.getDate(row, number); data.fifoStream.write(enclosure.getBytes()); data.fifoStream.write(sdfDateTime.format(time).getBytes()); data.fifoStream.write(enclosure.getBytes()); break; default: throw new KettleException(BaseMessages.getString(PKG, "GPLoadDataOutput.Exception.TypeNotSupported", v.getType())); } } } data.fifoStream.write(Const.CR.getBytes()); data.fifoStream.flush(); } catch (IOException e) { throw new KettleException(e.getMessage()); } } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (GPLoadMeta) smi; data = (GPLoadData) sdi; try { Object[] r = getRow(); // Get row from input rowset & set row busy! // no more input to be expected... if (r == null) { setOutputDone(); if (!preview) { if (output != null) { // Close the output try { if (meta.isfifo()) { this.closeOutput(); } else { output.close(); } } catch (Exception e) { throw new KettleException("Error while closing output", e); } output = null; } String loadMethod = meta.getLoadMethod(); // if it specified that we are to load at the end of processing if (GPLoadMeta.METHOD_AUTO_END.equals(loadMethod)) { // if we actually wrote at least one row if (getLinesOutput() > 0) { // we do this if (!meta.isfifo()) { createControlFile(meta); execute(meta, true); } } else { // we don't create a control file and execute logBasic(BaseMessages.getString(PKG, "GPLoad.Info.NoRowsWritten")); } } else if (GPLoadMeta.METHOD_MANUAL.equals(loadMethod)) { // we create the control file but do not execute if (!meta.isfifo()) { createControlFile(meta); } logBasic(BaseMessages.getString(PKG, "GPLoad.Info.MethodManual")); } else { throw new KettleException( BaseMessages.getString(PKG, "GPload.Execption.UnhandledLoadMethod", loadMethod)); } } return false; } if (!preview) { if (first) { first = false; if (meta.isautocreatetable()) { String sql[] = getsql(meta); for (String string : sql) { try { Result res = data.db.execStatement(string); } catch (Exception e) { logBasic(e.getMessage()); } } if (!data.db.isAutoCommit()) { data.db.commit(); } } output = new GPLoadDataOutput(this, meta, log.getLogLevel()); setparam(getInputRowMeta()); // if ( GPLoadMeta.METHOD_AUTO_CONCURRENT.equals(meta.getLoadMethod()) ) // { // execute(meta, false); // } output.open(this, gploadProcess); String loadMethod = meta.getLoadMethod(); // if it specified that we are to load at the end of processing if (GPLoadMeta.METHOD_AUTO_END.equals(loadMethod)) { // if we actually wrote at least one row // we do this if (meta.isfifo()) { String commline = createCommandLine(meta, true); data.gploadexec = new Gploadexec(commline, true); createControlFile(meta); if (!Const.isWindows()) { try { log.logBasic("Opening fifo " + output.getdatafile() + " for writing."); OpenFifo openFifo = new OpenFifo(output.getdatafile(),268435456); openFifo.start(); data.gploadexec.start(); while (true) { openFifo.join(200); if (openFifo.getState() == Thread.State.TERMINATED) { break; } try { data.gploadexec.checkExcn(); } catch (Exception e) { // We need to open a stream to the fifo to unblock the fifo writer // that was waiting for the sqlRunner that now isn't running new BufferedInputStream(new FileInputStream(output.getdatafile())).close(); openFifo.join(); logError("Make sure user has been granted the FILE privilege."); logError(""); throw e; } try { openFifo.checkExcn(); } catch (Exception e) { throw e; } } data.fifoStream = openFifo.getFifoStream(); } catch (Exception e) { logError(e.getMessage()); throw new KettleException(BaseMessages.getString(PKG, e.getMessage())); // TODO: handle exception } } } } else if (GPLoadMeta.METHOD_MANUAL.equals(loadMethod)) { // we create the control file but do not execute if (meta.isfifo()) { createControlFile(meta); throw new KettleException(BaseMessages.getString(PKG, "can not use fifo in manual")); } logBasic(BaseMessages.getString(PKG, "GPLoad.Info.MethodManual")); } else { throw new KettleException( BaseMessages.getString(PKG, "GPload.Execption.UnhandledLoadMethod", loadMethod)); } } if (meta.isfifo()) { writeLinefifo(getInputRowMeta(), r); } else { output.writeLine(getInputRowMeta(), r); } } putRow(getInputRowMeta(), r); incrementLinesOutput(); } catch (KettleException e) { logError(BaseMessages.getString(PKG, "GPLoad.Log.ErrorInStep") + e.getMessage()); setErrors(1); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (GPLoadMeta) smi; data = (GPLoadData) sdi; Trans trans = getTrans(); preview = trans.isPreview(); if (super.init(smi, sdi)) { data.db = new Database(this, meta.getDatabaseMeta()); data.db.shareVariablesWith(this); try { if (getTransMeta().isUsingUniqueConnections()) { synchronized (getTrans()) { data.db.connect(getTrans().getTransactionId(), getPartitionID()); } } else { data.db.connect(getPartitionID()); } } catch (Exception e) { // TODO: handle exception } return true; } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (GPLoadMeta) smi; data = (GPLoadData) sdi; super.dispose(smi, sdi); if (!preview && meta.isEraseFiles()) { // Erase the created cfg/dat files if requested. We don't erase // the rest of the files because it would be "stupid" to erase them // right after creation. If you don't want them, don't fill them in. FileObject fileObject = null; String method = meta.getLoadMethod(); if (GPLoadMeta.METHOD_AUTO_END.equals(method)) { if (meta.getControlFile() != null) { try { fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getControlFile()), getTransMeta()); fileObject.delete(); fileObject.close(); } catch (Exception ex) { logError("Error deleting control file \'" + KettleVFS.getFilename(fileObject) + "\': " + ex.getMessage()); } } } if (GPLoadMeta.METHOD_AUTO_END.equals(method)) { // In concurrent mode the data is written to the control file. if (meta.getDataFile() != null) { try { fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getDataFile()), getTransMeta()); fileObject.delete(); fileObject.close(); } catch (Exception ex) { logError("Error deleting data file \'" + KettleVFS.getFilename(fileObject) + "\': " + ex.getMessage(), ex); } } } if (GPLoadMeta.METHOD_MANUAL.equals(method)) { logBasic("Deletion of files is not compatible with \'manual load method\'"); } } } /** * Adds quotes to the passed string if the OS is Windows and there is at least * one space . * * @param string * @return */ private String addQuotes(String string) { if (Const.getOS().startsWith("Windows") && string.indexOf(" ") != -1) { string = "\"" + string + "\""; } return string; } static class Gploadexec extends Thread { private String commandLine; private boolean waite; private Exception ex; public Gploadexec(String commandLinea, boolean waitea) { this.commandLine = commandLinea; this.waite = waitea; // TODO Auto-generated constructor stub } public void run() { try { Runtime rt = Runtime.getRuntime(); int gpLoadExitVal = 0; try { Process gploadProcess = rt.exec(commandLine); if (waite) { // any error??? gpLoadExitVal = gploadProcess.waitFor(); if (gpLoadExitVal != 0) { throw new KettleException( BaseMessages.getString(PKG, "GPLoad.Log.ExitValuePsqlPath", "" + gpLoadExitVal)); } } } catch (KettleException ke) { throw ke; } catch (Exception ex) { // Don't throw the message upwards, the message contains the password. throw new KettleException( "Error while executing \'" + commandLine + "\'. Exit value = " + gpLoadExitVal); } } catch (Exception ex) { System.out.print(ex.getMessage()); this.ex = ex; } } void checkExcn() throws Exception { // This is called from the main thread context to rethrow any saved // excn. if (ex != null) { throw ex; } } } static class OpenFifo extends Thread { private BufferedOutputStream fifoStream = null; private Exception ex; private String fifoName; private int size; OpenFifo( String fifoName, int size ) { this.fifoName = fifoName; this.size = size; } public void run() { try { fifoStream = new BufferedOutputStream( new FileOutputStream( OpenFifo.this.fifoName ), this.size ); } catch ( Exception ex ) { this.ex = ex; } } void checkExcn() throws Exception { // This is called from the main thread context to rethrow any saved // excn. if ( ex != null ) { throw ex; } } BufferedOutputStream getFifoStream() { return fifoStream; } } } <file_sep>kettle gpload插件 可以不指定列 插件会自动识别列名 可以不做数据预处理 插件会自动替换 特殊换行符 特殊字符 0*00等字符
9337b513e118e92f573bfe860e1ea70f10ad82f9
[ "Markdown", "Java" ]
2
Java
Enjoyor-AI/kettle-gpload-plugin
18ba93df8f818bf003fa363da3ff33a6fa9a328b
0761cac6c2a82df911fea96b41e9603d0f16f18e
refs/heads/master
<file_sep>#!/usr/bin/env python #import serial import time import random import copy #import RPi.GPIO as GPIO #global variable parents_info = [[0 for i in range(80)] for j in range(20)] #distance = [[i,0] for i in range(20)] #start messages print 'input generation (calculate similarity)' generation = input('> ') print u'generation %d : ok?(y or n)' % generation message = raw_input('> ') if message == 'y': #read parents_file parents_filename = 'generation%d.dat' % generation line_number = 0 for line in open(parents_filename, 'r'): itemList = line.split('\t') numbers = [] for item in itemList: numbers.append( int(item) ) parents_info[int(line_number)] = copy.deepcopy(numbers) line_number += 1 same_number = 0 total_number = 0 #calcurate similarity for i in range(0,20): for j in range(i+1,20): for k in range(0,80): if parents_info[i][k] == parents_info[j][k] : same_number += 1 total_number += 1 similarity = same_number * 100.0 / total_number print 'Similarity : %lf' % similarity #add similarity file similarity_file = open('similarity.dat', 'a') generation_info = 'Generation : %d\n' % generation similarity_file.write(str(generation_info)) info = 'Similarity : %lf \n' % similarity similarity_file.write(str(info)) similarity_file.write('\n') similarity_file.close() print 'finish' else: print 'cancel' <file_sep>#!usr/bin/python import RPi.GPIO as GRIO import time GPIO.setmode(GPIO.BCM) LED = 2 GPIO.setup(LED, GPIO.OUT) for i in range(10): GPIO.output(LED, GPIO.HIGH) print 'LED HIGH' time.sleep(1) GPIO.output(LED, GPIO.LOW) print 'LED LOW' time.sleep(1) GPIO.cleanup() <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #servo1,servo3 while True: #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 32 03 A1")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 32 03 A3")) #right port.write(bytearray.fromhex("FF FF 02 05 03 1E CD 00 0A")) port.write(bytearray.fromhex("FF FF 05 05 03 1E CD 00 07")) time.sleep(1) #left port.write(bytearray.fromhex("FF FF 03 05 03 1E CD 00 09")) port.write(bytearray.fromhex("FF FF 01 05 03 1E CD 00 0b")) #right port.write(bytearray.fromhex("FF FF 02 05 03 1E 32 03 A2")) port.write(bytearray.fromhex("FF FF 05 05 03 1E 32 03 9F")) time.sleep(1) <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #servo1,servo3 #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 00 02 D4")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 00 02 D6")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 00 02 D2")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 00 02 D5")) time.sleep(1) while True: #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 96 02 3E")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 6A 01 6D")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 6A 01 69")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 96 02 3F")) time.sleep(0.5) #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 6A 01 6B")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 96 02 40")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 96 02 3C")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 6A 01 6C")) time.sleep(0.5) <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #servo1,servo3 while True: #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 64 02 70")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 64 02 72")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 9C 01 37")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 9C 01 3A")) time.sleep(1) #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 9C 01 39")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 9C 01 3B")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 64 02 6E")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 64 02 71")) time.sleep(1) <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #servo1 servo5 # #Left Right # #servo3 servo2 #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 00 02 D4")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 00 02 D6")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 00 02 D2")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 00 02 D5")) time.sleep(1) i = 0 while i<10: print i #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 64 02 70")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 9C 01 3B")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 00 02 D2")) #port.write(bytearray.fromhex("FF FF 02 05 03 1E 64 02 71")) time.sleep(0.5) #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 00 02 D4")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 64 02 72")) #right #port.write(bytearray.fromhex("FF FF 05 05 03 1E 64 02 6E")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 64 02 71")) time.sleep(0.5) #left #port.write(bytearray.fromhex("FF FF 03 05 03 1E 64 02 70")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 00 02 D6")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 64 02 6E")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 9C 01 3A")) time.sleep(0.5) #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 9C 01 39")) #port.write(bytearray.fromhex("FF FF 01 05 03 1E 9C 01 3B")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 9C 01 37")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 00 02 D5")) time.sleep(0.5) i += 1 <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) while True: port.write(bytearray.fromhex("FF FF 05 05 03 1E 32 03 9f")) time.sleep(3) port.write(bytearray.fromhex("FF FF 05 05 03 1E CD 00 07")) time.sleep(3) <file_sep>#!/usr/bin/env python #list #3152315231523152 #moving time : 10 seconds (80) #number of 1 geberaton : 20 import serial import time import random import copy import RPi.GPIO as GPIO def calc_checksum (num_1, num_2, num_3, num_4, num_5, num_6): ans = num_1 + num_2 + num_3 + num_4 + num_5 + num_6 if ans > 255: ans = ans - 256 return 255 - ans def init(): #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 00 02 D4")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 00 02 D6")) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 00 02 D2")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 00 02 D5")) port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #global variable parents_info = [[0 for i in range(80)] for j in range(20)] distance = [[i,0] for i in range(20)] #start messages print 'input generation' generation = input('> ') print u'generation %d : ok?(y or n)' % generation message = raw_input('> ') if message == 'y': #read parents_file parents_filename = 'generation%d.dat' % generation line_number = 0 for line in open(parents_filename, 'r'): itemList = line.split('\t') numbers = [] for item in itemList: numbers.append( int(item) ) servo3 = ['' for i in range(20)] servo1 = ['' for i in range(20)] servo5 = ['' for i in range(20)] servo2 = ['' for i in range(20)] #make sirial command for i in range(0, 80): if i%4 == 0 : #servo3 x7 = numbers[i] % 256 x8 = numbers[i] / 256 x9 = calc_checksum(03, 05, 03, 30, x7, x8) servo3[i/4] = 'FF FF 03 05 03 1E %02X %02X %02X' % (x7, x8, x9) elif i%4 == 1 : #servo1 x7 = numbers[i] % 256 x8 = numbers[i] / 256 x9 = calc_checksum(01, 05, 03, 30, x7, x8) servo1[i/4] = 'FF FF 01 05 03 1E %02X %02X %02X' % (x7, x8, x9) elif i%4 == 2 : #servo5 x7 = numbers[i] % 256 x8 = numbers[i] / 256 x9 = calc_checksum(05, 05, 03, 30, x7, x8) servo5[i/4] = 'FF FF 05 05 03 1E %02X %02X %02X' % (x7, x8, x9) else : #servo2 x7 = numbers[i] % 256 x8 = numbers[i] / 256 x9 = calc_checksum(02, 05, 03, 30, x7, x8) servo2[i/4] = 'FF FF 02 05 03 1E %02X %02X %02X' % (x7, x8, x9) #send sirial command time.sleep(2) init() print 'Please input character' enter = raw_input('> ') for i in range(0, 20): port.write(bytearray.fromhex(servo3[i])) port.write(bytearray.fromhex(servo1[i])) port.write(bytearray.fromhex(servo5[i])) port.write(bytearray.fromhex(servo2[i])) print i time.sleep(0.5) print 'enter distance X[mm] (%d/20)' % int(line_number + 1) distance[int(line_number)][1] = input('> ') parents_info[int(line_number)] = copy.deepcopy(numbers) line_number += 1 ranking = sorted(distance, key=lambda x: int(x[1]), reverse=True) children_info = [[0 for i in range(80)] for j in range(20)] #make child for i in range(0,4): if ranking[i/2][1] > 0: children_info[i] = copy.deepcopy(parents_info[ranking[i/2][0]]) else: children_info[i] = [random.randint(0,300) + 362 for j in range(80)] #swap info #before 1 1 2 2 3 4 5 ... #after 1 2 1 2 3 4 5 ... tmp_info = copy.deepcopy(children_info[1]) children_info[1] = copy.deepcopy(children_info[2]) children_info[2] = copy.deepcopy(tmp_info) for i in range(4,20): if ranking[i-2][1] > 0: children_info[i] = copy.deepcopy(parents_info[ranking[i-2][0]]) else: children_info[i] = [random.randint(0,300) + 362 for j in range(80)] #keep elite (1st, 2nd) #crossing for i in range(1,10): sep_line = random.randint(1,78) tmp = copy.deepcopy(children_info[i*2][sep_line:]) children_info[i*2][sep_line:] = copy.deepcopy(children_info[i*2+1][sep_line:]) children_info[i*2+1][sep_line:] = copy.deepcopy(tmp) #mutation for i in range(0,70): #biont x = random.randint(2,19) #place y = random.randint(0,79) #value value = random.randint(0,300) + 362 #print u'x:%d y:%d value:%d' % (x, y, value) children_info[x][y] = value #add result result_file = open('result.dat', 'a') generation_info = 'Generation : %d\n' % generation result_file.write(str(generation_info)) average = 0 for i in range(0,20): average += ranking[i][1] info = '%d\t' % ranking[i][1] result_file.write(str(info)) result_file.write('\n') average = average * 1.0 average = average / 20 average_info = 'Average : %f' % average result_file.write(average_info) result_file.write('\n') result_file.write('\n') result_file.close() #write children_file generation += 1 children_filename = 'generation%d.dat' % generation children_file = open(children_filename, 'w') for i in range(0,20): for j in range(0,80): children_file.write(str(children_info[i][j])) if j < 79: children_file.write('\t') if i < 19: children_file.write('\n') print u'made %s' % children_file children_file.close() print 'finish' else: print 'cancel' <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #while True: # port.write(bytearray.fromhex("FF FF 01 05 03 1E 32 03 A3")) # time.sleep(3) # port.write(bytearray.fromhex("FF FF 01 05 03 1E CD 00 0b")) # time.sleep(3) port.write(bytearray.fromhex("FF FF 01 05 03 1E FF 02 D7")) <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) while True: port.write(bytearray.fromhex("FF FF 02 05 03 1E 32 03 A2")) time.sleep(3) port.write(bytearray.fromhex("FF FF 02 05 03 1E CD 00 0A")) time.sleep(3) #port.write(bytearray.fromhex("FF FF 02 05 03 1E 00 02 D5")) #time.sleep(3) <file_sep>import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.OUT) GPIO.output(2, GPIO.HIGH) time.sleep(2) GPIO.cleanup() <file_sep>#!/usr/bin/env python #list #3152315231523152 #moving time : 10 seconds (80) #number of 1 geberaton : 20 #immigration span : 10 #0: 512 - 120 = 392 : 392 #1: 512 + 120 = 632 : 392 + 1*240 import serial import time import random import copy import RPi.GPIO as GPIO def calc_checksum (num_1, num_2, num_3, num_4, num_5, num_6): ans = num_1 + num_2 + num_3 + num_4 + num_5 + num_6 if ans > 255: ans = ans - 256 return 255 - ans port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) line = '1 1 1 1 1 0 1 1 0 1 1 0 0 1 0 1 1 0 1 0 1 0 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 0 1 1 0 0 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0' itemList = line.split() numbers = [] for item in itemList: numbers.append( int(item) ) servo3 = ['' for i in range(20)] servo1 = ['' for i in range(20)] servo5 = ['' for i in range(20)] servo2 = ['' for i in range(20)] #make sirial command for i in range(0, 80): val = 392 + 240 * numbers[i] if i%4 == 0 : #servo3 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(03, 05, 03, 30, x7, x8) servo3[i/4] = 'FF FF 03 05 03 1E %02X %02X %02X' % (x7, x8, x9) elif i%4 == 1 : #servo1 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(01, 05, 03, 30, x7, x8) servo1[i/4] = 'FF FF 01 05 03 1E %02X %02X %02X' % (x7, x8, x9) elif i%4 == 2 : #servo5 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(05, 05, 03, 30, x7, x8) servo5[i/4] = 'FF FF 05 05 03 1E %02X %02X %02X' % (x7, x8, x9) else : #servo2 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(02, 05, 03, 30, x7, x8) servo2[i/4] = 'FF FF 02 05 03 1E %02X %02X %02X' % (x7, x8, x9) #send sirial command for i in range(0, 20): port.write(bytearray.fromhex(servo3[i])) port.write(bytearray.fromhex(servo1[i])) port.write(bytearray.fromhex(servo5[i])) port.write(bytearray.fromhex(servo2[i])) print (i+1) time.sleep(0.5) print 'finish' <file_sep>#!/usr/bin/env python #list #3152315231523152 #moving time : 10 seconds (80) #number of 1 geberaton : 20 #immigration span : 10 #0: 512 - 120 = 392 : 392 #1: 512 + 120 = 632 : 392 + 1*240 import serial import time import random import copy import RPi.GPIO as GPIO def calc_checksum (num_1, num_2, num_3, num_4, num_5, num_6): ans = num_1 + num_2 + num_3 + num_4 + num_5 + num_6 if ans > 255: ans = ans - 256 return 255 - ans def init(): #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 00 02 D4")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 00 02 D6")) time.sleep(0.01) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 00 02 D2")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 00 02 D5")) port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #global variable parents_info = [[[0 for i in range(80)] for j in range(5)] for k in range(4)] distance = [[[i,0] for i in range(5)] for k in range(4)] #start messages print 'input generation' generation = input('> ') print u'generation %d : ok?(y or n)' % generation message = raw_input('> ') if message == 'y': #read parents_file parents_filename = 'generation3_%d.dat' % generation line_number = 0 for line in open(parents_filename, 'r'): itemList = line.split('\t') numbers = [] for item in itemList: numbers.append( int(item) ) servo3 = ['' for i in range(20)] servo1 = ['' for i in range(20)] servo5 = ['' for i in range(20)] servo2 = ['' for i in range(20)] #make sirial command for i in range(0, 80): val = 392 + 240 * numbers[i] if i%4 == 0 : #servo3 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(03, 05, 03, 30, x7, x8) servo3[i/4] = 'FF FF 03 05 03 1E %02X %02X %02X' % (x7, x8, x9) elif i%4 == 1 : #servo1 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(01, 05, 03, 30, x7, x8) servo1[i/4] = 'FF FF 01 05 03 1E %02X %02X %02X' % (x7, x8, x9) elif i%4 == 2 : #servo5 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(05, 05, 03, 30, x7, x8) servo5[i/4] = 'FF FF 05 05 03 1E %02X %02X %02X' % (x7, x8, x9) else : #servo2 x7 = val % 256 x8 = val / 256 x9 = calc_checksum(02, 05, 03, 30, x7, x8) servo2[i/4] = 'FF FF 02 05 03 1E %02X %02X %02X' % (x7, x8, x9) #send sirial command time.sleep(2) init() print 'Please input character' enter = raw_input('> ') for i in range(0, 20): port.write(bytearray.fromhex(servo3[i])) port.write(bytearray.fromhex(servo1[i])) port.write(bytearray.fromhex(servo5[i])) port.write(bytearray.fromhex(servo2[i])) print (i+1) time.sleep(0.5) print 'Island : %d Number : %d' % (int(line_number/5), int(line_number%5 + 1)) print 'enter distance X[mm] (%d/20)' % int(line_number + 1) distance[int(line_number/5)][int(line_number%5)][1] = input('> ') parents_info[int(line_number/5)][int(line_number%5)] = copy.deepcopy(numbers) line_number += 1 ranking = [[[0,0] for i in range(5)] for k in range(4)] for i in range(0,4): ranking[i] = sorted(distance[i], key=lambda x: int(x[1]), reverse=True) children_info = [[[0 for i in range(80)] for j in range(5)] for k in range(4)] #make child (Ver3) for i in range(0,20): if i%5 == 0: if ranking[i/5][i%5][1] > 0: children_info[i/5][i%5] = copy.deepcopy(parents_info[i/5][ranking[i/5][i%5][0]]) else: children_info[i/5][i%5] = [random.randint(0,1) for j in range(80)] else: if ranking[i/5][i%5-1][1] > 0: children_info[i/5][i%5] = copy.deepcopy(parents_info[i/5][ranking[i/5][i%5-1][0]]) else: children_info[i/5][i%5] = [random.randint(0,1) for j in range(80)] #keep elite (1st for each) #crossing for i in range(0,4): for j in range(1,3): sep_line = random.randint(1,78) tmp = copy.deepcopy(children_info[i][j*2-1][sep_line:]) children_info[i][j*2-1][sep_line:] = copy.deepcopy(children_info[i][j*2][sep_line:]) children_info[i][j*2][sep_line:] = copy.deepcopy(tmp) #mutation for i in range (0,4): for j in range(0,20): #biont x = random.randint(1,4) #place y = random.randint(0,79) #reverse children_info[i][x][y] = 1 - children_info[i][x][y] #immigration if generation%10 == 0: case = random.randint(0,8) immigrate = [[0,0] for i in range(4)] if case == 0: immigrate[0][0] = 1 immigrate[1][0] = 2 immigrate[2][0] = 3 immigrate[3][0] = 0 elif case == 1: immigrate[0][0] = 3 immigrate[1][0] = 0 immigrate[2][0] = 1 immigrate[3][0] = 2 elif case == 2: immigrate[0][0] = 2 immigrate[1][0] = 3 immigrate[2][0] = 1 immigrate[3][0] = 0 elif case == 3: immigrate[0][0] = 3 immigrate[1][0] = 2 immigrate[2][0] = 0 immigrate[3][0] = 1 elif case == 4: immigrate[0][0] = 2 immigrate[1][0] = 0 immigrate[2][0] = 3 immigrate[3][0] = 1 elif case == 5: immigrate[0][0] = 1 immigrate[1][0] = 3 immigrate[2][0] = 0 immigrate[3][0] = 2 elif case == 6: immigrate[0][0] = 2 immigrate[1][0] = 3 immigrate[2][0] = 0 immigrate[3][0] = 1 elif case == 7: immigrate[0][0] = 1 immigrate[1][0] = 0 immigrate[2][0] = 3 immigrate[3][0] = 2 else: immigrate[0][0] = 3 immigrate[1][0] = 2 immigrate[2][0] = 1 immigrate[3][0] = 0 #elite remain island for i in range(0,4): immigrate[i][1] = random.randint(1,4) immigrant = [[0 for i in range(80)] for j in range(4)] for i in range(0,4): immigrant[i] = copy.deepcopy(children_info[i][immigrate[i][1]]) for i in range(0,4): children_info[immigrate[i][0]][immigrate[immigrate[i][0]][1]] = copy.deepcopy(immigrant[i]) #add result result_file = open('result3.dat', 'a') generation_info = 'Generation : %d\n' % generation result_file.write(str(generation_info)) whole_average = 0 for i in range(0,4): info_island = '\tIsland : %d\n' % i result_file.write(info_island) average = 0 for j in range(0,5): average += ranking[i][j][1] info = '\t%d' % ranking[i][j][1] result_file.write(str(info)) result_file.write('\n') whole_average += average average *= 0.20 average_info = '\t\tAverage : %f\n' %average result_file.write(average_info) whole_average *= 0.05 whole_average_info = 'Whole Average : %f\n' % whole_average result_file.write(whole_average_info) result_file.write('\n') #immigration info if generation%10 == 0: immi_number = generation / 10 immigration_info = 'Immigration : %d\n' % immi_number result_file.write(str(immigration_info)) immi_0 = '\tImmigrant_0 (0,%d) --> Island_%d\n' % (immigrate[0][1], immigrate[0][0]) immi_1 = '\tImmigrant_1 (1,%d) --> Island_%d\n' % (immigrate[1][1], immigrate[1][0]) immi_2 = '\tImmigrant_2 (2,%d) --> Island_%d\n' % (immigrate[2][1], immigrate[2][0]) immi_3 = '\tImmigrant_3 (3,%d) --> Island_%d\n' % (immigrate[3][1], immigrate[3][0]) result_file.write(str(immi_0)) result_file.write(str(immi_1)) result_file.write(str(immi_2)) result_file.write(str(immi_3)) result_file.write('\n') result_file.close() #write children_file generation += 1 children_filename = 'generation3_%d.dat' % generation children_file = open(children_filename, 'w') for i in range(0,20): for j in range(0,80): children_file.write(str(children_info[i/5][i%5][j])) if j < 79: children_file.write('\t') if i < 19: children_file.write('\n') print u'made %s' % children_file children_file.close() time.sleep(2) init() print 'finish' else: print 'cancel' <file_sep>import serial import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) #GPIO.setup(2, GPIO.OUT) port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) while True: port.write(bytearray.fromhex("FF FF 01 05 03 1E 32 03 A3")) #time.sleep(0.1) #GPIO.output(2, GPIO.LOW) time.sleep(3) #GPIO.output(2,GPIO.HIGH) port.write(bytearray.fromhex("FF FF 01 05 03 1E CD 00 0b")) #time.sleep(0.1) #GPIO.output(2,GPIO.LOW) time.sleep(3) <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #while True: # port.write(bytearray.fromhex("FF FF 03 05 03 1E 32 03 A1")) # time.sleep(3) # port.write(bytearray.fromhex("FF FF 03 05 03 1E CD 00 09")) # time.sleep(3) port.write(bytearray.fromhex("FF FF 03 05 03 1E 0c 02 c8")) <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #servo1,servo3 while True: port.write(bytearray.fromhex("FF FF 03 05 03 1E 32 03 A1")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 32 03 A3")) time.sleep(3) port.write(bytearray.fromhex("FF FF 03 05 03 1E CD 00 09")) port.write(bytearray.fromhex("FF FF 01 05 03 1E CD 00 0b")) time.sleep(3) <file_sep>import random file = open('generation1.dat', 'w') for i in range(0, 20): for j in range(0, 80): file.write(str(random.randint(0,300) + 362)) if j < 79 : file.write('\t') if i < 19 : file.write('\n') file.close() <file_sep>import serial import time import RPi.GPIO as GPIO port = serial.Serial("/dev/ttyAMA0", baudrate=1000000, timeout=3.0) #left port.write(bytearray.fromhex("FF FF 03 05 03 1E 00 02 D4")) port.write(bytearray.fromhex("FF FF 01 05 03 1E 00 02 D6")) time.sleep(0.2) #right port.write(bytearray.fromhex("FF FF 05 05 03 1E 00 02 D2")) port.write(bytearray.fromhex("FF FF 02 05 03 1E 00 02 D5"))
6f060e1119c5ecfc32dce47c024e7f11fa3b522d
[ "Python" ]
18
Python
yuki-shark/jisyupro
ab4bd5d37f427ba613caa9800b2ba6284fd39afa
b1bd3310632d31aacb73e1e618d5575bb80ea2d2
refs/heads/master
<repo_name>Mohamed-Eltaher/ecommerce<file_sep>/admin/page.php <?php // condition ? true : false; (shortlisted if) $do = isset($_GET['do']) ? $_GET['do'] : 'mange'; // if the page is the main page if ( $do == 'manage') { echo 'welcome you are in manage category page'; echo '<a href="?do=insert"> Add New Category +</a>'; } elseif ($do == 'add') { echo 'you are in add page'; } elseif ($do == 'insert') { echo 'you are in insert page'; } else { echo 'error there is no such page'; } <file_sep>/admin/comments.php <?php /* ============================================ == Manage Comments Page == Here you can edit, delete comments ============================================= */ session_start(); $pageTitle = 'Comments'; if (isset($_SESSION['Username'])) { include 'init.php'; $do = isset($_GET['do']) ? $_GET['do'] : 'manage'; if ($do == 'manage') { #################################### #### Manage Page #################################### $stmt = $con->prepare("SELECT comments.*, items.Name, users.Username FROM comments INNER JOIN items ON items.Item_ID = comments.item_id INNER JOIN users ON users.UserID = comments.user_id "); $stmt->execute(); $rows = $stmt->fetchAll(); ?> <h1 class="text-center">Manage Comments</h1> <div class="container"> <div class="table-responsive"> <table class="table table-bordered text-center"> <tr class="info"> <td>ID</td> <td>Comment</td> <td>Item</td> <td>Username</td> <td>Added date</td> <td>Control</td> </tr> <?php foreach ($rows as $row) { echo '<tr>'; echo '<td>' . $row['c_id'] . '</td>'; echo '<td>' . $row['comment'] . '</td>'; echo '<td>' . $row['Name'] . '</td>'; echo '<td>' . $row['Username'] . '</td>'; echo '<td>' . $row['comment_date'] . '</td>'; echo "<td> <a href='comments.php?do=Edit&comid=" . $row['c_id'] ."' class='btn btn-success'><i class='fa fa-edit'></i> Edit</a> <a href='comments.php?do=delete&comid=" . $row['c_id'] ."' class='btn btn-danger confirm'><i class='fa fa-close'></i> Delete</a>"; if ($row['status'] == 0 ) { echo "<a href='comments.php?do=approve&comid=" . $row['c_id'] ."' class='btn btn-info'> Approve</a>"; } echo "</td>"; echo '</tr>'; } ?> </table> </div> </div> <?php } elseif ($do == 'delete') { #################################### #### Delete Page #################################### //if condition for security purposes to check if the user exist $comid = isset($_GET['comid']) && is_numeric($_GET['comid']) ? intval($_GET['comid']) : 0; $stmt = $con->prepare("SELECT * FROM comments WHERE c_id = ?"); $stmt->execute(array($comid)); $count = $stmt->rowCount(); if ($count > 0) { $stmt = $con->prepare("DELETE FROM comments WHERE c_id= :zcomment"); $stmt->bindparam(":zcomment", $comid); $stmt->execute(); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record Deleted'; echo "</div>"; } else{ $theMsg = "<div class='alert alert-danger'>There is no comment with this ID</div>"; redirectHome($theMsg, 'back', 5); } } elseif ($do == 'approve') { #################################### #### Activate Page #################################### //if condition for security purposes to check if the user exist $comid = isset($_GET['comid']) && is_numeric($_GET['comid']) ? intval($_GET['comid']) : 0; $stmt = $con->prepare("SELECT * FROM comments WHERE c_id = ? LIMIT 1"); $stmt->execute(array($comid)); $count = $stmt->rowCount(); if ($count > 0) { $stmt = $con->prepare("UPDATE comments SET status = 1 WHERE c_id = ? "); $stmt->execute(array($comid)); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record Activated'; echo "</div>"; redirectHome("", 'back'); } else{ $theMsg = "<div class='alert alert-danger'>There is no member with this ID</div>"; redirectHome($theMsg, 'back', 5); } } elseif ($do == 'Edit') { #################################### #### Edit Page #################################### //if condition for security purposes $comid = isset($_GET['comid']) && is_numeric($_GET['comid']) ? intval($_GET['comid']) : 0; $stmt = $con->prepare("SELECT * FROM comments WHERE c_id = ? LIMIT 1"); $stmt->execute(array($comid)); $comment = $stmt->fetch(); $count = $stmt->rowCount(); if ($count > 0) { ?> <h1 class="text-center">Edit comment</h1> <div class="container"> <form METHOD="POST" action="?do=update" class="form-horizontal"> <input type="hidden" name="comid" value="<?php echo $comid ?>" /> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Comment</label> <div class="col-md-6"> <textarea class="form-control" name="comment"> <?php echo $comment['comment'] ?> </textarea> </div> </div> <div class="form-group"> <div class="col-md-4 col-md-offset-4"> <input type="submit" value="Save" class="form-control btn-primary" autocomplete="new-password"> </div> </div> </form> </div> <?php } else { $theMsg = "<div class='alert alert-danger'>sorry, there is no such id</div>"; redirectHome($theMsg, 5); } } elseif ($do == 'update') { #################################### #### Update Page #################################### echo "<div class='container'>"; echo "<h1 class='text-center'>Update Comment</h1>"; if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Get Variables form the form $id = $_POST['comid']; $comment = $_POST['comment']; // Update the DP with this Info $stmt = $con->prepare("UPDATE comments SET comment = ? WHERE c_id = ? "); $stmt->execute(array($comment, $id)); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record updated'; echo "</div>"; redirectHome("" ,'back', 5); } else { $theMsg = "<div class='alert alert-danger'>sorry you can not browse this page directly</div>"; redirectHome($theMsg, 5); } } echo "</div>"; include $tmp . 'footer.php'; }else{ header('Location: index.php'); exit(); }<file_sep>/index.php <?php session_start(); $pageTitle = 'Home'; include 'init.php'; include $tmp . 'footer.php'; ?> <file_sep>/admin/members.php <?php /* ============================================ == Manage Members Page == Here you can edit, add , delete members ============================================= */ session_start(); $pageTitle = 'Members'; if (isset($_SESSION['Username'])) { include 'init.php'; $do = isset($_GET['do']) ? $_GET['do'] : 'manage'; if ($do == 'manage') { #################################### #### Manage Page #################################### $query = ""; if (isset($_GET['page']) && $_GET['page'] == 'pending') { $query = 'AND RegStatus = 0'; } // select all users except Admin $stmt = $con->prepare("SELECT * FROM users WHERE GroupID != 1 $query"); // execute the statement $stmt->execute(); // Assign the statement to variable $rows = $stmt->fetchAll(); ?> <h1 class="text-center">Manage Member</h1> <div class="container"> <div class="table-responsive"> <table class="table table-bordered text-center"> <tr class="info"> <td>#ID</td> <td>Username</td> <td>Email</td> <td>Fullname</td> <td>Registered date</td> <td>Control</td> </tr> <?php foreach ($rows as $row) { echo '<tr>'; echo '<td>' . $row['UserID'] . '</td>'; echo '<td>' . $row['Username'] . '</td>'; echo '<td>' . $row['Email'] . '</td>'; echo '<td>' . $row['Fullname'] . '</td>'; echo '<td>' . $row['Date'] . '</td>'; echo "<td> <a href='members.php?do=Edit&userid=" . $row['UserID'] ."' class='btn btn-success'><i class='fa fa-edit'></i> Edit</a> <a href='members.php?do=delete&userid=" . $row['UserID'] ."' class='btn btn-danger confirm'><i class='fa fa-close'></i> Delete</a>"; if ($row['RegStatus'] == 0 ) { echo "<a href='members.php?do=activate&userid=" . $row['UserID'] ."' class='btn btn-info'> Activate</a>"; } echo "</td>"; echo '</tr>'; } ?> </table> </div> <a href='members.php?do=add' class="btn btn-primary"><i class="fa fa-plus"></i> new member</a> </div> <?php } elseif ($do == 'delete') { #################################### #### Delete Page #################################### //if condition for security purposes to check if the user exist $userid = isset($_GET['userid']) && is_numeric($_GET['userid']) ? intval($_GET['userid']) : 0; $stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1"); $stmt->execute(array($userid)); $count = $stmt->rowCount(); if ($count > 0) { $stmt = $con->prepare("DELETE FROM users WHERE UserID= :zuser"); $stmt->bindparam(":zuser", $userid); $stmt->execute(); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record Deleted'; echo "</div>"; } else{ $theMsg = "<div class='alert alert-danger'>There is no member with this ID</div>"; redirectHome($theMsg, 'back', 5); } } elseif ($do == 'activate') { #################################### #### Activate Page #################################### //if condition for security purposes to check if the user exist $userid = isset($_GET['userid']) && is_numeric($_GET['userid']) ? intval($_GET['userid']) : 0; $stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1"); $stmt->execute(array($userid)); $count = $stmt->rowCount(); if ($count > 0) { $stmt = $con->prepare("UPDATE users SET RegStatus = 1 WHERE UserID = ? "); $stmt->execute(array($userid)); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record Activated'; echo "</div>"; redirectHome("", 'back'); } else{ $theMsg = "<div class='alert alert-danger'>There is no member with this ID</div>"; redirectHome($theMsg, 'back', 5); } } elseif ($do == 'add') { #################################### #### ADD Page #################################### ?> <h1 class="text-center">Add Member</h1> <div class="container"> <form METHOD="POST" action="?do=insert" class="form-horizontal"> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">User Name</label> <div class="col-md-6"> <input type="text" name="username" class="form-control" autocomplete="off" required="required"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Password</label> <div class="col-md-6"> <input type="<PASSWORD>" name="password" class="form-control password" autocomplete="new-password" required="required"> <i class="show-pass fa fa-eye fa-2x"></i> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Email</label> <div class="col-md-6"> <input type="Email" name="email" class="form-control" autocomplete="off" required="required"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Full Name</label> <div class="col-md-6"> <input type="text" name="fullname" class="form-control" autocomplete="off" required="required"> </div> </div> <div class="form-group"> <div class="col-md-4 col-md-offset-4"> <input type="submit" value="ADD" class="form-control btn-primary"> </div> </div> </form> </div> <?php } elseif ($do == 'insert') { #################################### #### Insert Page #################################### if ($_SERVER['REQUEST_METHOD'] == 'POST') { echo "<div class='container'>"; echo "<h1 class='text-center'>Update Member</h1>"; // Get Variables form the form $user = $_POST['username']; $email = $_POST['email']; $pass = $_POST['<PASSWORD>']; $name = $_POST['fullname']; $hashpass= sha1($_POST['password']); //validation of the form $formErorres = array(); if (strlen($user) < 4 ) { $formErorres[] = "Username can not be less than 4 letters"; } if (empty($user)) { $formErorres[] = "Username can not be empty"; } if (empty($email)) { $formErorres[] = "Email can not be empty"; } if (empty($pass)) { $formErorres[] = "Password can not be empty"; } if (empty($name)) { $formErorres[] = "Full Name can not be empty"; } foreach ($formErorres as $erorr) { echo "<div class='alert alert-danger'> $erorr </div>"; } if (empty($formErorres)) { // check if the member already exist in database $check = checkItem("Username", "users", $user); if ($check == 1) { echo 'Sorry, this member exist in database'; } else{ // insert userinfo into DP $stmt = $con->prepare("INSERT INTO users(Username, Password, Email, Fullname, RegStatus, Date) VALUES(:zuser, :zpass, :zmail, :zname, 1, now()) "); $stmt->execute(array( 'zuser' => $user, 'zpass' => <PASSWORD>, 'zmail' => $email, 'zname' => $name )); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record updated'; echo "</div>"; redirectHome('', 'back'); } } } else { $theMsg = "<div class='alert alert-danger'>sorry, there is no such id</div>"; redirectHome($theMsg, 5); } echo "</div>"; } elseif ($do == 'Edit') { #################################### #### Edit Page #################################### //if condition for security purposes $userid = isset($_GET['userid']) && is_numeric($_GET['userid']) ? intval($_GET['userid']) : 0; $stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1"); $stmt->execute(array($userid)); $row = $stmt->fetch(); $count = $stmt->rowCount(); if ($count > 0) { ?> <h1 class="text-center">Edit Member</h1> <div class="container"> <form METHOD="POST" action="?do=update" class="form-horizontal"> <input type="hidden" name="userid" value="<?php echo $userid ?>" /> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">User Name</label> <div class="col-md-6"> <input type="text" name="username" class="form-control" value="<?php echo $row['Username'] ?>" autocomplete="off" required="required"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Password</label> <div class="col-md-6"> <input type="hidden" name="old-password" value="<?php echo $row['Password'] ?>" /> <input type="Password" name="new-password" class="form-control" autocomplete="new-password"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Email</label> <div class="col-md-6"> <input type="Email" name="email" class="form-control" value="<?php echo $row['Email'] ?>" autocomplete="off" required="required"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Full Name</label> <div class="col-md-6"> <input type="text" name="fullname" class="form-control" value="<?php echo $row['Fullname'] ?>" autocomplete="off" required="required"> </div> </div> <div class="form-group"> <div class="col-md-4 col-md-offset-4"> <input type="submit" value="Update" class="form-control btn-primary" autocomplete="new-password"> </div> </div> </form> </div> <?php } else { $theMsg = "<div class='alert alert-danger'>sorry, there is no such id</div>"; redirectHome($theMsg, 5); } } elseif ($do == 'update') { #################################### #### Update Page #################################### echo "<div class='container'>"; echo "<h1 class='text-center'>Update Member</h1>"; if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Get Variables form the form $id = $_POST['userid']; $user = $_POST['username']; $email = $_POST['email']; $name = $_POST['fullname']; // password trick $pass = empty($_POST['new-password']) ? $_POST['old-password'] : sha1($_POST['new-password']); //validation of the form $formErorres = array(); if (strlen($user) < 4 ) { $formErorres[] = "Username can not be less than 4 letters"; } if (empty($user)) { $formErorres[] = "Username can not be empty"; } if (empty($email)) { $formErorres[] = "Email can not be empty"; } if (empty($name)) { $formErorres[] = "Full Name can not be empty"; } foreach ($formErorres as $erorr) { echo "<div class='alert alert-danger'> $erorr </div>"; } if (empty($formErorres)) { // Update the DP with this Info $stmt = $con->prepare("UPDATE users SET Username = ?, Email = ?, Fullname = ?, Password = ? WHERE UserID = ? "); $stmt->execute(array($user, $email, $name, $pass, $id)); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record updated'; echo "</div>"; redirectHome("" ,'back', 5); } } else { $theMsg = "<div class='alert alert-danger'>sorry you can not browse this page directly</div>"; redirectHome($theMsg, 5); } } echo "</div>"; include $tmp . 'footer.php'; }else{ header('Location: index.php'); exit(); }<file_sep>/categories.php <?php include 'init.php'; ?> <div class="container"> <h1 class="text-center"> <?php echo $_GET['pagename']; ?> </h1> <div class="row"> <?php $items = getItems($_GET['pageid']); foreach ($items as $item) { echo "<div class='col-md-4'>"; echo "<div class='item text-center'>"; echo "<div class='img-thumbnail'>"; echo "<img class='img-responsive' src='https://placeholdit.co//i/350x200' alt=''>"; echo "<span class='price'>" . $item['Price'] . "</span>"; echo "<span class='country'>" . $item['Country_Made'] . "</span>"; echo "</div>"; echo "<div class='clearfix'> </div>"; echo "<span>"; echo "<strong>" . $item['Name'] . "</strong>"; echo "</span>"; echo "<p>"; echo $item['Description']; echo "</p>"; echo "</div>"; echo "</div>"; } ?> </div> </div> <?php include $tmp . 'footer.php'; ?> <file_sep>/admin/categories.php <?php /* ================================================ == Template Page ================================================ */ ob_start(); // Output Buffering Start session_start(); $pageTitle = 'Categories'; if (isset($_SESSION['Username'])) { include 'init.php'; $do = isset($_GET['do']) ? $_GET['do'] : 'Manage'; if ($do == 'Manage') { #################################### #### Manage Page #################################### $sort = 'DESC'; $sort_array = array('ASC', 'DESC'); if ( isset($_GET['sort']) && in_array($_GET['sort'], $sort_array)) { $sort = $_GET['sort']; } $stmt = $con->prepare("SELECT * FROM categories ORDER BY Ordering $sort"); // execute the statement $stmt->execute(); // Assign the statement to variable $cats = $stmt->fetchAll(); ?> <div class="container"> <h1 class="text-center">Manage Categories</h1> <div class="panel panel-default"> <div class="panel-heading">Manage Categories <div class="options pull-right"> <strong>Order BY</strong> <a class="<?php if ($sort == 'ASC') {echo 'active';} ?>" href="?sort=ASC">ASC</a> | <a class="<?php if ($sort == 'DESC') {echo 'active';} ?>" href="?sort=DESC">DESC</a> <strong>View</strong> <span data-view="full">Full</span> | <span data-view="classic">Classic</span> </div> </div> <div class="panel-body"> <?php foreach ($cats as $cat) { ?> <div class="cat clearfix"> <div class="hidden-buttons"> <a href="categories.php?do=Edit&catid=<?php echo $cat['ID'] ?>" class="pull-right label label-info">Edit</a> <a class='label label-danger pull-right confirm' href="categories.php?do=delete&catid=<?php echo $cat['ID'] ?>" >Delete</a> </div> <?php echo "<h3>" . $cat['Name'] . "</h3>"; echo '<div class="full-view">'; echo "<p>" . $cat['Description'] . "</p>" ; echo "<span class='label label-primary'> Order Number " . $cat['Ordering'] . "</span>"; if ($cat['Visibility'] == 1) { echo "<span class='label label-default'>Hidden Item </span>"; }; if ($cat['Allow_comment'] == 1) { echo "<span class='label label-danger'>Comments are disabled </span>"; }; if ($cat['Allow_Ads'] == 1) { echo "<span class='label label-warning'>Ads are disabled </span>"; }; echo '</div>'; echo '<hr>'; } ?> </div> <a class='btn btn-primary' href="categories.php?do=add&catid" >Add New Category</a> </div> </div> </div> <?php } elseif ($do == 'add') { #################################### #### ADD Page #################################### ?> <h1 class="text-center">Add Category</h1> <div class="container"> <form METHOD="POST" action="?do=insert" class="form-horizontal"> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1"> Name</label> <div class="col-md-6"> <input type="text" name="name" class="form-control" autocomplete="off" required="required"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Description</label> <div class="col-md-6"> <input type="text" name="description" class="form-control"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Ordering</label> <div class="col-md-6"> <input type="number" name="ordering" class="form-control" autocomplete="off"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Visible</label> <div class="col-md-6"> <div> <input type='radio' id='vis-yes' name=visibility value='0' checked /> <label for="vis-yes">Yes</label> </div> <div> <input type='radio' id='vis-no' name=visibility value='1' /> <label for="vis-no">No</label> </div> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Allow Commenting</label> <div class="col-md-6"> <div> <input type='radio' id='comment-yes' name='commenting' value='0' checked /> <label for="comment-yes">Yes</label> </div> <div> <input type='radio' id='comment-no' name='commenting' value='1' /> <label for="comment-no">No</label> </div> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Allow Ads</label> <div class="col-md-6"> <div> <input type='radio' id='ads-yes' name="ads" value='0' checked /> <label for="ads-yes">Yes</label> </div> <div> <input type='radio' id='ads-no' name="ads" value='1' /> <label for="ads-no">No</label> </div> </div> </div> <div class="form-group"> <div class="col-md-4 col-md-offset-4"> <input type="submit" value="ADD Category" class="form-control btn-primary"> </div> </div> </form> </div> <?php } elseif ($do == 'insert') { #################################### #### Insert Page #################################### if ($_SERVER['REQUEST_METHOD'] == 'POST') { echo "<div class='container'>"; echo "<h1 class='text-center'>Update Member</h1>"; // Get Variables form the form $name = $_POST['name']; $desc = $_POST['description']; $order = $_POST['ordering']; $visible = $_POST['visibility']; $comment = $_POST['commenting']; $ads = $_POST['ads']; // check if the member already exist in database $check = checkItem("name", "categories", $name); if ($check == 1) { echo 'Sorry, this member exist in database'; } else{ // insert userinfo into DP $stmt = $con->prepare("INSERT INTO categories(Name, Description, Ordering, Visibility, Allow_comment, Allow_Ads) VALUES(:zname, :zdesc, :zorder, :zvisibile, :zcommenter, :zads)"); $stmt->execute(array( 'zname' => $name, 'zdesc' => $desc, 'zorder' => $order, 'zvisibile' => $visible, 'zcommenter' => $comment, 'zads' => $ads )); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record updated'; echo "</div>"; redirectHome('', 'back'); } } else { $theMsg = "<div class='alert alert-danger'>sorry, there is no such id</div>"; redirectHome($theMsg, 5); } echo "</div>"; } elseif ($do == 'Edit') { #################################### #### Edit Page #################################### //if condition for security purposes $catid = isset($_GET['catid']) && is_numeric($_GET['catid']) ? intval($_GET['catid']) : 0; $stmt = $con->prepare("SELECT * FROM categories WHERE ID = ?"); $stmt->execute(array($catid)); $cat = $stmt->fetch(); $count = $stmt->rowCount(); if ($count > 0) { ?> <h1 class="text-center">Edit Category</h1> <div class="container"> <form METHOD="POST" action="?do=update" class="form-horizontal"> <input type="hidden" name="catid" value="<?php echo $catid ?>" /> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1"> Name</label> <div class="col-md-6"> <input type="text" name="name" class="form-control" required="required" value="<?php echo $cat['Name'] ?>"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Description</label> <div class="col-md-6"> <input type="text" name="description" class="form-control" value="<?php echo $cat['Description'] ?>"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Ordering</label> <div class="col-md-6"> <input type="number" name="ordering" class="form-control" value="<?php echo $cat['Ordering'] ?>"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Visible</label> <div class="col-md-6"> <div> <input type='radio' id='vis-yes' name=visibility value='0' <?php if( $cat['Visibility'] == 0) {echo 'checked';} ?> /> <label for="vis-yes">Yes</label> </div> <div> <input type='radio' id='vis-no' name=visibility value='1' <?php if( $cat['Visibility'] == 1) {echo 'checked';} ?> /> <label for="vis-no">No</label> </div> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Allow Commenting</label> <div class="col-md-6"> <div> <input type='radio' id='comment-yes' name='commenting' value='0' <?php if( $cat['Allow_comment'] == 0) {echo 'checked';} ?> /> <label for="comment-yes">Yes</label> </div> <div> <input type='radio' id='comment-no' name='commenting' value='1' <?php if( $cat['Allow_comment'] == 1) {echo 'checked';} ?> /> <label for="comment-no">No</label> </div> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Allow Ads</label> <div class="col-md-6"> <div> <input type='radio' id='ads-yes' name="ads" value='0' <?php if( $cat['Allow_Ads'] == 0) {echo 'checked';} ?> /> <label for="ads-yes">Yes</label> </div> <div> <input type='radio' id='ads-no' name="ads" value='1' <?php if( $cat['Allow_Ads'] == 1) {echo 'checked';} ?> /> <label for="ads-no">No</label> </div> </div> </div> <div class="form-group"> <div class="col-md-4 col-md-offset-4"> <input type="submit" value="Update Category" class="form-control btn-primary"> </div> </div> </form> </div> <?php } else { $theMsg = "<div class='alert alert-danger'>sorry, there is no such id</div>"; redirectHome($theMsg, 5); } } elseif ($do == 'update') { #################################### #### Update Page #################################### echo "<div class='container'>"; echo "<h1 class='text-center'>Update Category</h1>"; if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Get Variables form the form $id = $_POST['catid']; $name = $_POST['name']; $desc = $_POST['description']; $order = $_POST['ordering']; $visible = $_POST['visibility']; $comment = $_POST['commenting']; $ads = $_POST['ads']; // Update the DP with this Info $stmt = $con->prepare("UPDATE categories SET Name = ?, Description = ?, Ordering = ?, Visibility = ?, Allow_comment = ?, Allow_Ads = ? WHERE ID = ? "); $stmt->execute(array($name, $desc, $order, $visible, $comment, $ads, $id)); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record updated'; echo "</div>"; redirectHome("" ,'back'); } } elseif ($do == 'delete') { #################################### #### Delete Page #################################### //if condition for security purposes to check if the user exist $catid = isset($_GET['catid']) && is_numeric($_GET['catid']) ? intval($_GET['catid']) : 0; $check = checkItem('ID', 'categories', $catid); if ($check > 0) { $stmt = $con->prepare("DELETE FROM categories WHERE ID= :zcat"); $stmt->bindparam(":zcat", $catid); $stmt->execute(); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record Deleted'; echo "</div>"; redirectHome(' ', 'back'); } else{ $theMsg = "<div class='alert alert-danger'>There is no member with this ID</div>"; redirectHome($theMsg, 'back', 5); } }; include $tmp . 'footer.php'; } else { header('Location: index.php'); exit(); } ob_end_flush(); // Release The Output ?><file_sep>/login.php <?php session_start(); $pageTitle = 'login'; // if the user is registedred in the session, take him to the DashB if (isset($_SESSION['member'])) { header('Location: index.php'); }; include 'init.php'; // Check If User Coming From HTTP Post Request if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['user']; $password = $_POST['pass']; $hashedPass = sha1($password); // for security purposes we use sha1 // Check If The User Exist In Database $stmt = $con->prepare("SELECT Username, Password FROM users WHERE Username = ? AND Password = ? "); $stmt->execute(array($username, $hashedPass)); $count = $stmt->rowCount(); // If Count > 0 This Mean The Database Contain Record About This Username if ($count > 0) { $_SESSION['member'] = $username; // Register Session Name header('Location: index.php'); // Redirect To Dashboard Page exit(); } } ?> <div class="container"> <div class="login-page"> <h1 class="text-center in-out"> <span data-class="login" class='selected'>Login</span> | <span data-class="signup">Signup</span> </h1> <!-- Start Login Form --> <form class="login inlog" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <div class="form-group"> <input class="form-control input-lg" type="text" name="user" placeholder="type your username" autocomplete="off" required="required" /> </div> <div class="form-group"> <input class="form-control input-lg" type="password" name="pass" placeholder=" type your password" autocomplete="new-password" required="required" /> </div> <input class="btn btn-primary btn-lg btn-block" type="submit" value="login" /> </form> <!-- End Login Form --> <!-- Start Signup Form --> <form class="signup inlog" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <div class="form-group"> <input class="form-control input-lg" type="text" name="user" placeholder="type your username" autocomplete="off" required="required" /> </div> <div class="form-group"> <input class="form-control input-lg" type="<PASSWORD>" name="pass" placeholder=" type your password" autocomplete="new-password" required="required" /> </div> <div class="form-group"> <input class="form-control input-lg" type="email" name="email" placeholder="type your Email" autocomplete="off" required="required" /> </div> <input class="btn btn-success btn-lg btn-block" type="Signout" value="signout" /> </form> <!-- End Signup Form --> </div> </div> <?php include $tmp . 'footer.php'; ?> <file_sep>/init.php <?php // Error Reporting ini_set('display_errors', 'on'); error_reporting(E_ALL); include 'admin/connect.php'; // so if you needed db, just include init.php in your page // Registering session user in a var to use it everywhere $sessionUser = ""; if (isset($_SESSION['member'])) { $sessionUser = $_SESSION['member']; } // Routes $func = 'includes/functions/'; // functions Directory $lang= 'includes/langs/'; // Lang Directory $tmp = 'includes/templates/'; // Templates Directory $css = 'admin/layout/css/'; // css Directory $frontcss = 'layout/css/'; // frontend css Directory $js = 'admin/layout/js/'; // js Directory $frontjs = 'layout/js/'; // Frontend js Directory include $func . 'functions.php'; include $lang . 'english.php'; include $tmp . 'header.php'; <file_sep>/includes/templates/header.php <!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"> <title><?php echo page_title(); ?></title> <link rel="stylesheet" href="<?php echo $css;?>font-awesome.min.css"> <link rel="stylesheet" href="<?php echo $css;?>bootstrap.min.css"> <link rel="stylesheet" href="<?php echo $frontcss;?>frontend.css"> </head> <body> <div class="upper-bar"> <div class="container"> <?php if (isset($_SESSION['member'])){ echo ' Hello' . ' ' . $sessionUser . ' ' . "<a href='profile.php'>My Profile</a> - <a href='logout.php'>logout</a>" . '</br>'; $userstatus = userStatus($sessionUser); if ($userstatus == 1) { echo "Your Membership need to be activated"; } } else { ?> <a class='pull-right' href="login.php">Login | Logout</a> <?php } ?> </div> </div> <nav class="navbar navbar-inverse"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php">HomePage</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <?php $categories = getCats(); foreach ($categories as $category) { echo "<li> <a href='categories.php?pageid=" . $category['ID'] ."&pagename=" . $category['Name'] ."'>" . $category['Name'] . "</a> </li>"; } ?> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container --> </nav> <file_sep>/profile.php <?php session_start(); $pageTitle = 'Profile'; include 'init.php'; ?> <h1 class="text-center"><?php echo $sessionUser; ?> Profile</h1> <div class="my-information"> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading">My Information</div> <div class="panel-body"> test info </div> </div> </div> </div> <div class="ads"> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading">My Ads</div> <div class="panel-body"> test ads </div> </div> </div> </div> <div class="my-comments"> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading">Latest Comments</div> <div class="panel-body"> test comments </div> </div> </div> </div> <?php include $tmp . 'footer.php'; ?> <file_sep>/includes/langs/english.php <?php // common function for langs. you can find it in google function lang($phrase) { static $lang = array( // Navbar keys 'Logo' => 'Home', 'cat' => 'Categories', 'item' => 'Items', 'member' => 'Members', 'comments' => 'Comments', 'statistic' => 'Statistics', 'log' => 'Logs', 'name' => 'Eltaher', ); return $lang[$phrase]; } <file_sep>/admin/dashboard.php <?php session_start(); if (isset($_SESSION['Username'])) { $pageTitle = 'Dashboard'; include 'init.php'; // get latest users function $latestUser = 5; $getLatestUsers = getLatest("*", "users", "UserID", $latestUser); $latestItem = 5; $getLatestitem = getLatest("*", "items", "Item_ID", $latestItem); $latestcom = 2; /* start Dashborad page */ ?> <div class="container"> <h1 class="text-center">DashBoard</h1> <div class="main text-center"> <div class="row"> <div class="col-md-3"> <div class="states"> Total Members <span><a href="members.php"><?php echo countItems('UserId', 'users') ?></a></span> </div> </div> <div class="col-md-3"> <div class="states"> Pending Members <span> <a href="members.php?do=manage&page=pending"><?php echo checkItem('RegStatus', 'users', 0) ?> </a> </span> </div> </div> <div class="col-md-3"> <div class="states"> Total Items <span> <a href="items.php"><?php echo countItems('Item_ID', 'items') ?></a> </span> </div> </div> <div class="col-md-3"> <div class="states"> Total Comments <span> <a href="comments.php"><?php echo countItems('c_id', 'comments') ?></a> </span> </div> </div> </div> </div> <div class="panels"> <div class="row"> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading toggle-info">Latest <?php echo $latestUser; ?> Registered Users <i class="fa fa-minus pull-right"></i> </div> <div class="panel-body"> <?php if (!empty($getLatestUsers)) { foreach ($getLatestUsers as $user) { ?> <li class="list-unstyled clearfix"> <?php echo $user['Username']; ?> <a class='btn btn-primary pull-right' href="members.php?do=Edit&userid=<?php echo $user['UserID'] ?>" >Edit</a> <?php $row = userStatus($user['Username']); if ($user['RegStatus'] == 0 ) { echo "<a href='members.php?do=activate&userid=" . $user['UserID'] ."' class='btn btn-info pull-right'> Activate</a>"; } ?> </li> <?php } } else{ echo ' there is no users to show';} ?> </div> </div> </div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading toggle-info">Latest <?php echo $latestItem; ?> Items <i class="fa fa-minus pull-right"></i> </div> <div class="panel-body"> <?php if (!empty($getLatestitem)) { foreach ($getLatestitem as $item) { ?> <li class="list-unstyled clearfix"> <?php echo $item['Name']; ?> <a class='btn btn-primary pull-right' href="items.php?do=Edit&itemid=<?php echo $item['Item_ID'] ?> " >Edit</a> <?php if ($item['Approve'] == 0 ) { echo "<a href='items.php?do=approve&itemid=" . $item['Item_ID'] ."' class='btn btn-info pull-right'><i class='fa fa-check'></i> Approve</a>"; } ?> </li> <?php } } else{echo ' there is no items here';} ?> </div> </div> </div> </div> <!-- start comments row --> <div class="row"> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading toggle-info">Latest Comments <i class="fa fa-comment-o pull-right"></i> </div> <div class="panel-body"> <?php $stmt = $con->prepare("SELECT comments.*, users.Username FROM comments INNER JOIN users ON users.UserID = comments.user_id ORDER BY c_id DESC LIMIT $latestcom "); $stmt->execute(); $comments = $stmt->fetchAll(); if (!empty($comments)) { foreach ($comments as $comment) { echo "<span>"; echo "<a href='members.php?do=Edit&userid=" . $comment['c_id'] . "'>" . $comment['Username'] . "</a>"; echo "</span>"; echo "<p>" . $comment['comment'] . "</p>"; } } else {echo "No Comments to show";} ?> </div> </div> </div> </div> <!--end comments row--> </div> </div> <?php /* end Dashborad page */ include $tmp . 'footer.php'; }else{ header('Location: index.php'); exit(); }<file_sep>/admin/init.php <?php include 'connect.php'; // so if you needed db, just include init.php in your page // Routes $func = 'includes/functions/'; // functions Directory $lang= 'includes/langs/'; // Lang Directory $tmp = 'includes/templates/'; // Templates Directory $css = 'layout/css/'; // css Directory $js = 'layout/js/'; // js Directory include $func . 'functions.php'; include $lang . 'english.php'; include $tmp . 'header.php'; if (!isset($noNavbar)){include $tmp . 'navbar.php';} <file_sep>/admin/items.php <?php /* ================================================ == Items Page ================================================ */ ob_start(); // Output Buffering Start session_start(); $pageTitle = 'Items'; if (isset($_SESSION['Username'])) { include 'init.php'; $do = isset($_GET['do']) ? $_GET['do'] : 'Manage'; if ($do == 'Manage') { #################################### #### Manage Page #################################### $stmt = $con->prepare(" SELECT items.*, categories.Name AS category_name, users.Username FROM items INNER JOIN categories ON categories.ID = items.Cat_ID INNER JOIN users ON users.UserID = items.Member_ID "); // execute the statement $stmt->execute(); // Assign the statement to variable $items = $stmt->fetchAll(); ?> <h1 class="text-center">Manage Items</h1> <div class="container"> <div class="table-responsive"> <table class="table table-bordered text-center"> <tr class="info"> <td>#ID</td> <td>name</td> <td>Description</td> <td>Price</td> <td>Adding date</td> <td>Category</td> <td>UserName</td> <td>Control</td> </tr> <?php foreach ($items as $item) { echo '<tr>'; echo '<td>' . $item['Item_ID'] . '</td>'; echo '<td>' . $item['Name'] . '</td>'; echo '<td>' . $item['Description'] . '</td>'; echo '<td>' . $item['Price'] . '</td>'; echo '<td>' . $item['Add_Date'] . '</td>'; echo '<td>' . $item['category_name'] . '</td>'; echo '<td>' . $item['Username'] . '</td>'; echo "<td> <a href='items.php?do=Edit&itemid=" . $item['Item_ID'] ."' class='btn btn-success'><i class='fa fa-edit'></i> Edit</a> <a href='items.php?do=delete&itemid=" . $item['Item_ID'] ."' class='btn btn-danger confirm'><i class='fa fa-close'></i> Delete</a>"; if ($item['Approve'] == 0 ) { echo "<a href='items.php?do=approve&itemid=" . $item['Item_ID'] ."' class='btn btn-info'><i class='fa fa-check'></i> Approve</a>"; } echo "</td>"; echo '</tr>'; } ?> </table> </div> <a href='items.php?do=add' class="btn btn-primary"><i class="fa fa-plus"></i> new Item</a> </div> <?php } elseif ($do == 'add') { #################################### #### ADD Page #################################### ?> <h1 class="text-center">Add Item</h1> <div class="container"> <form METHOD="POST" action="?do=insert" class="form-horizontal"> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1"> Item Name</label> <div class="col-md-6"> <input type="text" name="item-name" class="form-control" autocomplete="off" required="required"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Description</label> <div class="col-md-6"> <input type="text" name="description" class="form-control"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Price</label> <div class="col-md-6"> <input type="text" name="price" class="form-control"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Counrty</label> <div class="col-md-6"> <input type="text" name="country" class="form-control"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Status</label> <div class="col-md-6"> <select class="form-control" name='rating'> <option value=0>A</option> <option value=1>B</option> <option value=2>C</option> <option value=3>D</option> </select> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Users</label> <div class="col-md-6"> <select class="form-control" name='member'> <option value='0'>...</option> <?php $stmt2 = $con->prepare("SELECT * FROM users"); $stmt2->execute(); $users = $stmt2->fetchAll(); foreach ($users as $user) { echo "<option value='" . $user['UserID'] . "'>" . $user['Username'] . "</option>"; } ?> </select> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Categories</label> <div class="col-md-6"> <select class="form-control" name='category'> <option value='0'>...</option> <?php $stmt = $con->prepare("SELECT * FROM categories"); $stmt->execute(); $cats = $stmt->fetchAll(); foreach ($cats as $cat) { echo "<option value='" . $cat['ID'] . "'>" . $cat['Name'] . "</option>"; } ?> </select> </div> </div> <div class="form-group"> <div class="col-md-4 col-md-offset-4"> <input type="submit" value="ADD Item" class="form-control btn-primary"> </div> </div> </form> </div> <?php } elseif ($do == 'insert') { #################################### #### Insert Page #################################### if ($_SERVER['REQUEST_METHOD'] == 'POST') { echo "<div class='container'>"; echo "<h1 class='text-center'>Update Item</h1>"; // Get Variables form the form $name = $_POST['item-name']; $desc = $_POST['description']; $price = $_POST['price']; $country = $_POST['country']; $status = $_POST['rating']; $users = $_POST['member']; $categories = $_POST['category']; // insert userinfo into DP $stmt = $con->prepare("INSERT INTO items(Name, Description, Price, Country_Made, Status, Add_Date, Member_ID, Cat_ID) VALUES(:zname, :zdesc, :zprice, :zcountry, :zstatus, now(), :zmember, :zcatid)"); $stmt->execute(array( 'zname' => $name, 'zdesc' => $desc, 'zprice' => $price, 'zcountry' => $country, 'zstatus' => $status, 'zmember' => $users, 'zcatid' => $categories, )); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record updated'; echo "</div>"; redirectHome('', 'back'); } else { $theMsg = "<div class='alert alert-danger'>sorry, there is no such id</div>"; redirectHome($theMsg, 5); } echo "</div>"; } elseif ($do == 'Edit') { #################################### #### Edit Page #################################### //if condition for security purposes $itemid = isset($_GET['itemid']) && is_numeric($_GET['itemid']) ? intval($_GET['itemid']) : 0; $stmt = $con->prepare("SELECT * FROM items WHERE Item_ID = ?"); $stmt->execute(array($itemid)); $item = $stmt->fetch(); $count = $stmt->rowCount(); if ($count > 0) { ?> <h1 class="text-center">Edit Item</h1> <div class="container"> <form METHOD="POST" action="?do=update" class="form-horizontal"> <input type="hidden" name="itemid" value="<?php echo $itemid ?>" /> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1"> Item Name</label> <div class="col-md-6"> <input type="text" name="item-name" class="form-control" autocomplete="off" required="required" value="<?php echo $item['Name'] ?>"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Description</label> <div class="col-md-6"> <input type="text" name="description" class="form-control" value="<?php echo $item['Description'] ?>"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Price</label> <div class="col-md-6"> <input type="text" name="price" class="form-control" value="<?php echo $item['Price'] ?>"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Counrty</label> <div class="col-md-6"> <input type="text" name="country" class="form-control" value="<?php echo $item['Country_Made'] ?>"> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Status</label> <div class="col-md-6"> <select class="form-control" name='rating'> <option value=0 <?php if ( $item['Status'] == 0) {echo 'selected';} ?> >A</option> <option value=1 <?php if ( $item['Status'] == 1) {echo 'selected';} ?> >B</option> <option value=2 <?php if ( $item['Status'] == 2) {echo 'selected';} ?>>C</option> <option value=3 <?php if ( $item['Status'] == 3) {echo 'selected';} ?>>D</option> </select> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Users</label> <div class="col-md-6"> <select class="form-control" name='member'> <?php $stmt2 = $con->prepare("SELECT * FROM users"); $stmt2->execute(); $users = $stmt2->fetchAll(); foreach ($users as $user) { echo "<option value='" . $user['UserID'] . "'"; if ( $item['Member_ID'] == $user['UserID']) { echo 'selected';} echo ">" . $user['Username'] . "</option>"; } ?> </select> </div> </div> <div class="form-group form-group-lg"> <label class="control-label col-md-2 col-md-offset-1">Categories</label> <div class="col-md-6"> <select class="form-control" name='category'> <?php $stmt = $con->prepare("SELECT * FROM categories"); $stmt->execute(); $cats = $stmt->fetchAll(); foreach ($cats as $cat) { echo "<option value='" . $cat['ID'] . "'"; if ( $item['Cat_ID'] == $cat['ID']) { echo 'selected';} echo ">" . $cat['Name'] . "</option>"; } ?> </select> </div> </div> <div class="form-group"> <div class="col-md-4 col-md-offset-4"> <input type="submit" value="Update Item" class="form-control btn-primary"> </div> </div> </form> <?php #################################### #### Manage Comments #################################### $stmt = $con->prepare("SELECT comments.*, users.Username FROM comments INNER JOIN users ON users.UserID = comments.user_id WHERE item_id = ? "); $stmt->execute(array($itemid)); $rows = $stmt->fetchAll(); if (!empty($rows)) { ?> <h1 class="text-center">Manage <?php echo $item['Name'] ?> Comments</h1> <div class="table-responsive"> <table class="table table-bordered text-center"> <tr class="info"> <td>Comment</td> <td>Username</td> <td>Added date</td> <td>Control</td> </tr> <?php foreach ($rows as $row) { echo '<tr>'; echo '<td>' . $row['comment'] . '</td>'; echo '<td>' . $row['Username'] . '</td>'; echo '<td>' . $row['comment_date'] . '</td>'; echo "<td> <a href='comments.php?do=Edit&comid=" . $row['c_id'] ."' class='btn btn-success'><i class='fa fa-edit'></i> Edit</a> <a href='comments.php?do=delete&comid=" . $row['c_id'] ."' class='btn btn-danger confirm'><i class='fa fa-close'></i> Delete</a>"; if ($row['status'] == 0 ) { echo "<a href='comments.php?do=approve&comid=" . $row['c_id'] ."' class='btn btn-info'> Approve</a>"; } echo "</td>"; echo '</tr>'; } ?> </table> </div> <?php } ?> </div> <?php } else { $theMsg = "<div class='alert alert-danger'>sorry, there is no such id</div>"; redirectHome($theMsg, 5); } } elseif ($do == 'update') { #################################### #### Update Page #################################### echo "<div class='container'>"; echo "<h1 class='text-center'>Update Item</h1>"; if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Get Variables form the form $id = $_POST['itemid']; $name = $_POST['item-name']; $desc = $_POST['description']; $price = $_POST['price']; $country = $_POST['country']; $status = $_POST['rating']; $users = $_POST['member']; $categories = $_POST['category']; // Update the DP with this Info $stmt = $con->prepare("UPDATE items SET Name = ?, Description = ?, Price = ?, Country_Made = ?, Status = ?, Member_ID = ?, Cat_ID = ? WHERE Item_ID = ? "); $stmt->execute(array($name, $desc, $price, $country, $status, $users, $categories, $id)); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record updated'; echo "</div>"; redirectHome("" ,'back'); } } elseif ($do == 'delete') { #################################### #### Delete Page #################################### //if condition for security purposes to check if the user exist $itemid = isset($_GET['itemid']) && is_numeric($_GET['itemid']) ? intval($_GET['itemid']) : 0; $check = checkItem('Item_ID', 'items', $itemid); if ($check > 0) { $stmt = $con->prepare("DELETE FROM items WHERE Item_ID= :zitem"); $stmt->bindparam(":zitem", $itemid); $stmt->execute(); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record Deleted'; echo "</div>"; redirectHome(' ', 'back'); } else{ $theMsg = "<div class='alert alert-danger'>There is no member with this ID</div>"; redirectHome($theMsg, 'back', 5); } } elseif($do == 'approve') { #################################### #### Approve Page #################################### //if condition for security purposes to check if the user exist $itemid = isset($_GET['itemid']) && is_numeric($_GET['itemid']) ? intval($_GET['itemid']) : 0; $stmt = $con->prepare("SELECT * FROM items WHERE Item_ID = ?"); $stmt->execute(array($itemid)); $count = $stmt->rowCount(); if ($count > 0) { $stmt = $con->prepare("UPDATE items SET Approve = 1 WHERE Item_ID = ? "); $stmt->execute(array($itemid)); // echo success message ?> <div class='alert alert-success'> <?php echo $stmt->rowCount() . 'Record Approved'; echo "</div>"; redirectHome("", 'back'); } else{ $theMsg = "<div class='alert alert-danger'>There is no member with this ID</div>"; redirectHome($theMsg, 'back', 5); } } include $tmp . 'footer.php'; } else { header('Location: index.php'); exit(); } ob_end_flush(); // Release The Output ?>
ae6e262a363d44c39d8436ba2044cb7b95d823e0
[ "PHP" ]
14
PHP
Mohamed-Eltaher/ecommerce
01e648b91469a96a2a35960337ef7d3856d8bc64
d94c2eac65c81a7af8320f328dbf5dd1c5fcd6ce
refs/heads/master
<file_sep><!doctype html> <html lang="ru"> <head> <title>Продвижение в социальных сетях Facebook и Instagram - WeDo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="description" content="SMM. Таргетированная реклама в Facebook и Instagram. Привлечение подписчиков и клиентов. Узнайте, сколько клиентов получите! Бесплатная консультация."> <meta name="yandex-verification" content="80567c69a37b1299" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link rel="stylesheet" href="<?=$templateUriA?>/css/main.css"> <script src="<?=$templateUriA?>/js/jquery.selectric.js"></script> <script src="<?=$templateUriA?>/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=$templateUriA?>/img/logo_fav.ico" type="image/x-icon"> </head> <body> <div class="head-smm"> <div class="container head-content"> <div class="row top-line"> <div class="col-4 col-md-5 col-lg-6"> <div class="logo"> <a href="#"><img src="<?=$templateUriA?>/img/logo-green.png" alt="WeDo"></a> </div> </div> <div class="col-6 col-md-6 col-lg-5"> <div class="phone"> <a href="tel:+38(098)151-20-15">+38(098)151-20-15</a> </div> </div> <div class="col-2 col-md-1 col-lg-1"> <div class="hamburger-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <nav class="nav-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <ul class="main-menu"> <li><a href="/">Главная</a></li> <li><a href="/sozdanie-saitov/">Создание сайтов</a></li> <li><a href="/internet-magaziny/">Создание интернет-магазинов</a></li> <li><a href="/kontekstnaya-reklama/">Контекстная реклама</a></li> <li><a href="/seo/">SEO-продвижение</a></li> <li><a href="/smm/">SMM</a></li> <li class="current_page"><a href="/blog/">Блог</a></li> </ul> </nav> </div> </div> </div> <div class="row center-line"> <div class="col"> <h1 class="title-page-marketing"> <span class="h1 h1_smm">SMM</span> <span class="h1_text h1_text_smm">Таргетированная реклама в социальных сетях Facebook и Instagram</span> </h1> </div> </div> <div class="row bottom-line"> <div class="col"> <p>Вашему бизнесу подойдёт продвижение в социальных сетях?</p> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-discover-smm" data-wipe="Узнать">Узнать</a> </div> </div> </div> </div> </div> </div> </div> <div class="container"> <div class="whom-smm"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Продвижение в социальных сетях с помощью таргетированной рекламы будет полезно компаниям:</h2> </div> </div> <div class="row content-section"> <div class="col-lg-4"> <div class="wrap-block"> <img src="<?=$templateUriA?>/img/icons/insta-like1.png" alt="like"> <p>Работающим сфере b2c, то есть предлагающим товары конечному потребителю для удовлетворения его собственных потребностей, а не для дальнейшей перепродажи.</p> <img src="<?=$templateUriA?>/img/icons/insta-icon1.png" alt=""> </div> </div> <div class="col-lg-4"> <div class="wrap-block"> <img src="<?=$templateUriA?>/img/icons/insta-like2.png" alt="like"> <p>Продающим товары лёгкого спроса (косметика, одежда, мелкая техника, гаджеты, товары для дома, детские товары и т.д.)</p> <img src="<?=$templateUriA?>/img/icons/insta-icon1.png" alt=""> </div> </div> <div class="col-lg-4"> <div class="wrap-block"> <img src="<?=$templateUriA?>/img/icons/insta-like3.png" alt="like"> <p>Предлагающим нишевые услуги в сфере образования (курсы, тренинги, школы раннего развития, скорочтения и т.д.), красоты (косметология, пластическая хирургия, спа, салонные услуги и т.д.), здоровья (диагностика, лечение заболеваний, стоматология и т.д.), спорта (фитнес клубы, тренера и т.д.)</p> <img src="<?=$templateUriA?>/img/icons/insta-icon1.png" alt=""> </div> </div> </div> </div> <div class="advantage-smm"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Преимущества продвижения в социальных сетях с помощью таргетированной рекламы:</h2> </div> </div> <div class="row content-section"> <div class="col-lg-4"> <div class="wrap-block"> <div class="img"> <img src="<?=$templateUriA?>/img/icons/ukraine-icon.png" alt="ukraine"> </div> <p class="title-block">Широкий охват</p> <p class="descr">Аудитория Facebook в Украине на 2018 год составляет 11 млн пользователей, а Instagram – перевалила за 6 млн. И это всё потенциальные потребители товаров и услуг.</p> </div> </div> <div class="col-lg-4"> <div class="wrap-block"> <div class="img"> <img src="<?=$templateUriA?>/img/icons/target-icon.png" alt="target"> </div> <p class="title-block">Точность настройки рекламы</p> <p class="descr">Выбор целевой аудитории для рекламы позволяет учесть даже такие факторы, как пол, возраст, религия, семейное положение, профессия, доход, образование, интересы и т.д. Реклама будет показана только тем, кому она действительно интересна.</p> </div> </div> <div class="col-lg-4"> <div class="wrap-block"> <div class="img"> <img src="<?=$templateUriA?>/img/icons/advertising1-icon.png" alt="advertising"> </div> <p class="title-block">Множество вариаций объявлений</p> <p class="descr">Карусели, мультиформаты, банеры – всё, что позволит привлечь внимание покупателя.</p> </div> </div> </div> </div> <div class="result-smm"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Результаты рекламы наших клиентов</h2> </div> </div> <div class="row append-dots"> <div class="owl-carousel slider-result-smm"> <div class="item"> <div class="wrap-slid slide1"> <div class="wrap-descr"> <h3 class="title">SMM в Instagram для пластического хирурга</h3> <div class="details"> <p class="title-list">Задачи:</p> <ul class="list"> <li>Привлечение подписчиков</li> <li>Запись на консультацию через Instagram </li> </ul> <p class="title-list">Мы сделали:</p> <ol class="list"> <li>Разработали стратегию</li> <li>Составили контент-план </li> <li>Подобрали хештеги</li> <li>Писали тексты для постов</li> <li>Оформляли посты</li> <li>Привлекали целевую аудиторию (женщины, 25-45, Украина: Киев, Запорожье, Днепр) через массфолоу и масслайкинг</li> <li>Комментировали и общались с пациентами в Директе.</li> </ol> <p class="title-list title-list_green">Итог работы за 1 год:</p> <ol class="list"> <li>Увеличение числа подписчиков с 0 до 11000</li> <li>Количество записи на консультацию через Instagram – 90 в месяц</li> </ol> </div> </div> </div> </div> <div class="item"> <div class="wrap-slid slide2"> <div class="wrap-descr"> <h3 class="title">Таргетированная реклама в Facebook для онлайн магазина ретро-футболок</h3> <div class="details"> <p class="title-list">Задачи:</p> <ul class="list"> <li>Привлечение подписчиков на сайт магазина </li> </ul> <p class="title-list">Мы сделали:</p> <ol class="list"> <li>Выбрали целевые аудитории по интересам, месту проживания, возрасту</li> <li>Разработали для каждой группы рекламную кампанию</li> <li>Выбрали наиболее удачные периоды показа рекламы</li> <li>Запустили и сопровождали рекламные кампании, корректируя стратегии показа</li> </ol> <p class="title-list title-list_green">Итог работы за месяц:</p> <ol class="list"> <li>Переходов на сайт с рекламы – 1046</li> <li>Средний CTR (отношение кликов к показам): 4,54%</li> </ol> </div> </div> </div> </div> <div class="item"> <div class="wrap-slid slide3"> <div class="wrap-descr"> <h3 class="title">SMM в Instagram для онлайн магазина ретро формы</h3> <div class="details"> <p class="title-list">Задачи:</p> <ul class="list"> <li>Привлечение подписчиков</li> <li>Формирование сообщества любителей ретро-футболок</li> <li>Формирование контента на около футбольную тематику </li> <li>Увеличение трафика на сайт из социальных сетей.</li> </ul> <p class="title-list">Мы сделали:</p> <ol class="list"> <li>Разработали стратегию</li> <li>Составили контент-план</li> <li>Подобрали хештеги</li> <li>Писали тексты для постов</li> <li>Оформляли посты</li> <li>ривлекали целевую аудиторию (мужчины, 18-35, Великобритания, США, Азия) через массфолоу и масслайкинг</li> <li>Комментировали и общались с клиентами в Директе.</li> </ol> <p class="title-list title-list_green">Итог работы за 7 месяцев:</p> <ol class="list"> <li>Увеличение числа подписчиков, соответствующих заданным параметрам, с 0 до 10000+ </li> <li>Рост трафика на сайт из социальных сетей</li> <li>Сформировано сообщество постоянных клиентов интернет-магазина</li> </ol> </div> </div> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-same-smm" class="btn-pink" data-wipe="Хочу так же">Хочу так же</a> </div> </div> </div> </div> <div class="guarantees-smm"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Наши гарантии на продвижение в социальных сетях:</h2> </div> </div> <div class="row content-section"> <div class="col-md-4 col-lg-4"> <div class="wrap-block"> <img src="<?=$templateUriA?>/img/icons/tick-box-green.png" alt="done"> <p>Работаем по техническому заданию и договору</p> </div> </div> <div class="col-md-4 col-lg-4"> <div class="wrap-block"> <img src="<?=$templateUriA?>/img/icons/tick-box-green.png" alt="done"> <p>Согласовываем с вами все шаги и предложения</p> </div> </div> <div class="col-md-4 col-lg-4"> <div class="wrap-block"> <img src="<?=$templateUriA?>/img/icons/tick-box-green.png" alt="done"> <p>Предоставляем полную детализацию расходов</p> </div> </div> </div> </div> <div class="value-smm"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Стоимость продвижения в социальных сетях</h2> </div> </div> <div class="row button-tariff-kr d-flex d-md-none"> <div class="col-6"> <button class="2 btn-tariff btn-tariff-one btn-tariff_active">Простой</button> </div> <div class="col-6"> <button class="3 btn-tariff btn-tariff-two">Бизнес</button> </div> </div> <div class="row"> <table class="table custom-table table-bordered table-hover-custom"> <thead> <tr> <th class="t-col1 title" scope="col"></th> <th class="t-col2 title" scope="col">Простой</th> <th class="t-col3 title" scope="col">Бизнес</th> </tr> </thead> <tbody> <tr> <th class="t-col1" scope="row">Социальная сеть</th> <td class="t-col2">Или Facebook, или Instagram</td> <td class="t-col3">Facebook+Instagram</td> </tr> <tr> <th class="t-col1" scope="row">Выбор целевой аудитории, разбивка её на группы</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Разработка стратегии</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Создание группы или бизнес-страницы с оптимизированным контентом</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Разработка контент-плана</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Отложенный постинг</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Массфоллоу и масслайкинг для Instagram</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Разработка рекламной кампании (4 объявления)</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Настройка рекламной кампании и её ведение</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Отчёт в конце месяца по активности рекламы и аккаунта</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Стоимость</th> <td class="t-col2">3000 грн. разово</td> <td class="t-col3">6000 грн. ежемесячно</td> </tr> <tr> <th class="t-col1" scope="row"><img src="<?=$templateUriA?>/img/icons/gift.png" alt="Gift">Ваши подарки</th> <td class="t-col2">Бесплатный мини-аудит аккаунта с рекомендациями по улучшению и оптимизации</td> <td class="t-col3">Скидка 10% на создание контекстной рекламы </td> </tr> </tbody> </table> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-consultation-smm" data-wipe="Заказать консультацию">Заказать консультацию</a> </div> </div> </div> </div> <div class="promotion"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2 class="title_light">Другие способы продвижения сайта</h2> </div> </div> <div class="row append-dots"> <div class="other-mathods owl-carousel slider-other-mathods"> <div class="item"> <div class="card-wrap"> <a href="/seo/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SEO</p> </div> <div class="description-card"> <p>Увеличение видимости интернет-магазина в поисковой системе и привлечение пользователей</p> </div> </div> </a> </div> </div> <div class="item"> <div class="card-wrap"> <a href="/kontekstnaya-reklama/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>PPC</p> </div> <div class="description-card"> <p>Контекстная реклама для быстрого привлечения клиентов, планирующих покупку</p> </div> </div> </a> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-consultation-smm" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </div> </div> <div class="call-back-kr"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-callback-kr"> <img src="<?=$templateUriA?>/img/icons/shake-phone.png" alt="Phone"> <div class="overlay"> <div class="text">Обратный звонок</div> </div> </a> </div> <div class="footer-kr"> <div class="container"> <div class="row items justify-content-center align-items-center no-gutters"> <div class="col-12 col-md-12 col-xl-12 item justify-content-center align-items-center"> <div class="logo-footer"> <a href=""><img src="<?=$templateUriA?>/img/logo-green.png" alt="WeDo"></a> <div class="footer-phone"> <a href="tel:+38(098)151-20-15">+38(098)151-20-15</a> </div> <p>© Copyright 2018, Все права защищены</p> </div> </div> </div> </div> </div> <div class="modal call-us fade modal-kr" id="modal-callback-kr"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Заказ обратного звонка</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="callback-form-kr"> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="Username-kr" name="Username-kr" required> <label for="Username-kr">Имя</label> <div class="bar"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-kr" value="" name="phone-kr" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-kr">Телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal modal-kr modal-thank fade" id="modal-thank" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Cпасибо!!! Мы свяжемся с вами в ближайшее время.</p> </div> </div> </div> <div class="wrap-btn"> <div class="button button_green"> <a href="#" ontouchstart="" data-dismiss="modal" data-wipe="ok">ok</a> </div> </div> </div> </div> </div> <div class="modal fade modal-smm" id="modal-discover-smm"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <p class="modal-title">Узнайте, подойдёт ли вам продвижение в социальных сетях</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="form-discover-smm"> <div class="input-container"> <input type="text" id="name-discover-smm" name="name-discover-smm" required> <label for="name-discover-smm">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-discover-smm" value="" name="phone-discover-smm" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-discover-smm">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <input type="text" id="site-discover-smm" name="site-discover-smm"> <label for="site-discover-smm">Адрес сайта</label> <div class="bar"></div> </div> <div class="input-container"> <input type="text" id="busines-discover-smm" name="busines-discover-smm"> <label for="busines-discover-smm">Сфера бизнеса</label> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Узнать">Узнать</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-smm" id="modal-same-smm"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="modal-body"> <div class="card"> <form id="form-same-smm"> <div class="input-container"> <input type="text" id="name-same-smm" name="name-same-smm" required> <label for="name-same-smm">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-same-smm" value="" name="phone-same-smm" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-same-smm">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <label for="comment-same-smm">Комментарий</label> <textarea id="comment-same-smm" name="comment-same-smm"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-smm" id="modal-order-consultation-smm"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <p class="modal-title">Оставьте свои данные, и мы ответим на ваши вопросы</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="form-order-consult-smm"> <div class="input-container"> <input type="text" id="name-order-consult-smm" name="name-order-consult-smm" required> <label for="name-order-consult-smm">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-order-consult-smm" value="" name="phone-order-consult-smm" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-order-consult-smm">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <label for="comment-order-consult-smm">Комментарий</label> <textarea id="comment-order-consult-smm" name="comment-order-consult-smm"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=$templateUriA?>/js/owl.carousel.min.js"></script> <script src="<?=$templateUriA?>/js/config.js"></script> <script src="<?=$templateUriA?>/js/waypoints.min.js"></script> <script src="<?=$templateUriA?>/js/animate-css.js"></script> <script src="<?=$templateUriA?>/js/main.js"></script> </body> </html><file_sep><? $templateUri = get_template_directory_uri(); $templateUriA = $templateUri."/assets"; $templateDir = get_template_directory(); $URI=$_SERVER['REQUEST_URI']; // var_dump($templateUri); // die(); if ($URI == "/") { include_once $templateDir . "/content/main.php"; } else { $pageName = substr($URI,-strlen($URI),strlen($URI)-1); $FullPageName = $templateDir . "/content" . $pageName . ".php"; if (file_exists($FullPageName)) { include_once $FullPageName; } } ?> <file_sep><? $templateUri = get_template_directory_uri(); $templateUriA = $templateUri."/assets"; ?> <!doctype html> <html lang="ru"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="description" content=""> <meta name="yandex-verification" content="80567c69a37b1299" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link rel="stylesheet" href="<?=$templateUriA?>/css/main.css"> <script src="<?=$templateUriA?>/js/jquery.selectric.js"></script> <script src="<?=$templateUriA?>/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=$templateUriA?>/img/logo_fav.ico" type="image/x-icon"> </head> <body> <div class="head-404"> <div class="container head-content"> <div class="row top-line"> <div class="col-4 col-md-5 col-lg-6"> <div class="logo"> <a href="/"><img src="<?=$templateUriA?>/img/logoWedo.png" alt="WeDo"></a> </div> </div> <div class="col-6 col-md-6 col-lg-5"> <div class="phone"> <a href="tel:+38(098)150-83-95">+38(098)150-83-95</a> </div> </div> <div class="col-2 col-md-1 col-lg-1"> <div class="hamburger-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <nav class="nav-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <ul class="main-menu"> <li><a href="\">Главная</a></li> <li><a href="\sozdanie-saitov\">Создание сайтов</a></li> <li><a href="\internet-magaziny\">Создание интернет-магазинов</a></li> <li><a href="\kontekstnaya-reklama\">Контекстная реклама</a></li> <li><a href="\seo\">SEO-продвижение</a></li> <li><a href="\smm\">SMM</a></li> <li class="current_page"><a href="\blog\">Блог</a></li> </ul> </nav> </div> </div> </div> <div class="row center-line"> <div class="wrap-image-bg"> <img src="<?=$templateUriA?>/img/macbook-min.png" class="img-fluid d-none d-md-block"> </div> <div class="wrap-text"> <p class="title_404">404</p> <p class="descr_404">Страница, которую вы ищете, не существует или была перемещена</p> <div class="row wrap-btn justify-content-center"> <div class="col-4 col-md-4 col-lg-3"> <div class="button button_orange"> <a href="index.html">Главная</a> </div> </div> <div class="col-4 col-md-4 col-lg-3"> <div class="button button_orange"> <a href="blog.html">Блог</a> </div> </div> </div> </div> </div> <div class="row bottom-line"> <p class="copyright">© Copyright 2018, Все права защищены</p> </div> </div> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=$templateUriA?>/js/owl.carousel.min.js"></script> <script src="<?=$templateUriA?>/js/config.js"></script> <script src="<?=$templateUriA?>/js/waypoints.min.js"></script> <script src="<?=$templateUriA?>/js/animate-css.js"></script> <script src="<?=$templateUriA?>/js/main.js"></script> </body> </html><file_sep><script>function changePath(o) { ~["en"].indexOf(path[1]) ? window.location.href = "/en" == o ? oldUrl : "/" : window.location.href = "/" == o ? oldUrl : o + oldUrl } var oldUrl = window.location.pathname, path = oldUrl.split("/")</script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=get_theme_file_uri()?>/assets/js/owl.carousel.min.js"></script> <script src="<?=get_theme_file_uri()?>/assets/js/main.js"></script><!--<script src="js/bootstrap-formhelpers.min.js"></script>--></body> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>6PVCmYl" crossorigin="anonymous"></script> <script src="<?=get_theme_file_uri()?>/assets/js/owl.carousel.min.js"></script> <script src="<?=get_theme_file_uri()?>/assets/js/config.js"></script> <script src="<?=get_theme_file_uri()?>/assets/js/waypoints.min.js"></script> <script src="<?=get_theme_file_uri()?>/assets/js/animate-css.js"></script> <script src="<?=get_theme_file_uri()?>/assets/js/main.js"></script> <? wp_footer(); ?> </html><file_sep># wp_wedo_landing wp_wedo_landing <file_sep><!doctype html> <html lang="ru"> <head><!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-109981378-1"></script> <script>function gtag() { dataLayer.push(arguments) } window.dataLayer = window.dataLayer || [], gtag("js", new Date), gtag("config", "UA-109981378-1")</script> <!-- Google Tag Manager --> <script>!function (e, t, a, n, g) { e[n] = e[n] || [], e[n].push({"gtm.start": (new Date).getTime(), event: "gtm.js"}); var m = t.getElementsByTagName(a)[0], r = t.createElement(a); r.async = !0, r.src = "https://www.googletagmanager.com/gtm.js?id=GTM-WPHJ273", m.parentNode.insertBefore(r, m) }(window, document, "script", "dataLayer")</script><!-- End Google Tag Manager --> <title>Разработка интернет-магазина, продвижение (seo,ppc,smm) | WeDo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="yandex-verification" content="80567c69a37b1299"> <meta name="freelancehunt" content="f1392e2ffcdd730"> <meta name="description" content="Создание интернет-магазина с нуля. Интеграция с 1С и учётными системами. SEO, контекстная реклама, продвижение в социальных сетях. Бесплатная консультация."> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link rel="stylesheet" href="<?=get_theme_file_uri()?>/assets/css/main.css"> <script src="<?=get_theme_file_uri()?>/assets/js/jquery.selectric.js"></script> <script src="<?=get_theme_file_uri()?>/assets/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=get_theme_file_uri()?>/assets/img/logo_fav.ico" type="image/x-icon"> </head> <body><!-- Yandex.Metrika counter --> <script type="text/javascript">!function (e, t, a) { (t[a] = t[a] || []).push(function () { try { t.yaCounter46972284 = new Ya.Metrika({ id: 46972284, clickmap: !0, trackLinks: !0, accurateTrackBounce: !0, webvisor: !0 }) } catch (e) { } }); var c = e.getElementsByTagName("script")[0], n = e.createElement("script"), r = function () { c.parentNode.insertBefore(n, c) }; n.type = "text/javascript", n.async = !0, n.src = "https://cdn.jsdelivr.net/npm/yandex-metrica-watch/watch.js", "[object Opera]" == t.opera ? e.addEventListener("DOMContentLoaded", r, !1) : r() }(document, window, "yandex_metrika_callbacks")</script> <noscript> <div><img src="https://mc.yandex.ru/watch/46972284" style="position:absolute;left:-9999px" alt=""></div> </noscript><!-- /Yandex.Metrika counter --> <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WPHJ273" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> <file_sep><!doctype html> <html lang="ru"> <head> <title>Разработка интернет-магазина, продвижение (seo,ppc,smm) | WeDo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="yandex-verification" content="80567c69a37b1299" /> <meta name='freelancehunt' content='f1392e2ffcdd730' /> <meta name="description" content="Создание интернет-магазина с нуля. Интеграция с 1С и учётными системами. SEO, контекстная реклама, продвижение в социальных сетях. Бесплатная консультация."> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link rel="stylesheet" href="<?=$templateUriA?>/css/main.css"> <script src="<?=$templateUriA?>/js/jquery.selectric.js"></script> <script src="<?=$templateUriA?>/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=$templateUriA?>/img/logo_fav.ico" type="image/x-icon"> </head> <body> <header> <div class="container b-head-height"> <div class="parallax"> <div class="image-parallax man"></div> </div> <div class="row top-line align-items-center"> <div class="col-4 col-md-5 col-lg-6 item"> <div class="logo"> <a href=""><img src="<?=$templateUriA?>/img/logoWedo.png" alt="WeDo"></a> </div> </div> <div class="col-6 col-md-6 col-lg-5 item"> <div class="phone"> <a href="tel:+38(098)150-83-95">+38(098)150-83-95</a> <div class="collapse-lang"> <div class="ru" onclick="changePath('/')"><p>RU</p></div> <div class="en" onclick="changePath('/en')"><p>EN</p></div> </div> </div> </div> <div class="col-2 col-md-1 col-lg-1 item"> <div class="hamburger-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <nav class="nav-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <ul class="main-menu"> <li><a href="\">Главная</a></li> <li><a href="\sozdanie-saitov\">Создание сайтов</a></li> <li><a href="\internet-magaziny\">Создание интернет-магазинов</a></li> <li><a href="\kontekstnaya-reklama\">Контекстная реклама</a></li> <li><a href="\seo\">SEO-продвижение</a></li> <li><a href="\smm\">SMM</a></li> <li class="current_page"><a href="\blog\">Блог</a></li> </ul> </nav> </div> </div> </div> <div class="row align-items-center justify-content-end" id="menu"> <div class="col-12 col-md-9 col-xl-6"> <ul> <li><a href="#development">Development of online stores</a></li> <li><a href="#integration">Integration with accounting systems</a></li> <li><a href="#advancement">Promotion of online stores</a></li> </ul> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button"> <a href="#" data-toggle="modal" data-target="#myModal" class="btn-pink" data-wipe="Free consultation">Free consultation</a> <!--<a href="#" class="btn-pink b24-web-form-popup-btn-12 b24-web-form-popup-btn-6" data-wipe="Free consultation">Free consultation</a>--> </div> </div> </div> </div> </header> <section id="wedo"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h1>WeDo</h1> <h1>development of effective systems<br>of online sales </h1> </div> </div> <div class="row items"> <div class="col-12 col-md-4 col-xl-4 align-self-center item"><p>Since <span>2008</span> in <br>the field of IT and <br>marketing</p></div> <div class="col-12 col-md-4 col-xl-4 align-self-center item"><p>More than <span>100</span><br>successful web and accounting <br>systems’ projects</p></div> <div class="col-12 col-md-4 col-xl-4 align-self-center item"><p>More than <span>10</span><br>specialists working with <br>the project</p></div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button"> <a href="#" data-toggle="modal" data-target="#myModal" class="btn-pink" data-wipe="Free consultation">Free consultation</a> </div> </div> </div> </div> </section> <section id="development"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Development of online stores</h2> <h2>we will help you to sell products 24 hours <br class='hidden-sm-down'> a day, 7 days a week</h2> </div> </div> <div class="row content"> <div class="col-12 col-md-12 col-lg-6 col-xl-6"> <section class="timeline"> <ul> <li><div>Analysis <br>of business <br>and niche</div></li> <li><div>Strategy <br>development</div></li> <li><div>Website <br>design and <br>programming</div></li> <li><div>Integration <br>with accounting <br>systems</div></li> <li><div>The launch of <br>the project and <br>technical support</div></li> <li><div>Marketing <br>promotion</div></li> </ul> </section> </div> <div class="col-12 col-md-12 col-lg-6 col-xl-6"> <div class="ribbon-phone"> <div class="ribbon-text"> <div class="wrap-thesis"> <ul class="thesis"> <li>Mobile Friendly</li> <li>UX design</li> <li>SEO, PPC, SMM</li> <li>High conversion rate</li> <li>Prompt tech support</li> </ul> </div> </div> <div class="wrap-btn"> <div class="button"> <a href="#" data-toggle="modal" data-target="#myModal" class="btn-pink" data-wipe="Online store calculation">Online store calculation</a> </div> </div> </div> </div> </div> </div> </section> <section id="integration"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Integration with accounting systems</h2> <h2>we will accelerate the acceptance of orders and provide actual product prices and availability on the website</h2> <!--<h2>мы ускорим приём заказов и обеспечим<br class="hidden-sm-down">актуальные цены и наличие на сайте</h2>--> </div> </div> <div class="row items"> <div class="col-12 col-md-6 col-xl-6 align-self-center item"><p>Automatic <br><span>uploading</span><br> of products and orders</p></div> <div class="col-12 col-md-6 col-xl-6 align-self-center item"><p>Automated <br><span>Manager’s workplace</span><br> for dealing with the orders</p></div> </div> <div class="row items"> <div class="col-12 col-md-6 col-xl-6 align-self-center item"><p>The system for <span> Customer <br>relationship management</span><br> (CRM)</p></div> <div class="col-12 col-md-6 col-xl-6 align-self-center item"><p>Complex <br><span>discount and bonus</span><br> programs in the online shop</p></div> </div> </div> </section> <section id="advancement"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>The promotion of an online store</h2> <h2>we bring targeted customers and increase <br>brand awareness</h2> </div> </div> <div class="row items justify-content-center no-gutters"> <div class="col-12 col-md-6 col-xl-4 align-self-center item"> <a href="/seo/" class="link-to-other-page" target="_blank"> <p>SEO</p> <p>Increases online <br>stores’ visibility in search <br>engines (Google, Bing, <br>Yandex etc)</p> </a> </div> <div class="col-12 col-md-6 col-xl-4 align-self-center item"> <a href="/kontekstnaya-reklama/" class="link-to-other-page" target="_blank"> <p>PPC</p> <p>Quickly attracts <br>customers that plan to <br>purchase online stores’ <br>goods of defined kind</p> </a> </div> <div class="col-12 col-md-6 col-xl-11 align-self-center item hidden-sm-down"> <div class="wrap-btn"> <div class="button"> <a href="#" data-toggle="modal" data-target="#myModal" class="btn-pink" data-wipe="Help in choosing">Help in choosing</a> </div> </div> </div> <div class="col-12 col-md-6 col-xl-4 align-self-center item"> <a href="/smm/" class="link-to-other-page" target="_blank"> <p>SMM</p> <p>Increases company’s <br>and brand’s awareness <br>by gaining customers’ <br>confidence</p> </a> </div> </div> <div class="row justify-content-end"> <div class="col-12 col-xl-11"> <div class="wrap-btn"> <div class="button"> <a href="#" data-toggle="modal" data-target="#myModal" class="btn-pink" data-wipe="Help in choosing">Help in choosing</a> </div> </div> </div> </div> </div> </section> <footer> <div class="container"> <div class="row items justify-content-center align-items-center no-gutters"> <div class="col-12 col-md-4 col-xl-3 item"> <div class="phone-footer hidden-sm-down"> <p>+38(098)150-83-95</p> <p>Zaporozhye, Ukraine</p> </div> </div> <div class="col-12 col-md-4 col-xl-6 item"> <div class="logo-footer"> <a href=""><img src="<?=$templateUriA?>/img/logoWedo.png" alt="WeDo"></a> <p>© Copyright 2017, All rights reserved</p> </div> </div> <div class="col-12 col-md-4 col-xl-3 item"> <div class="menu-footer"> <ul> <li><a href="#development">Development of online stores</a></li> <li><a href="#integration">Integration with accounting systems</a></li> <li><a href="#advancement">Promotion of online stores</a></li> <li><a href="">Job opportunity</a></li> </ul> </div> </div> </div> </div> </footer> <!-- Modal --> <div class="modal fade" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/close.png" alt=""> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <h3 class="modal-title" id="exampleModalLabel">Please enter your contact details and we will provide you with a free consultation</h3> </div> </div> <div id="hidden-row" class="row"> <div class="modal-body"> <div class="container1"> <div class="card"> <form id="callback-form"> <div class="input-container"> <input type="text" id="Username" name="Username" required> <label for="Username">Name</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone" value="" name="phone" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone">Phone</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Specify your phone. (see the hint)</div> <div class="input-container"> <select class="form-control" id="select" name="select" required> <option value="" disabled selected>You need</option> <option value="Development of online stores">Development of online stores</option> <option value="Integration with accounting systems">Integration with accounting systems</option> <option value="Promotion of online stores">Promotion of online stores</option> </select> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button"> <button type="submit" class="btn" data-wipe="Send">Send</button> <!--<a href="" id="submit-btn" class="btn-pink" data-wipe="Отправить заявку">Отправить заявку</a>--> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> </div> <!--<div class="wrap-alert"> <div class="alert-div" id="alert"> <p>Thank you! We will contact you to discuss the project.</p> <div class="wrap-btn"> <div class="button"> <a href="#" id="open-close" class="btn-pink" data-wipe="ОК">ОК</a> </div> </div> </div> </div>--> <!-- END Modal --> <div class="modal fade" id="modal-thank" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <p>Thank you! We will contact you to discuss the project.</p> </div> <div class="modal-footer"> <div class="wrap-btn"> <div class="button"> <a href="#" data-dismiss="modal" class="btn-pink" data-wipe="ОК">ОК</a> </div> </div> </div> </div> </div> </div> <script> var oldUrl = window.location.pathname; var path = oldUrl.split('/'); function changePath(local) { if (!!~['en'].indexOf(path[1])) { window.location.href = local=="/en" ? oldUrl: "/"; } else { window.location.href = local=="/" ? oldUrl: local + oldUrl; } } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=$templateUriA?>/js/owl.carousel.min.js"></script> <script src="<?=$templateUriA?>/js/config.js"></script> <script src="<?=$templateUriA?>/js/waypoints.min.js"></script> <script src="<?=$templateUriA?>/js/animate-css.js"></script> <script src="<?=$templateUriA?>/js/main.js"></script> <!--<script src="js/bootstrap-formhelpers.min.js"></script>--> </body> </html><file_sep><!doctype html> <html lang="ru"> <head> <title>SEO продвижение и оптимизация сайтов для поисковых систем - WeDo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="description" content="Только белые методы. Глубокий аудит. Работа с ключевыми запросами и контентом, техническое SEO. Кейсы наших клиентов. Бесплатный экспресс-аудит"> <meta name="yandex-verification" content="80567c69a37b1299" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link rel="stylesheet" href="<?=$templateUriA?>/css/main.css"> <script src="<?=$templateUriA?>/js/jquery.selectric.js"></script> <script src="<?=$templateUriA?>/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=$templateUriA?>/img/logo_fav.ico" type="image/x-icon"> </head> <body> <div class="head-seo"> <div class="container head-content"> <div class="row top-line"> <div class="col-4 col-md-5 col-lg-6"> <div class="logo"> <a href="#"><img src="<?=$templateUriA?>/img/logo-green.png" alt="WeDo"></a> </div> </div> <div class="col-6 col-md-6 col-lg-5"> <div class="phone"> <a href="tel:+38(098)151-20-15">+38(098)151-20-15</a> </div> </div> <div class="col-2 col-md-1 col-lg-1"> <div class="hamburger-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <nav class="nav-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <ul class="main-menu"> <li><a href="/index/">Главная</a></li> <li><a href="/sozdanie-saitov/">Создание сайтов</a></li> <li><a href="/internet-magaziny/">Создание интернет-магазинов</a></li> <li><a href="/kontekstnaya-reklama/">Контекстная реклама</a></li> <li><a href="/seo/">SEO-продвижение</a></li> <li><a href="/smm/">SMM</a></li> <li class="current_page"><a href="/blog/">Блог</a></li> </ul> </nav> </div> </div> </div> <div class="row center-line"> <div class="col"> <h1 class="title-page-marketing"> <span class="h1 h1_seo">SEO</span> <span class="h1_text">продвижение сайтов в поисковых системах Google и Яндекс</span> </h1> </div> </div> <div class="row bottom-line"> <div class="col"> <p>Как обстоят дела у моего сайта?</p> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-free-audit-seo" data-wipe="Бесплатный экспресс-аудит">Бесплатный экспресс-аудит</a> </div> </div> </div> </div> </div> </div> </div> <div class="container"> <div class="whom-seo"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2>Кому необходимо SEO-продвижение сайтов?</h2> <p>Практически любому сайту, но особенно тем, которые:</p> </div> </div> <div class="row content"> <div class="col-md-7 col-lg-6"> <div class="text"> <ul> <li>Недавно созданы</li> <li>Имеют недостаточную посещаемость</li> <li>Имеют достаточное число посетителей, но они почему-то не превращаются в покупателей</li> <li>Занимают низкие позиции в поисковой выдаче или вовсе отсутствуют в ней</li> <li>Планируют в ближайшем будущем запускать платную контекстную рекламу</li> </ul> </div> </div> <div class="col-md-5 col-lg-6"> <div class="image"> <img src="<?=$templateUriA?>/img/notebook-seo.png" alt="img"> </div> </div> </div> </div> <div class="we-do-seo"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Что мы делаем в рамках SEO-продвижения?</h2> </div> </div> <div class="row items"> <div class="col-lg-5"> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Подробный аудит и детальный анализ сайта</p> </div> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Работа с ключевыми запросами и составление семантической карты сайта</p> </div> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Формирование мета-тегов, которые помогут поисковым системам правильно индексировать страницы</p> </div> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Техническая оптимизация страниц сайта (устранение ошибок в коде, дублей страниц, ошибок 404, настройка правильных редиректов и т.д.)</p> </div> </div> <div class="col-lg-5 offset-lg-2"> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Ускорение загрузки страниц сайта</p> </div> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Настройка вебмастеров, файла robots и sitemap</p> </div> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Настройка аналитики и целей для конверсии</p> </div> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Переезд на безопасный протокол https, который является требованием Google</p> </div> <div class="item"> <img class="icon" src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> <p class="text">Контент-маркетинг</p> </div> </div> </div> </div> <div class="features-seo"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Особенности SEO компании WeDo:</h2> </div> </div> <div class="row tiles"> <div class="col-12 col-sm-6 col-md col-lg"> <div class="tile"> <img class="icon" src="<?=$templateUriA?>/img/icons/increase-seo.png" alt="SEO"> <p class="text">Только белые методы <br>продвижения сайтов</p> </div> </div> <div class="col-12 col-sm-6 col-md col-lg"> <div class="tile"> <img class="icon" src="<?=$templateUriA?>/img/icons/external-link-seo.png" alt="SEO"> <p class="text">Без покупки <br>ссылок</p> </div> </div> <div class="col-12 col-sm-12 col-md col-lg"> <div class="tile"> <img class="icon" src="<?=$templateUriA?>/img/icons/group-seo.png" alt="SEO"> <p class="text">Минимум 4 специалиста <br>для работы над проектом</p> </div> </div> <div class="col-12 col-sm-6 col-md col-lg"> <div class="tile"> <img class="icon" src="<?=$templateUriA?>/img/icons/bank-seo.png" alt="SEO"> <p class="text">Оплата за перечень <br>работ, а не почасовая</p> </div> </div> <div class="col-12 col-sm-6 col-md col-lg"> <div class="tile"> <img class="icon" src="<?=$templateUriA?>/img/icons/report-card-seo.png" alt="SEO"> <p class="text">Отчёт о <br>работе</p> </div> </div> </div> </div> <div class="result-seo"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Результаты SEO-продвижения наших клиентов:</h2> </div> </div> <div id="id-btn-seo" class="row list-button list-button_top"> <button class="btn_arrow first-btn active-button"> rabotenko <!--<div class="arrow"></div>--> </button> <button class="btn_arrow second-btn"> vidnova <!--<div class="arrow"></div>--> </button> </div> <div class="row result-content first-slide"> <div class="col"> <div class="row cont-line"> <div class="col-lg-7"> <div class="detailed-text"> <p class="title">Сайт пластического хирурга <span class="name-of-site">rabotenko.com</span></p> <p class="list-header">Основные проблемы:</p> <ul class="list-custom"> <li>Низкая посещаемость</li> <li>Большой процент «отказов» и единичных просмотров страниц</li> </ul> <p class="list-header">Старт работ – ноябрь 2015 года</p> <p class="list-header">Предпринятые меры:</p> <ul class="list-custom"> <li>Работа с ключевыми запросами</li> <li>Составление семантической карты сайта</li> <li>Написание оптимизированных текстов на страницы сайта</li> <li>Формирование правильных мета-тегов для страниц</li> <li>Регистрация вебмастеров, составление robots и sitemap</li> <li>Продвижение контентом</li> <li>Переезд на безопасный протокол https</li> </ul> </div> </div> <div class="col-lg-5"> <div class="title-result"> <p>Результаты продвижения на ноябрь 2016 года</p> </div> </div> </div> <div class="row cont-line d-none d-sm-flex"> <div class="col-lg-4"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/rabotenko-chart-1.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Время на сайте</p> <p class="descr-ch">Увеличение среднего времени пребывания на сайте с 2:48 минут до 3:06 (+10%)</p> </div> </div> </div> <div class="col-lg-4"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/rabotenko-chart-2.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Отказы</p> <p class="descr-ch">Снижение количества отказов (выходов с сайта без перехода на другие страницы, просмотров до 15 секунд) с 15% до 10,9%</p> </div> </div> </div> <div class="col-lg-4"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/rabotenko-chart-3.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Посещаемость</p> <p class="descr-ch">Рост количества посетителей из поисковых систем на 48%</p> </div> </div> </div> </div> <div class="row append-dots cont-line d-block d-sm-none"> <div class="col"> <div class="owl-carousel chart-slider1"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/rabotenko-chart-3.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Посещаемость</p> <p class="descr-ch">Рост количества посетителей из поисковых систем на 48%</p> </div> </div> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/rabotenko-chart-2.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Отказы</p> <p class="descr-ch">Снижение количества отказов (выходов с сайта без перехода на другие страницы, просмотров до 15 секунд) с 15% до 10,9%</p> </div> </div> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/rabotenko-chart-1.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Время на сайте</p> <p class="descr-ch">Увеличение среднего времени пребывания на сайте с 2:48 минут до 3:06 (+10%)</p> </div> </div> </div> </div> </div> </div> </div> <div class="row result-content second-slide"> <div class="col"> <div class="row cont-line"> <div class="col-lg-7"> <div class="detailed-text"> <p class="title">Сайт клиники пластической хирургии и эстетической медецины <span class="name-of-site">vidnova.com.ua</span></p> <p class="list-header">Основные проблемы:</p> <ul class="list-custom"> <li>Наложение санкций от поисковых систем за неуникальный контент</li> <li>Практически полное отсутствие посетителей</li> <li>Плохие поведенческие факторы посетителей на сайте</li> </ul> <p class="list-header">Старт работ – декабрь 2015 года</p> <p class="list-header">Предпринятые меры:</p> <ul class="list-custom"> <li>Реструктуризация сайта</li> <li>Изменение дизайна</li> <li>Мобильная адаптация</li> <li>Техническое SEO</li> <li>Работа с ключевыми запросами</li> <li>Составление семантической карты сайта</li> <li>Написание оптимизированных текстов на страницы сайта</li> <li>Формирование правильных мета-тегов для страниц</li> <li>Регистрация вебмастеров, составление robots и sitemap</li> <li>Продвижение контентом</li> <li>Переезд на безопасный протокол https</li> </ul> </div> </div> <div class="col-lg-5"> <div class="title-result"> <p>Результаты продвижения на ноябрь 2016 года:</p> </div> </div> </div> <div class="row cont-line d-none d-sm-flex"> <div class="col-lg-4"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/vidnova-chart-1.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Санкции</p> <p class="descr-ch">Сняты санкции поисковых систем с сайта</p> </div> </div> </div> <div class="col-lg-4"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/vidnova-chart-2.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Посещаемость</p> <p class="descr-ch">Рост посещаемости сайта в 5 раз</p> </div> </div> </div> <div class="col-lg-4"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/vidnova-chart-3.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Отказы</p> <p class="descr-ch">Снижение числа отказов (выходов с сайта без перехода на другие страницы, просмотров до 15 секунд) с 20,3% до 10,4%</p> </div> </div> </div> </div> <div class="row append-dots cont-line d-block d-sm-none"> <div class="col"> <div class="owl-carousel chart-slider2"> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/vidnova-chart-2.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Посещаемость</p> <p class="descr-ch">Рост посещаемости сайта в 5 раз</p> </div> </div> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/vidnova-chart-3.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Отказы</p> <p class="descr-ch">Снижение числа отказов (выходов с сайта без перехода на другие страницы, просмотров до 15 секунд) с 20,3% до 10,4%</p> </div> </div> <div class="wrap-chart"> <div class="img-chart"> <img src="<?=$templateUriA?>/img/chart/vidnova-chart-1.png" alt="chart1"> </div> <div class="text-chart"> <p class="title-ch">Санкции</p> <p class="descr-ch">Сняты санкции поисковых систем с сайта</p> </div> </div> </div> </div> </div> </div> </div> <div class="row list-button list-button_bottom d-flex d-md-none"> <button class="btn_arrow first-btn active-button"> rabotenko <!--<div class="arrow"></div>--> </button> <button class="btn_arrow second-btn"> vidnova <!--<div class="arrow"></div>--> </button> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-promotion-seo1" data-wipe="Хочу так же">Хочу так же</a> </div> </div> </div> </div> <div class="our-garanties-seo"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Наши гарантии</h2> <p>Заказывая SEO-продвижение сайта у нас, вы можете быть уверены в качестве и честности работ, потому что мы:</p> </div> </div> <div class="row items"> <div class="col-lg-4"> <div class="item"> <div class="img-item"> <img src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> </div> <div class="text-item"> <p>Делаем копию сайта, на котором вносим все изменения, проверяем и тестируем работу, а лишь затем переносим всё на рабочий сайт</p> </div> </div> </div> <div class="col-lg-4"> <div class="item"> <div class="img-item"> <img src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> </div> <div class="text-item"> <p>Предоставляем отчёт о выполнении каждого этапа работ</p> </div> </div> </div> <div class="col-lg-4"> <div class="item"> <div class="img-item"> <img src="<?=$templateUriA?>/img/icons/check-circle-green.png" alt="check"> </div> <div class="text-item"> <p>Заключаем договор и работаем по техническому заданию, в котором определены все объёмы работ, их стоимость и сроки</p> </div> </div> </div> </div> </div> <div class="stages-seo"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Этапы работ по SEO-продвижению сайта</h2> </div> </div> <div class="row wrap-stages"> <div class="col"> <ol> <li> <span class="number-stages" aria-hidden="true">1</span> <p><span>Аудит сайта <span>Мы проверим наличие технических ошибок на сайте, его соответствие SEO-требованиям поисковых систем и протестируем сайт с точки зрения удобства для пользователя.</span></span></p> </li> <li> <span class="number-stages" aria-hidden="true">2</span> <p><span>Составление технического задания <span>Мы предоставим отчёт с указанием всех проблем на сайте в порядке их критичности и составим техническое задание на устранение ошибок с указанием объёма работ, сроков и стоимости.</span></span></p> </li> <li> <span class="number-stages" aria-hidden="true">3</span> <p><span>Поэтапное выполнение работ на тестовом сайте <span>Мы выполним согласованный список работ на тестовом сайте, вы проверите и примете работы</span></span></p> </li> <li> <span class="number-stages" aria-hidden="true">4</span> <p><span>Перенос изменений на рабочий сайт <span>Мы перенесём все принятые изменения на рабочий сайт, проверим корректность работы ресурса после применения доработок и отчитаемся о выполнении работы</span></span></p> </li> <li> <span class="number-stages last-stages" aria-hidden="true">5</span> <p><span>Ваш сайт начнёт «расти» в поисковых системах</span></p> </li> </ol> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-5"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-promotion-seo2" data-wipe="Заказать SEO-продвижение сайта">Заказать SEO-продвижение сайта</a> </div> </div> </div> </div> <div class="when-result-seo"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Когда будет результат от SEO-продвижения сайта?</h2> </div> </div> <div class="row wrap-when-result"> <div class="col-lg-5"> <div class="img-when-result"> <img src="<?=$templateUriA?>/img/rocket-seo.png" alt="rocket-seo"> </div> </div> <div class="col-lg-7"> <div class="text-when-result"> <p>Первые результаты вы увидите через 3-6 месяцев после выполнения работ. SEO-продвижение сайта не даёт быстрого результата, но оно безопасно – в отличие от серых и чёрных методов продвижения – и даёт длительный эффект на многие годы.</p> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-5"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-consultation-seo" data-wipe="Заказать консультацию">Заказать консультацию</a> </div> </div> </div> </div> <div class="promotion"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2 class="title_light">Другие способы продвижения сайта</h2> </div> </div> <div class="row append-dots"> <div class="other-mathods owl-carousel slider-other-mathods"> <div class="item"> <div class="card-wrap"> <a href="/smm/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SMM</p> </div> <div class="description-card"> <p>Повышения узнаваемости компании и бренда, завоевания доверия потенциальных клиентов</p> </div> </div> </a> </div> </div> <div class="item"> <div class="card-wrap"> <a href="/kontekstnaya-reklama/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>PPC</p> </div> <div class="description-card"> <p>Контекстная реклама для быстрого привлечения клиентов, планирующих покупку</p> </div> </div> </a> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-consultation-seo" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </div> </div> <div class="call-back-kr"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-callback-kr"> <img src="<?=$templateUriA?>/img/icons/shake-phone.png" alt="Phone"> <div class="overlay"> <div class="text">Обратный звонок</div> </div> </a> </div> <div class="footer-kr"> <div class="container"> <div class="row items justify-content-center align-items-center no-gutters"> <div class="col-12 col-md-12 col-xl-12 item justify-content-center align-items-center"> <div class="logo-footer"> <a href=""><img src="<?=$templateUriA?>/img/logo-green.png" alt="WeDo"></a> <div class="footer-phone"> <a href="tel:+38(098)151-20-15">+38(098)151-20-15</a> </div> <p>© Copyright 2018, Все права защищены</p> </div> </div> </div> </div> </div> <div class="modal call-us fade modal-kr" id="modal-callback-kr"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Заказ обратного звонка</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="callback-form-kr"> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="Username-kr" name="Username-kr" required> <label for="Username-kr">Имя</label> <div class="bar"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-kr" value="" name="phone-kr" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-kr">Телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal modal-kr modal-thank fade" id="modal-thank" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Cпасибо!!! Мы свяжемся с вами в ближайшее время.</p> </div> </div> </div> <div class="wrap-btn"> <div class="button button_green"> <a href="#" ontouchstart="" data-dismiss="modal" data-wipe="ok">ok</a> </div> </div> </div> </div> </div> <div class="modal fade modal-seo" id="modal-free-audit-seo"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <p class="modal-title">Наши специалисты сделают экспресс-аудит сайта по чек-листу и дадут рекомендации по дальнейшей работе</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="free-audit-seo"> <div class="input-container"> <input type="text" id="name-free-audit" name="name-free-audit" required> <label for="name-free-audit">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-free-audit" value="" name="phone-free-audit" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-free-audit">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <input type="text" id="site-free-audit" name="site-free-audit" required> <label for="site-free-audit">Сайт</label> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Протестировать сайт">Протестировать сайт</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-seo" id="modal-order-promotion-seo1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <p class="modal-title">Заказ SEO-продвижения</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="want-the-same"> <div class="input-container"> <input type="text" id="name-same" name="name-same" required> <label for="name-same">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-same" value="" name="phone-same" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-same">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <input type="text" id="site-same" name="site-same"> <label for="site-same">Сайт</label> <div class="bar"></div> </div> <div class="input-container"> <label for="comment-same">Опишите вашу проблему</label> <textarea id="comment-same" name="comment-same"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-seo" id="modal-order-promotion-seo2"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <p class="modal-title">Заказ SEO-продвижения</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="order-promotion-seo2"> <div class="input-container"> <input type="text" id="name-order-promotion" name="name-order-promotion" required> <label for="name-order-promotion">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-order-promotion" value="" name="phone-order-promotion" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-order-promotion">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <input type="text" id="site-order-promotion" name="site-order-promotion"> <label for="site-order-promotion">Сайт</label> <div class="bar"></div> </div> <div class="input-container"> <label for="comment-order-promotion">Опишите вашу проблему</label> <textarea id="comment-order-promotion" name="comment-order-promotion"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-seo" id="modal-order-consultation-seo"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <p class="modal-title">Заказ обратного звонка</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="order-consultation-seo"> <div class="input-container"> <input type="text" id="name-order-consultation" name="name-order-consultation" required> <label for="name-order-consultation">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-order-consultation" value="" name="phone-order-consultation" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-order-consultation">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <input type="text" id="site-order-consultation" name="site-order-consultation"> <label for="site-order-consultation">Сайт</label> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=$templateUriA?>/js/owl.carousel.min.js"></script> <script src="<?=$templateUriA?>/js/config.js"></script> <script src="<?=$templateUriA?>/js/waypoints.min.js"></script> <script src="<?=$templateUriA?>/js/animate-css.js"></script> <script src="<?=$templateUriA?>/js/main.js"></script> </body> </html><file_sep><!doctype html> <html lang="ru"> <head> <title>Разработка сайтов "под ключ" от 300$, компания WeDo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="description" content="Лендинг, сайт-визитка, корпоративный сайт с дизайном, вёрсткой, программирвоанием, seo-оптимизацией. Поддержка и продвижение. +38(098)150-83-95"> <meta name="yandex-verification" content="80567c69a37b1299" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link rel="stylesheet" href="<?=$templateUriA?>/css/main.css"> <script src="<?=$templateUriA?>/js/jquery.selectric.js"></script> <script src="<?=$templateUriA?>/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=$templateUriA?>/img/logo_fav.ico" type="image/x-icon"> </head> <body> <div class="head-site"> <div class="container head-content"> <div class="row top-line"> <div class="col-4 col-md-5 col-lg-6"> <div class="logo"> <a href="#"><img src="<?=$templateUriA?>/img/logo-blue-light.png" alt="WeDo"></a> </div> </div> <div class="col-6 col-md-6 col-lg-5"> <div class="phone"> <a href="tel:+38(098)150-83-95">+38(098)150-83-95</a> </div> </div> <div class="col-2 col-md-1 col-lg-1"> <div class="hamburger-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <nav class="nav-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <ul class="main-menu"> <li><a href="/">Главная</a></li> <li><a href="/sozdanie-saitov/">Создание сайтов</a></li> <li><a href="/internet-magaziny/">Создание интернет-магазинов</a></li> <li><a href="/kontekstnaya-reklama/">Контекстная реклама</a></li> <li><a href="/seo/">SEO-продвижение</a></li> <li><a href="/smm/">SMM</a></li> <li class="current_page"><a href="/blog/">Блог</a></li> </ul> </nav> </div> </div> </div> <div class="row center-line"> <div class="col"> <h1 class="title-page-marketing"> <span class="h1_text h1_text__align-center">Создание сайтов <span class="italic">«под ключ»</span> с оптимизацией для поисковых систем</span> </h1> </div> </div> <div class="row bottom-line"> <div class="col"> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_blue-light"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-free-consult-site" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </div> </div> </div> <div class="container"> <div class="section-block features-of-sites"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-10"> <h2 class="title_light">Особенности сайтов, разработанных компанией WeDo</h2> <h2>Вы получите маркетинговый инструмент, полностью соответствующий вашему бизнесу, который к тому же легко продвигать в поисковых системах.</h2> </div> </div> <div class="row content-section"> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-conference.png" alt=""> </div> <div class="text"> <p>Учитываем интересы целевой аудитории</p> </div> </div> </div> </div> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-doorbell.png" alt=""> </div> <div class="text"> <p>Заботимся о юзабилити и поведенческих факторах</p> </div> </div> </div> </div> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-console.png" alt=""> </div> <div class="text"> <p>Выбираем cms, исходя из особенностей будущего сайта и вашего удобства</p> </div> </div> </div> </div> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-text.png" alt=""> </div> <div class="text"> <p>Пишем тексты 2-в-1: продающие и оптимизированные</p> </div> </div> </div> </div> </div> <div class="row content-section"> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-seo.png" alt=""> </div> <div class="text"> <p>Составляем мета-теги для всех страниц</p> </div> </div> </div> </div> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-multiple-devices.png" alt=""> </div> <div class="text"> <p>Делаем адаптивный дизайн</p> </div> </div> </div> </div> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-software-installer.png" alt=""> </div> <div class="text"> <p>Устанавливаем счётчики и KPI по важным показателям</p> </div> </div> </div> </div> <div class="col-6 col-md-3 col-lg-3"> <div class="wrap-items"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/icon-website.png" alt=""> </div> <div class="text"> <p>Всю разработку ведём на тестовом сайте, закрытом от индексации</p> </div> </div> </div> </div> </div> </div> <div class="section-block examples-our-work"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2 class="title_light">Примеры наших работ</h2> </div> </div> <div class="row append-dots content-section"> <div class="owl-carousel slider-work-site"> <a href="https://chikiss.com.ua/" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide1"> <div class="wrap-descr"> <p>Интернет-магазин нижнего белья и одежды с интеграцией с 1С</p> <div class="wrap-link"> <p>chikiss.com.ua</p> </div> </div> </div> </div> </a> <a href="https://lotos24.com.ua" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide2"> <div class="wrap-descr"> <p>Интернет-магазин бытовой химии и косметики с интеграцией с 1С</p> <div class="wrap-link"> <p>lotos24.com.ua</p> </div> </div> </div> </div> </a> <a href="https://ankor-crimea.ru" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide3"> <div class="wrap-descr"> <p>Интернет-магазин строительных материалов</p> <div class="wrap-link"> <p>ankor-crimea.ru</p> </div> </div> </div> </div> </a> <a href="https://ankor-profili.ru" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide4"> <div class="wrap-descr"> <p>Лэндинг для контекстной рекламы</p> <div class="wrap-link"> <p>ankor-profili.ru</p> </div> </div> </div> </div> </a> <a href="https://поликарбонкрым.рф" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide5"> <div class="wrap-descr"> <p>Лэндинг для контекстной рекламы</p> <div class="wrap-link"> <p>поликарбонкрым.рф</p> </div> </div> </div> </div> </a> <a href="https://cmservice.com.ua/" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide6"> <div class="wrap-descr"> <p>Сайт-каталог официального представителя кофемашин WMF в Украине</p> <div class="wrap-link"> <p>cmservice.com.ua</p> </div> </div> </div> </div> </a> </div> </div> </div> <div class="section-block tabs-stages"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2 class="title_light">Этапы разработки сайтов</h2> </div> </div> <div class="row content-section"> <div class="col-12"> <div class="tabs-im"> <div class="tab-im col-12 col-lg-4"> <button class="tab-toggle-im">01. Разработка концепции</button> </div> <div class="content col-12 col-lg-8"> <div class="number-stage d-none d-lg-block"> <p>01</p> </div> <div class="wrap"> <h3 class="heading d-none d-lg-block">Разработка концепции</h3> <hr class="line-horizontal d-none d-sm-block"> <div class="description"> <ul> <li>Заполнение брифа: о нише вашего бизнеса, его особенностях, преимуществах и недостатках, конкурентах и конъюнктуре вашего рынка, ваших ожиданиях от сайта. Мы можем сделать это как на очной встрече, так и в удалённом режиме.</li> </ul> <a class="link-download" href="download/WeDo_Бриф на создание сайта.docx" download> <img src="<?=$templateUriA?>/img/icons/icon-download-from-cloud.png" alt=""> <p>Скачать бриф</p> </a> <ul> <li>Составление коммерческого предложения с предварительной оценкой бюджета и сроков проекта.</li> </ul> <ul> <li>Составление технического задания. Вы получаете готовый проект сайта с проработанной концепцией, структурой, уникальным торговым предложением, отражающий ваши преимущества.</li> </ul> </div> </div> </div> <div class="tab-im col-12 col-lg-4"> <button class="tab-toggle-im">02. Проектировка и прототипирование</button> </div> <div class="content col-12 col-lg-8"> <div class="number-stage d-none d-lg-block"> <p>02</p> </div> <div class="wrap"> <h3 class="heading d-none d-lg-block">Проектировка и прототипирование</h3> <hr class="line-horizontal d-none d-sm-block"> <div class="description"> <ul> <li>Проектировка пути пользователя по страницы и выполнение им заданного действия</li> <li>Выбор блоков и элементов для страницы для достижения пользователем поставленной цели</li> <li>Размещение блоков и элементов на странице (схематическое изображение)</li> <li>Согласование с вами прототипа основных страниц</li> </ul> </div> </div> </div> <div class="tab-im col-12 col-lg-4"> <button class="tab-toggle-im">03. Тексты и контент</button> </div> <div class="content col-12 col-lg-8"> <div class="number-stage d-none d-lg-block"> <p>03</p> </div> <div class="wrap"> <h3 class="heading d-none d-lg-block">Тексты и контент</h3> <hr class="line-horizontal d-none d-sm-block"> <div class="description"> <ul> <li>Сбор семантического ядра (ключевых запросов) для сайта и распределение групп слов по страницам</li> <li>Написание текстов на страницы сайта с применением модели AIDA, LSI-копирайтинга</li> <li>Размещение текстов в прототипе для комплексного восприятия</li> <li>Составление мета-тегов для страниц</li> </ul> </div> </div> </div> <div class="tab-im col-12 col-lg-4"> <button class="tab-toggle-im">04. Дизайн сайта</button> </div> <div class="content col-12 col-lg-8"> <div class="number-stage d-none d-lg-block"> <p>04</p> </div> <div class="wrap"> <h3 class="heading d-none d-lg-block">Дизайн сайта</h3> <hr class="line-horizontal d-none d-sm-block"> <div class="description"> <ul> <li>Отрисовка версии для десктопов </li> <li>Мобильная адаптация дизайна</li> </ul> </div> </div> </div> <div class="tab-im col-12 col-lg-4"> <button class="tab-toggle-im">05. Вёрстка и программирование</button> </div> <div class="content col-12 col-lg-8"> <div class="number-stage d-none d-lg-block"> <p>05</p> </div> <div class="wrap"> <h3 class="heading d-none d-lg-block">Вёрстка и программирование</h3> <hr class="line-horizontal d-none d-sm-block"> <div class="description"> <ul> <li>Развёртка тестового сайта, закрытого от индексации</li> <li>Вёрстка страниц</li> <li>Анимация элементов</li> <li>Настройка функционала</li> <li>Наполнение контентом</li> </ul> </div> </div> </div> <div class="tab-im col-12 col-lg-4"> <button class="tab-toggle-im">06. Тестирование</button> </div> <div class="content col-12 col-lg-8"> <div class="number-stage d-none d-lg-block"> <p>06</p> </div> <div class="wrap"> <h3 class="heading d-none d-lg-block">Тестирование</h3> <hr class="line-horizontal d-none d-sm-block"> <div class="description"> <ul> <li>Проверка корректности работы сайта и выполнения всех задач из ТЗ</li> <li>Принятие вами сайта и подтверждение выполнения работ</li> </ul> </div> </div> </div> <div class="tab-im col-12 col-lg-4"> <button class="tab-toggle-im">07. Запуск</button> </div> <div class="content col-12 col-lg-8"> <div class="number-stage d-none d-lg-block"> <p>07</p> </div> <div class="wrap"> <h3 class="heading d-none d-lg-block">Запуск</h3> <hr class="line-horizontal d-none d-sm-block"> <div class="description"> <ul> <li>Перенос сайт на рабочий домен</li> <li>Установка систем аналитики</li> <li>Формирование sitemap и robots.txt</li> <li>Открытие сайта к индексации поисковыми системами</li> </ul> </div> </div> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_blue-light"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-free-consult-site" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> <div class="section-block table-price-site"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2 class="title_light">Цена на разработку сайта</h2> </div> </div> <div class="row button-tariff-kr d-flex d-md-none"> <div class="col-6"> <button class="2 btn-tariff btn-tariff-one btn-tariff_active">Лендинг</button> </div> <div class="col-6"> <button class="3 btn-tariff btn-tariff-two">Сайт-визитка</button> </div> <div class="col-12"> <button class="4 btn-tariff btn-tariff-three">Корпоративный сайт</button> </div> </div> <div class="row content-section"> <table class="table custom-table table-bordered table-hover-custom"> <thead> <tr> <th class="t-col1 title" scope="col"></th> <th class="t-col2 title" scope="col">Лендинг</th> <th class="t-col3 title" scope="col">Сайт-визитка на шаблоне</th> <th class="t-col4 title" scope="col">Корпоративный сайт с индивидуальным дизайном</th> </tr> </thead> <tbody> <tr> <th class="t-col1" scope="row">Количество страниц</th> <td class="t-col2">1</td> <td class="t-col3">5</td> <td class="t-col4">10</td> </tr> <tr> <th class="t-col1" scope="row">Анализ бизнеса</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">Анализ конкурентов и их особенностей</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">Формирование УТП и преимуществ</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">Составление семантического ядра</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">Прототип и дизайн</th> <td class="t-col2">1 страница</td> <td class="t-col3">шаблонный дизайн с использованием корпоративных цветов и стиля, без прототипирования страниц</td> <td class="t-col4">5 страниц (Главная, О нас, Контакты, страница со списком новостей, страница со списком услуг) </td> </tr> <tr> <th class="t-col1" scope="row">Наполнение контентом</th> <td class="t-col2">1 страница</td> <td class="t-col3">5 страниц, 3000 знаков Остальные - опционально</td> <td class="t-col4">10 страниц</td> </tr> <tr> <th class="t-col1" scope="row">Базовая сео-оптимизация (мета-теги, заголовки)</th> <td class="t-col2">1 страница</td> <td class="t-col3">5 страниц</td> <td class="t-col4">10 страниц</td> </tr> <tr> <th class="t-col1" scope="row">Кроссбраузерность</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">Адаптивность</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col3">предусмотренная шаблоном</td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">https, сам ssl оплачивается отдельно</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">Страница 404</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col3">предусмотренная шаблоном</td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">robots, sitemap, вебмастера</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="Нет"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">Системы аналитики</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1" scope="row">План продвижения</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> <td class="t-col4"><img src="<?=$templateUriA?>/img/icons/check_blue.png" alt="Да"></td> </tr> <tr> <th class="t-col1 font-bold" scope="row">Цена</th> <td class="t-col2 font-bold">300 $</td> <td class="t-col3 font-bold">600 $</td> <td class="t-col4 font-bold">1400 $</td> </tr> <tr> <th class="t-col1 font-bold" scope="row">Срок</th> <td class="t-col2 font-bold">7 рабочих дней</td> <td class="t-col3 font-bold">15 рабочих дней</td> <td class="t-col4 font-bold">30 рабочих дней</td> </tr> <tr> <th class="t-col1" scope="row"><img src="<?=$templateUriA?>/img/icons/gift-blue.png" alt="Gift">Ваши подарки</th> <td class="t-col2">10% скидка на создание рекламной кампании в Гугле</td> <td class="t-col3">1 месяц бесплатного маркетингового сопровождения</td> <td class="t-col4">1 месяц бесплатного маркетингового сопровождения + 5% скидки на пакет «Продвижение контентом» (или 10% скидки на создание рекламной кампании в Гугле)</td> </tr> <tr> <th class="t-col1" scope="row"></th> <td class="t-col2"> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col"> <div class="button button_blue-light"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-site-tariff1" data-wipe="Заказать">Заказать</a> </div> </div> </div> </td> <td class="t-col3"> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col"> <div class="button button_blue-light"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-site-tariff2" data-wipe="Заказать">Заказать</a> </div> </div> </div> </td> <td class="t-col4"> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col"> <div class="button button_blue-light"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-site-tariff3" data-wipe="Заказать">Заказать</a> </div> </div> </div> </td> </tr> </tbody> </table> </div> </div> <div class="section-block why-us-site"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Веб-студия WeDo – факты о нас</h2> <h2>Разрабатывая сайты, мы стараемся быть лучшими в этом, и вот подтверждение</h2> </div> </div> <div class="row content-section wrap-why-us"> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon1.png" alt="Партнеры"> </div> <div class="text"> <p>Партнёр Google, Bitrix, Shopify</p> </div> </div> </div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon2.png" alt="Обучение сотрудников"> </div> <div class="text"> <p>Все сотрудники проходили обучение в Bitrix, Google, 1С</p> </div> </div> </div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon3.png" alt="Опыт работы"> </div> <div class="text"> <p>Опыт работы в сфере IT (1С, web) с 2008 года</p> </div> </div> </div> <div class="w-100"></div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon4.png" alt="Полный цикл"> </div> <div class="text"> <p>Полный цикл Разработка - Интеграция - Поддержка - Продвижение</p> </div> </div> </div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon5.png" alt="Успешные проекты"> </div> <div class="text"> <p>Более 100 успешных проектов в 1С и web</p> </div> </div> </div> </div> </div> <div class="section-block promotion-site"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Продвижение сайтов после запуска</h2> <h2>Разработка сайта и маркетинговое сопровождение принесут максимум эффекта в сочетании с таким продвижением</h2> </div> </div> <div class="row append-dots"> <div class="all-card owl-carousel slider-seo"> <div class="item"> <div class="card-wrap"> <a href="seo/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SEO</p> </div> <div class="description-card"> <p>Увеличение видимости интернет-магазина в поисковой системе и привлечение пользователей</p> </div> </div> </a> </div> </div> <div class="item"> <div class="card-wrap"> <a href="kontekstnaya-reklama/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>PPC</p> </div> <div class="description-card"> <p>Контекстная реклама для быстрого привлечения клиентов, планирующих покупку</p> </div> </div> </a> </div> </div> <div class="item"> <div class="card-wrap"> <a href="smm/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SMM</p> </div> <div class="description-card"> <p>Повышения узнаваемости компании и бренда, завоевания доверия потенциальных клиентов</p> </div> </div> </a> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_blue-light"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-free-consult-site" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </div> <div class="footer-kr"> <div class="container"> <div class="row items justify-content-center align-items-center no-gutters"> <div class="col-12 col-md-12 col-xl-12 item justify-content-center align-items-center"> <div class="logo-footer"> <a href=""><img src="<?=$templateUriA?>/img/logo-blue-light.png" alt="WeDo"></a> <div class="footer-phone"> <a href="tel:+38(098)151-20-15">+38(098)150-83-95</a> </div> <p>© Copyright 2018, Все права защищены</p> </div> </div> </div> </div> </div> <div class="modal call-us fade modal-kr" id="modal-free-consult-site"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Укажите, пожалуйста, Ваши контактные данные, и мы предоставим Вам бесплатную консультацию</p> </div> </div> <div class="modal-body"> <div class="card"> <form> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="name-site" name="name-site" required> <label for="name-site">Имя</label> <div class="bar bar_blue"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-site" value="" name="phone-site" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-site">Телефон</label> <div class="bar bar_blue"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_blue-light"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal call-us fade modal-kr" id="modal-site-tariff1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Укажите, пожалуйста, Ваши контактные данные, и мы свяжемся с Вами, чтобы обсудить проект</p> </div> </div> <div class="modal-body"> <div class="card"> <form> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="name-site-tariff1" name="name-site-tariff1" required> <label for="name-site-tariff1">Имя</label> <div class="bar bar_blue"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-site-tariff1" value="" name="phone-site-tariff1" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-site-tariff1">Телефон</label> <div class="bar bar_blue"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="row wrap-tariff-name"> <div class="col"> <div class="input-container"> <input type="hidden" id="site-tariff1" name="site-tariff1" value="Лендинг"> <label for="site-tariff1"> <div class="tariff"> <p>Ваш выбор:</p> <p class="name-tariff">Лендинг</p> </div> </label> </div> </div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_blue-light"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal call-us fade modal-kr" id="modal-site-tariff2"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Укажите, пожалуйста, Ваши контактные данные, и мы свяжемся с Вами, чтобы обсудить проект</p> </div> </div> <div class="modal-body"> <div class="card"> <form> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="name-site-tariff2" name="name-site-tariff2" required> <label for="name-site-tariff2">Имя</label> <div class="bar bar_blue"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-site-tariff2" value="" name="phone-site-tariff2" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-site-tariff2">Телефон</label> <div class="bar bar_blue"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="row wrap-tariff-name"> <div class="col"> <div class="input-container"> <input type="hidden" id="site-tariff2" name="site-tariff2" value="Сайт-визитка на шаблоне"> <label for="site-tariff2"> <div class="tariff"> <p>Ваш выбор:</p> <p class="name-tariff">Сайт-визитка на шаблоне</p> </div> </label> </div> </div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_blue-light"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal call-us fade modal-kr" id="modal-site-tariff3"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Укажите, пожалуйста, Ваши контактные данные, и мы свяжемся с Вами, чтобы обсудить проект</p> </div> </div> <div class="modal-body"> <div class="card"> <form> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="name-site-tariff3" name="name-site-tariff3" required> <label for="name-site-tariff3">Имя</label> <div class="bar bar_blue"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-site-tariff3" value="" name="phone-site-tariff3" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-site-tariff3">Телефон</label> <div class="bar bar_blue"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="row wrap-tariff-name"> <div class="col"> <div class="input-container"> <input type="hidden" id="site-tariff3" name="site-tariff3" value="Корпоративный сайт с индивидуальным дизайном"> <label for="site-tariff3"> <div class="tariff"> <p>Ваш выбор:</p> <p class="name-tariff">Корпоративный сайт</p> </div> </label> </div> </div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_blue-light"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal modal-kr modal-thank fade" id="modal-thank" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Cпасибо!!! Мы свяжемся с вами в ближайшее время.</p> </div> </div> </div> <div class="wrap-btn"> <div class="button button_blue-light"> <a href="#" ontouchstart="" data-dismiss="modal" data-wipe="ok">ok</a> </div> </div> </div> </div> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=$templateUriA?>/js/owl.carousel.min.js"></script> <script src="<?=$templateUriA?>/js/config.js"></script> <script src="<?=$templateUriA?>/js/waypoints.min.js"></script> <script src="<?=$templateUriA?>/js/animate-css.js"></script> <script src="<?=$templateUriA?>/js/main.js"></script> </body> </html><file_sep><!doctype html> <html lang="ru"> <head> <title>Разработка интернет-магазинов от 2150$, компания WeDo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="description" content="Сайт под ключ для продажи товаров. Современный дизайн, грамотное SEO. Высокая конверсия посетителя в покупателя. Интеграция с учёными системами и CRM."> <meta name="theme-color" content="#447d98"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="<?=$templateUriA?>/css/main.css"> <script src="<?=$templateUriA?>/js/jquery.selectric.js"></script> <script src="<?=$templateUriA?>/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=$templateUriA?>/img/for_im/logo_fav.ico" type="image/x-icon"> </head> <body class="body-internet-magaziny"> <header class="header-im"> <div class="container header-items"> <div class="row top-line"> <div class="col-4 col-md-5 col-lg-6 item"> <div class="logo"> <a href=""><img src="<?=$templateUriA?>/img/for_im/logo.png" alt="WeDo"></a> </div> </div> <div class="col-6 col-md-6 col-lg-5 item"> <div class="phone"> <a href="tel:++38(098)150-83-95">+38(098)150-83-95</a> </div> </div> <div class="col-2 col-md-1 col-lg-1 item"> <div class="hamburger-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <nav class="nav-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <ul class="main-menu"> <li><a href="/">Главная</a></li> <li><a href="/sozdanie-saitov/">Создание сайтов</a></li> <li><a href="/internet-magaziny/">Создание интернет-магазинов</a></li> <li><a href="/kontekstnaya-reklama/">Контекстная реклама</a></li> <li><a href="/seo/">SEO-продвижение</a></li> <li><a href="/smm/">SMM</a></li> <li class="current_page"><a href="/blog/">Блог</a></li> </ul> </nav> </div> </div> </div> <div class="row"> <div class="col-12"> <div class="title-center"> <h1>Разработка интернет-магазинов <br>для эффективных продаж</h1> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#free-consult-im" class="btn-pink" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </header> <section id="feature"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Особенности интернет-магазинов от компании WeDo</h2> <h2>мы учитываем все современные требования поисковых систем и пользователей к сайтам</h2> </div> </div> <div class="row"> <div class="col-12"> <div class="tabs-im"> <div class="tab-im col-12 col-lg-5"> <button class="tab-toggle-im">Высокая конверсия посетителей в покупатели</button> </div> <div class="content col-12 col-lg-7"> <h3 class="heading d-none d-lg-block">Высокая конверсия посетителей в покупатели</h3> <p class="description">Наша задача – разработать интернет-магазин, который будет не только приводить посетителей на сайт, но и конвертировать их в покупателей. Чтобы обеспечить это, мы проектируем сайт на основании пользовательского опыта и постоянно работаем с поведенческими факторами клиентов сайта.</p> </div> <div class="tab-im col-12 col-lg-5"> <button class="tab-toggle-im">Мобильная адаптация под смартфоны и планшеты</button> </div> <div class="content col-12 col-lg-7"> <h3 class="heading d-none d-lg-block">Мобильная адаптация под смартфоны и планшеты</h3> <p class="description">Адаптация сайта под мобильные устройства, по заявлению Google, оказывает значительное влияние на результаты поиска. Приоритет в выдаче отдаётся сайтам, контент и скорость загрузки которых отвечают требованиям для смартфонов и планшетов. Разработка интернет-магазина нашими специалистами включает этот важный этап.</p> </div> <div class="tab-im col-12 col-lg-5"> <button class="tab-toggle-im">SEO-оптимизация на этапе разработки</button> </div> <div class="content col-12 col-lg-7"> <h3 class="heading d-none d-lg-block">SEO-оптимизация на этапе разработки</h3> <p class="description">Для попадания интернет-магазинов в ТОП выдачи Google важно правильно собрать ключевые запросы, распределить их на группы, назначить страницам и сформировать мета-теги в соответствии с требованиями поисковых систем. Мы проводим эти работы на этапе разработки сайта.</p> </div> <div class="tab-im col-12 col-lg-5"> <button class="tab-toggle-im">Использование защищенных протоколов https</button> </div> <div class="content col-12 col-lg-7"> <h3 class="heading d-none d-lg-block">Использование защищенных протоколов https</h3> <p class="description">Защищенный протокол передачи данных https с использованием шифрования – требование Google к современным интернет-магазинам. Все сайты, использующие поля ввода данных и не перешедшие на данный протокол, помечаются как небезопасные. Именно поэтому мы используем SSL сертификат, который обеспечивает протокол https.</p> </div> <div class="tab-im col-12 col-lg-5"> <button class="tab-toggle-im">Высокая скорость загрузки страниц и работы</button> </div> <div class="content col-12 col-lg-7"> <h3 class="heading d-none d-lg-block">Высокая скорость загрузки страниц и работы</h3> <p class="description">Быстрота загрузки страниц – важный фактор при использовании интернет-магазина через мобильный интернет на смартфонах. Мы используем технологии, позволяющие увеличить скорость загрузки страниц сайта в соответствии с рекомендациями Google.</p> </div> <div class="tab-im col-12 col-lg-5"> <button class="tab-toggle-im">Оперативная техподдержка</button> </div> <div class="content col-12 col-lg-7"> <h3 class="heading d-none d-lg-block">Оперативная техподдержка</h3> <p class="description">После разработки интернет-магазина и его запуска мы гарантируем техническую поддержку и стабильность работы сайта. Мы учим Вас наполнять разделы товарами, обрабатывать заказы и оказываем консультационные услуги. Дополнительное маркетинговое сопровождение сайта позволит Вам получать актуальные советы по развитию и продвижению ресурса.</p> </div> </div> </div> </div> </div> </section> <p><a name="portfolio"></a></p> <section id="works"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Наши работы</h2> <h2>примеры интернет-магазинов, разработанных компанией WeDo</h2> </div> </div> <div class="row append-dots"> <div class="owl-carousel slider-work-im"> <a href="https://chikiss.com.ua/" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide1"> <div class="wrap-descr"> <p>Интернет-магазин нижнего белья и одежды с интеграцией с 1С</p> <div class="wrap-link"> <p>chikiss.com.ua</p> </div> </div> </div> </div> </a> <a href="https://lotos24.com.ua" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide2"> <div class="wrap-descr"> <p>Интернет-магазин бытовой химии и косметики с интеграцией с 1С</p> <div class="wrap-link"> <p>lotos24.com.ua</p> </div> </div> </div> </div> </a> <a href="https://ankor-crimea.ru" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide3"> <div class="wrap-descr"> <p>Интернет-магазин строительных материалов</p> <div class="wrap-link"> <p>ankor-crimea.ru</p> </div> </div> </div> </div> </a> <a href="https://ankor-profili.ru" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide4"> <div class="wrap-descr"> <p>Лэндинг для контекстной рекламы</p> <div class="wrap-link"> <p>ankor-profili.ru</p> </div> </div> </div> </div> </a> <a href="https://поликарбонкрым.рф" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide5"> <div class="wrap-descr"> <p>Лэндинг для контекстной рекламы</p> <div class="wrap-link"> <p>поликарбонкрым.рф</p> </div> </div> </div> </div> </a> <a href="https://cmservice.com.ua/" target="_blank" rel="nofollow"> <div class="item"> <div class="wrap-slid slide6"> <div class="wrap-descr"> <p>Сайт-каталог официального представителя кофемашин WMF в Украине</p> <div class="wrap-link"> <p>cmservice.com.ua</p> </div> </div> </div> </div> </a> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#free-consult-im" class="btn-pink" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </section> <p><a name="stoimost"></a></p> <section id="cost"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Стоимость разработки интернет-магазина</h2> <h2>ориентировочная цена интернет-магазина формируется на базе выбранного пакета и опций</h2> </div> </div> <div class="row d-block d-lg-none"> <div class="col-12"> <div class="custom-tabs-mobile"> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#first-tab" role="tab">Первый</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#second-tab" role="tab">Средний</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#third-tab" role="tab">Бизнес</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane active" id="first-tab" role="tabpanel"> <div class="price"> <p><span>$</span>2000</p> </div> <ul> <li><span>1000 товаров</span></li> <li><span>20 групп товаров</span></li> <li><span>Разработка структуры каталога</span></li> <li><span>База клиентов и список заказов на сайте</span></li> <li><span>Сравнение товаров, Избранное</span></li> <li><span>Функция купить в 1 клик</span></li> <li><span>Новости</span></li> <li><span>Поделиться в социальных сетях</span></li> </ul> <div class="wrap-btn"> <div class="button" id="light" name="Первый"> <a href="javascript:void(0)" ontouchstart="" class="btn-pink" data-wipe="Выбрать">Выбрать</a> </div> </div> </div> <div class="tab-pane" id="second-tab" role="tabpanel"> <div class="price"> <p><span>$</span>3000</p> </div> <ul> <li><span>5000 товаров</span></li> <li><span>50 групп товаров</span></li> <li><span>Весь функционал пакета Первый +</span></li> <li><span>Оптимизированный хостинг на год</span></li> <li><span>Работа по протоколу https</span></li> <li><span>Гибкая настройка дизайна</span></li> <li><span>Умный фильтр в каталоге и поиске</span></li> <li><span>Разновидности (SKU)</span></li> <li><span>Статусы наличия товара</span></li> <li><span>Отзывы о товаре</span></li> <li><span>Уведомление о новых заказах в Telegram</span></li> <li><span>Подробная информация о производителе товара</span></li> <li><span>Отдельные страницы для новинок, распродаж</span></li> <li><span>Регистрация и авторизация через соц.сети</span></li> <li><span>Покупка без регистрации</span></li> <li><span>Чат с менеджером на сайте</span></li> </ul> <div class="wrap-btn"> <div class="button" id="medium" name="Средний"> <a href="javascript:void(0)" ontouchstart="" class="btn-pink" data-wipe="Выбрать">Выбрать</a> </div> </div> </div> <div class="tab-pane" id="third-tab" role="tabpanel"> <div class="price"> <p><span>$</span>5000</p> </div> <ul> <li><span>Любое число товаров</span></li> <li><span>Любое число групп товаров</span></li> <li><span>Весь функционал пакета Средний +</span></li> <li><span>Отзывы о магазине</span></li> <li><span>Несколько типов цен (оптовая, розничная и т.д.)</span></li> <li><span>Наборы и комплекты</span></li> <li><span>Выставление счёта на сайте</span></li> <li><span>Накопительные скидки</span></li> <li><span>Баллы и бонусы</span></li> <li><span>Холдинговая структура</span></li> <li><span>A/B тестирование страниц</span></li> <li><span>Email-рассылки с анализом конверсии</span></li> </ul> <div class="wrap-btn"> <div class="button" id="premium" name="Бизнес"> <a href="javascript:void(0)" ontouchstart="" class="btn-pink" data-wipe="Выбрать">Выбрать</a> </div> </div> </div> </div> </div> </div> </div> <div class="row d-none d-lg-block"> <div class="col-12"> <div class="table"> <div class="table-container"> <div class="table-container-header"> <table class="table table-striped table-hover table-condensed table-bordered"> <thead> <tr> <th>Функционал</th> <th>Первый</th> <th>Средний</th> <th>Бизнес</th> </tr> </thead> </table> </div> <hr class="header-shadow"> <div class="table-container-body"> <table class="table table-hover table-condensed table-bordered"> <colgroup> <col></col> <col></col> <col></col> <col></col> </colgroup> <tbody> <tr> <td>Количество товаров</td> <td>до 1000</td> <td>до 5000</td> <td>&#8734</td> </tr> <tr> <td>Количество групп товаров</td> <td>до 20</td> <td>до 50</td> <td>&#8734</td> </tr> <tr> <td>База клиентов на сайте</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Список заказов на сайте</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Поиск по каталогу, свойствам и разделам</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Сравнение товаров</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Избранные товары</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Новости</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Поделиться в социальных сетях</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Гибкая настройка дизайна</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Разработка структуры каталога</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>СЕО-оптимизированные описания разделов каталога</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>СЕО-оптимизированные описания общих страниц ИМ</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Функция купить в 1 клик</td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Оптимизированный хостинг на год</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Работа по протоколу https</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Умный фильтр в каталоге и поиске</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Покупка без регистрации</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Разновидности (SKU)</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Статусы наличия товара (в наличии, под заказ, недоступно)</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Отзывы о товаре</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Информирование менеджеров о новых заказах в Telegram</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Подробная информация о производителе товара</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Отдельные страницы для новинок, распродаж и т.д.</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Регистрация и авторизация через соц.сети</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Чат с менеджером на сайте</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>A/B тестирование страниц</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Email-рассылки с анализом конверсии</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Отзывы о магазине</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Несколько типов цен (оптовая, розничная и т.д.)</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Наборы и комплекты</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Выставление счёта на сайте</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Накопительные скидки</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Баллы и бонусы</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> <tr> <td>Холдинговая структура</td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons close-ico">close</i></div></td> <td><div><i class="material-icons check-ico">done</i></div></td> </tr> </tbody> </table> </div> <hr class="bottom-shadow"> <div class="table-container-footer"> <table class="table table-striped table-hover table-condensed table-bordered"> <tfoot> <tr> <th>Стоимость</th> <th> <div class="price">$2000</div> <div class="wrap-btn"> <div class="button" id="light" name="Первый"> <a href="javascript:void(0)" ontouchstart="" class="btn-pink" data-wipe="Выбрать">Выбрать</a> </div> </div> </th> <th> <div class="price">$3000</div> <div class="wrap-btn"> <div class="button" id="medium" name="Средний"> <a href="javascript:void(0)" ontouchstart="" class="btn-pink" data-wipe="Выбрать">Выбрать</a> </div> </div> </th> <th> <div class="price">$5000</div> <div class="wrap-btn"> <div class="button" id="premium" name="Бизнес"> <a href="javascript:void(0)" ontouchstart="" class="btn-pink" data-wipe="Выбрать">Выбрать</a> </div> </div> </th> </tr> </tfoot> </table> </div> </div> </div> </div> </div> <div class="row"> <div class="col-12 col-lg-7"> <div class="options"> <div class="title-options"> <p>Дополнительные опции:</p> </div> <form class="checkbox-form"> <label for="mycheck1" class="c-custom-check" data-toggle="tooltip" data-placement="top" data-html="true" title="<ul><li>Управление ассортиментом ИМ из 1С</li><li>Выгрузка остатков и цен на сайт</li><li>Загрузка заказов в 1С</li><li>Хранение фотографий товаров за пределами базы 1С</li></ul>"> Обмен с 1С <input required type="checkbox" id="mycheck1" name="Обмен с 1С"> <div class="c-custom-check__indicator"></div> </label> <label for="mycheck2" class="c-custom-check" data-toggle="tooltip" data-placement="top" data-html="true" title=""> Оплата на сайте платёжной картой через систему Platon <input required type="checkbox" id="mycheck2" name="Оплата на сайте платёжной картой через систему Platon"> <div class="c-custom-check__indicator"></div> </label> <label for="mycheck3" class="c-custom-check" data-toggle="tooltip" data-placement="top" data-html="true" title="<ul><li>Выбор города и склада делает заказ удобнее</li><li>Меньше ошибок при заполнении адреса доставки</li></ul>"> Новая почта API на сайте <input required type="checkbox" id="mycheck3" name="Новая почта API на сайте"> <div class="c-custom-check__indicator"></div> </label> <label for="mycheck4" class="c-custom-check" data-toggle="tooltip" data-placement="top" data-html="true" title="<ul><li>Формирование ТТН на основе заказов</li><li>Контроль оплат наложенных платежей</li></ul>"> Новая почта API в 1С <input required type="checkbox" id="mycheck4" name="Новая почта API в 1С"> <div class="c-custom-check__indicator"></div> </label> <label for="mycheck5" class="c-custom-check" data-toggle="tooltip" data-placement="top" data-html="true" title="<ul><li>Полезно для длительных сделок</li></ul>"> Интеграция с CRM <input required type="checkbox" id="mycheck5" name="Интеграция с CRM"> <div class="c-custom-check__indicator"></div> </label> <label for="mycheck6" class="c-custom-check" data-toggle="tooltip" data-placement="top" data-html="true" title="<ul><li>Перенос карточек товара</li><li>Перенаправление страниц</li></ul>"> Переезд на новый сайт <input required type="checkbox" id="mycheck6" name="Переезд на новый сайт"> <div class="c-custom-check__indicator"></div> </label> <label for="mycheck7" class="c-custom-check" data-toggle="tooltip" data-placement="top" data-html="true" title=""> СЕО-фильтр+настройка <input required type="checkbox" id="mycheck7" name="СЕО-фильтр+настройка"> <div class="c-custom-check__indicator"></div> </label> </form> </div> </div> <div class="col-12 col-lg-5"> <div class="wrap-cost"> <div class="cost"> <div class="price"> <p>Стоимость</p> <div class="total-price" id="totalPrice">$2150</div> </div> <div class="time"> <p>Сроки</p> <div class="total-time" id="totalTime">2 месяца</div> </div> <div class="footnote"> <p>Стоимость и сроки предварительны. Свяжитесь с нами для точного расчета</p> </div> </div> </div> </div> </div> <div class="row home-button"> <div class="col-12"> <div class="wrap-btn"> <div class="button"> <a href="#" ontouchstart="" data-toggle="modal" id="modalBtn" data-target="#commercial-im" class="btn-pink" data-wipe="Заказать коммерческое предложение">Заказать коммерческое предложение</a> </div> </div> </div> </div> </div> </section> <p><a name="onas"></a></p> <section id="why-us"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Веб-студия WeDo – факты о нас</h2> <h2>разрабатывая интернет-магазины, мы стараемся быть лучшими в этом, и вот подтверждение</h2> </div> </div> <div class="row wrap-why-us"> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon1.png" alt="Партнеры"> </div> <div class="text"> <p>Партнёр Google, Bitrix, Shopify</p> </div> </div> </div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon2.png" alt="Обучение сотрудников"> </div> <div class="text"> <p>Все сотрудники проходили обучение в Bitrix, Google, 1С</p> </div> </div> </div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon3.png" alt="Опыт работы"> </div> <div class="text"> <p>Опыт работы в сфере IT (1С, web) с 2008 года</p> </div> </div> </div> <div class="w-100"></div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon4.png" alt="Полный цикл"> </div> <div class="text"> <p>Полный цикл Разработка - Интеграция - Поддержка - Продвижение</p> </div> </div> </div> <div class="col-12 col-md item-fact"> <div class="wrap-fact"> <div class="icon"> <img src="<?=$templateUriA?>/img/for_im/icon5.png" alt="Успешные проекты"> </div> <div class="text"> <p>Более 100 успешных проектов в 1С и web</p> </div> </div> </div> </div> </div> </section> <section id="promotion"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Продвижение интернет-магазинов после запуска</h2> <h2>разработка сайта и маркетинговое сопровождение принесут максимум эффекта в сочетании с таким продвижением</h2> </div> </div> <div class="row append-dots"> <div class="all-card owl-carousel slider-seo"> <div class="item"> <div class="card-wrap"> <a href="../seo/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SEO</p> </div> <div class="description-card"> <p>Увеличение видимости интернет-магазина в поисковой системе и привлечение пользователей</p> </div> </div> </a> </div> </div> <div class="item"> <div class="card-wrap"> <a href="../kontekstnaya-reklama/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>PPC</p> </div> <div class="description-card"> <p>Контекстная реклама для быстрого привлечения клиентов, планирующих покупку</p> </div> </div> </a> </div> </div> <div class="item"> <div class="card-wrap"> <a href="../smm/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SMM</p> </div> <div class="description-card"> <p>Повышения узнаваемости компании и бренда, завоевания доверия потенциальных клиентов</p> </div> </div> </a> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#free-consult-im" class="btn-pink" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </section> <footer> <div class="container"> <div class="row items justify-content-center align-items-center no-gutters"> <div class="col-12 col-md-12 col-xl-12 item justify-content-center align-items-center"> <div class="logo-footer"> <a href=""><img src="<?=$templateUriA?>/img/for_im/logo.png" alt="WeDo"></a> <div class="footer-phone"> <a href="tel:++38(098)150-83-95">+38(098)150-83-95</a> </div> <p>© Copyright 2018, Все права защищены</p> </div> </div> </div> </div> </footer> <!-- Modal --> <div class="modal call-us fade" id="free-consult-im"> <div class="modal-dialog"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/for_im/close.png" alt=""> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <h3 class="modal-title">Укажите, пожалуйста, Ваши контактные данные, и мы предоставим Вам бесплатную консультацию</h3> </div> </div> <div id="hidden-row" class="row"> <div class="modal-body"> <div class="container1"> <div class="card"> <form id="callback-form"> <div class="input-container"> <input type="text" id="name-free-consult-im" name="name-free-consult-im" required> <label for="name-free-consult-im">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-free-consult-im" value="" name="phone-free-consult-im" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-free-consult-im">Телефон</label> <div class="bar"></div> </div> <div id="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <label for="comment-free-consult-im">Комментарий</label> <textarea id="comment-free-consult-im" name="comment-free-consult-im"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить заявку">Отправить заявку</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> </div> <div class="modal commercial fade" id="commercial-im"> <div class="modal-dialog"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/for_im/close.png" alt=""> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <h3 class="modal-title">Укажите, пожалуйста, Ваши контактные данные, и мы предоставим Вам бесплатную консультацию</h3> </div> </div> <div id="hidden-row" class="row"> <div class="modal-body"> <div class="container1"> <div class="card"> <form id="commercial-offer"> <div class="summary-output"> <div class="tariff-plan"> <div class="title">Тариф:</div> <div class="value" id="mainTariff">Первый</div> <input id="tariff" name="tariff" type="hidden" value=""> </div> <div class="additional-options"> <div class="title">Доп. опции:</div> <div class="value" id="additionalOptions"></div> <input id="options" name="options" type="hidden" value=""> </div> <div class="date"> <div class="title">Сроки:</div> <div class="value" id="totalTimeForm">-</div> <input id="date" name="date" type="hidden" value=""> </div> <div class="cost"> <div class="title">Стоимость:</div> <div class="value" id="totalPriceForm"></div> <input id="cost-val" name="cost-val" type="hidden" value=""> </div> </div> <div class="wrap-input"> <div class="input-container"> <input type="text" id="Username-com" name="Username-com" required> <label for="Username-com">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-com" value="" name="phone-com" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-com">Телефон</label> <div class="bar"></div> </div> <div id="errorMessage2" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить заявку">Отправить заявку</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> </div> <div class="modal thank-you fade" id="modal-thank" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <p>Спасибо! Наш специалист свяжется с вами в ближайшее время.</p> </div> <div class="modal-footer"> <div class="wrap-btn"> <div class="button"> <a href="#" ontouchstart="" data-dismiss="modal" class="btn-pink" data-wipe="ОК">ОК</a> </div> </div> </div> </div> </div> </div> <!-- END Modal --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=$templateUriA?>/js/owl.carousel.min.js"></script> <script src="<?=$templateUriA?>/js/config.js"></script> <script src="<?=$templateUriA?>/js/waypoints.min.js"></script> <script src="<?=$templateUriA?>/js/animate-css.js"></script> <script src="<?=$templateUriA?>/js/main.js"></script> </body> </html><file_sep><!doctype html> <html lang="ru"> <head> <title>Разработка контекстной рекламы в Яндекс.Директ и Google Adwords - WeDo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="description" content="Реклама в интернете: Ваш сайт на первых страницах Google и Яндекса. Разработка, настройка и ведение рекламных компаний в Яндекс. Директе и Google Adwords. Узнайте сколько клиентов Вы сможете получить за 1 неделю рекламы!"> <meta name="yandex-verification" content="80567c69a37b1299" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script> <link rel="stylesheet" href="<?=$templateUriA?>/css/main.css"> <script src="<?=$templateUriA?>/js/jquery.selectric.js"></script> <script src="<?=$templateUriA?>/js/bootstrap-formhelpers.min.js"></script> <link rel="shortcut icon" href="<?=$templateUriA?>/img/logo_fav.ico" type="image/x-icon"> </head> <body> <div class="head-kr"> <div class="container head-content"> <div class="row top-line"> <div class="col-4 col-md-5 col-lg-6"> <div class="logo"> <a href="#"><img src="<?=$templateUriA?>/img/logo-green.png" alt="WeDo"></a> </div> </div> <div class="col-6 col-md-6 col-lg-5"> <div class="phone"> <a href="tel:+38(098)151-20-15">+38(098)151-20-15</a> </div> </div> <div class="col-2 col-md-1 col-lg-1"> <div class="hamburger-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <nav class="nav-menu"> <div class="responsive-nav"> <span></span> <span></span> <span></span> </div> <ul class="main-menu"> <li><a href="/">Главная</a></li> <li><a href="/sozdanie-saitov/">Создание сайтов</a></li> <li><a href="/internet-magaziny/">Создание интернет-магазинов</a></li> <li><a href="/kontekstnaya-reklama/">Контекстная реклама</a></li> <li><a href="/seo/">SEO-продвижение</a></li> <li><a href="/smm/">SMM</a></li> <li class="current_page"><a href="/blog/">Блог</a></li> </ul> </nav> </div> </div> </div> <div class="row center-line"> <div class="col"> <h1 class="title-page-marketing"> <span class="h1 h1_ppc">PPC</span> <span class="h1_text"> <span class="main-text">Контекстная реклама в Google и Яндекс</span> <span class="additional-text">Google AdWord, Яндекс Директ</span> </span> </h1> </div> </div> <div class="row bottom-line"> <div class="col"> <p>Сколько клиентов вы получите за неделю рекламы?</p> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-discover-kr" data-wipe="Узнать">Узнать</a> </div> </div> </div> </div> </div> </div> </div> <div class="whom-kr"> <div class="container"> <div class="row wrap-title justify-content-center"> <div class="col-12 col-md-12 col-xl-8"> <h2>Кому подойдёт контекстная реклама?</h2> <p>компаниям в сфере торговли и обслуживания, которые:</p> </div> </div> <div class="row items justify-content-center"> <div class="col-xl-6"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/check-square.png" alt="check"> </div> <div class="text"> <p>Продают товары и услуги широкого спроса (технику, одежду, строительные материалы, бытовую химию и т.д.)</p> </div> </div> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/check-square.png" alt="check"> </div> <div class="text"> <p>Работают на высоко конкурентном рынке</p> </div> </div> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/check-square.png" alt="check"> </div> <div class="text"> <p>Хотят выйти в новые регионы</p> </div> </div> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/check-square.png" alt="check"> </div> <div class="text"> <p>Клиенты нужны «на вчера»</p> </div> </div> </div> </div> </div> </div> <div class="advantage-kr"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <p>Контекстная реклама Google AdWords и Яндекс Директ – это гарантированное размещение сайта на первой странице поиска</p> </div> </div> <div class="row items"> <div class="col-lg-4 col-xl-4"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/search-property.png" alt="search"> </div> <hr> <div class="text"> <p>Сайт будет показан только по коммерческим запросам заинтересованным покупателям</p> </div> </div> </div> <div class="col-lg-4 col-xl-4"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/user-group-man.png" alt="search"> </div> <hr> <div class="text"> <p>Первые клиенты попадут на сайт сразу после размещения рекламы</p> </div> </div> </div> <div class="col-lg-4 col-xl-4"> <div class="item"> <div class="icon"> <img src="<?=$templateUriA?>/img/icons/online-payment.png" alt="search"> </div> <hr> <div class="text"> <p>Оплата только за переход на сайт или совершение нужного действия</p> </div> </div> </div> </div> </div> </div> <p><a name="results"></a></p> <div class="result-kr"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Результаты контекстной рекламы наших клиентов</h2> <p></p> </div> </div> <div class="row append-dots"> <div class="owl-carousel slider-work"> <div class="item"> <div class="wrap-slid slide1"> <div class="wrap-descr"> <p class="title">Продажа поликарбоната и комплектующих</p> <p class="sub-title">Реклама на лендинг компании Анкор</p> <div class="wrap-link"> <a href="http://ankor.com.ua" target="_blank" rel="nofollow">ankor.com.ua</a> </div> <div class="details"> <p><span class="green-text">Поисковая сеть: </span>Яндекс</p> <p><span class="green-text">Длительность: </span>2 недели (апрель 2018)</p> <p><span class="green-text">Показатель эффективности: </span></p> <ul> <li>CTR 25,43%</li> <li>Прогнозная цена клика – 8 грн. <br>Реальная цена клика – 5 грн.</li> <li>Бюджет на клики - 900 грн.</li> <li>Доход от рекламы – 24500 грн.</li> </ul> </div> </div> </div> </div> <div class="item"> <div class="wrap-slid slide2"> <div class="wrap-descr"> <p class="title">Услуга ринопластика (пластика носа)</p> <p class="sub-title">Реклама на сайт Центра пластической хирургии и эстетической медицины «Vidnova»</p> <div class="wrap-link"> <a href="https://vidnova.com.ua" target="_blank" rel="nofollow">vidnova.com.ua</a> </div> <div class="details"> <p><span class="green-text">Поисковая сеть: </span>Google</p> <p><span class="green-text">Длительность: </span>3 недели (июнь 2017)</p> <p><span class="green-text">Показатели эффективности:</span></p> <ul> <li>Прогнозный CTR – 3,8% <br>Реальный CTR – 19%</li> <li>Прогнозная цена перехода на сайт – 17,70 грн. <br>Реальная цена перехода на сайт – 8,94 грн.</li> <li>Просмотров страниц/сеанс – 6, 13</li> <li>Отказы – 6,68%</li> <li>+57% посетителей сайта</li> </ul> </div> </div> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_blue"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-kr" class="btn-pink" data-wipe="Заказать контекстную рекламу">Заказать контекстную рекламу</a> </div> </div> </div> </div> </div> <p><a name="prices"></a></p> <div class="price-table-kr"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Цена на контекстную рекламу</h2> <p></p> </div> </div> <div class="row button-tariff-kr d-flex d-md-none"> <div class="col-6"> <button class="2 btn-tariff btn-tariff-one btn-tariff_active">Разработка</button> </div> <div class="col-6"> <button class="3 btn-tariff btn-tariff-two">Основной</button> </div> </div> <div class="row"> <table class="table custom-table table-bordered table-hover-custom"> <thead> <tr> <th class="t-col1 title" scope="col">Тарифы</th> <th class="t-col2 title" scope="col">Разработка</th> <th class="t-col3 title" scope="col">Основной</th> </tr> </thead> <tbody> <tr> <th class="t-col1" scope="row">Описание</th> <td class="t-col2">Вы получите готовую рекламу в поисковой системе, за которой будете следить сами</td> <td class="t-col3">Вы получите рекламу «под ключ», включая создание, сопровождение и отчёты об эффективности с корректировками стратегии</td> </tr> <tr> <th class="t-col1" scope="row">Кому подойдёт</th> <td class="t-col2">Компаниям, у которых в штате есть штатная единица для ведения кампании</td> <td class="t-col3">Бизнесу, который нацелен на максимальную эффективность рекламы и планирует рекламировать большое количество товарных групп</td> </tr> <tr> <th class="t-col1" scope="row">Поисковая система</th> <td class="t-col2">Google или Яндекс</td> <td class="t-col3">Google или Яндекс</td> </tr> <tr> <th class="t-col1" scope="row">Разработка рекламы в поисковой системе</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Рекламная и партнёрская сеть (КМС, РСЯ) <br> <span class="small-italic">Реклама будет показана на площадках (сайтах), которые входят в рекламную сеть поисковых систем</span></th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3">Возможно опционально</td> </tr> <tr> <th class="t-col1" scope="row">Количество фраз</th> <td class="t-col2">До 1000</td> <td class="t-col3">До 1000</td> </tr> <tr> <th class="t-col1" scope="row">Ретаргетинг, ремаркетинг</th> <td class="t-col2">Возможно опционально</td> <td class="t-col3">Возможно опционально</td> </tr> <tr> <th class="t-col1" scope="row">Установка систем аналитики и настройка целей на сайте</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Ежедневное сопровождение</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Отчёт за месяц</th> <td class="t-col2"><img src="<?=$templateUriA?>/img/icons/close_gray.png" alt="no"></td> <td class="t-col3"><img src="<?=$templateUriA?>/img/icons/check_green.png" alt="yes"></td> </tr> <tr> <th class="t-col1" scope="row">Цена</th> <td class="t-col2">2700 грн. - разово</td> <td class="t-col3">2700 грн. - ежемесячно</td> </tr> <tr> <th class="t-col1" scope="row">Ежемесячный бюджет на клики <br> <span class="small-italic">Эту сумму вы вносите непосредственно в рекламный аккаунт Google или Яндекс. Они расходуются исключительно на клики. </span></th> <td class="t-col2">Рассчитывается индивидуально для каждого бизнеса. Вы можете оплачивать как рекомендованную нами сумму, так и меньше. Мы предоставляем сведения о том, какое количество клиентов вы получите за ту сумму, которую планируете вложить. <br><br><a href="#" data-toggle="modal" data-target="#modal-freecalc-kr">Заказать бесплатный расчёт</a></td> <td class="t-col3">Рассчитывается индивидуально для каждого бизнеса. Вы можете оплачивать как рекомендованную нами сумму, так и меньше. Мы предоставляем сведения о том, какое количество клиентов вы получите за ту сумму, которую планируете вложить. <br><br><a href="#" data-toggle="modal" data-target="#modal-freecalc-kr">Заказать бесплатный расчёт</a></td> </tr> <tr> <th class="t-col1" scope="row"><img src="<?=$templateUriA?>/img/icons/gift.png" alt="Gift">Ваши подарки</th> <td class="t-col2">Рекомендации по сопровождению компании и KPI для отслеживания эффективности</td> <td class="t-col3">Скидка 10% на SEO или рекламу в социальных сетях</td> </tr> </tbody> </table> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-kr" data-wipe="Заказать контекстную рекламу">Заказать контекстную рекламу</a> </div> </div> </div> </div> </div> <div class="stages-kr"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2>Этапы работ по созданию контекстной рекламы</h2> <p></p> </div> </div> <div class="row d-flex d-lg-none"> <div class="col"> <div id="custom-accordion-kr"> <div class="card custom-card-kr"> <div class="card-header custom-card-header-kr"> <button class="btn btn_green_square" data-toggle="collapse" data-target="#stage1" aria-expanded="true" aria-controls="stage1"> 1 </button> <p class="d-block d-lg-none">Планирование</p> </div> <div id="stage1" class="collapse fade show" aria-labelledby="headingOne" data-parent="#custom-accordion-kr"> <div class="card-body custom-body-kr"> <p class="d-none d-lg-block">Планирование</p> <ul> <li>Изучение вашего бизнеса и ниши</li> <li>Анализ конкурентов</li> <li>Выявление ваших преимуществ и составление уникального торгового предложения</li> </ul> </div> </div> </div> <div class="card custom-card-kr"> <div class="card-header custom-card-header-kr"> <button class="btn btn_green_square collapsed" data-toggle="collapse" data-target="#stage2" aria-expanded="true" aria-controls="stage2"> 2 </button> <p class="d-block d-lg-none">Разработка рекламной кампании</p> </div> <div id="stage2" class="collapse fade" aria-labelledby="headingTwo" data-parent="#custom-accordion-kr"> <div class="card-body custom-body-kr"> <p class="d-none d-lg-block">Разработка рекламной кампании</p> <ul> <li>Сбор ключевых слов</li> <li>Составление списка минус-слов</li> <li>Создание эффективных объявлений (2-3 объявления для каждой ключевой фразы, из которых через время выберем самые конверсионные)</li> <li>Кроссминусация для того, чтобы ключевые слова и объявления в вашей кампании не конкурировали друг с другом</li> </ul> </div> </div> </div> <div class="card custom-card-kr"> <div class="card-header custom-card-header-kr"> <button class="btn btn_green_square collapsed" data-toggle="collapse" data-target="#stage3" aria-expanded="true" aria-controls="stage3"> 3 </button> <p class="d-block d-lg-none">Настраиваем рекламную кампанию</p> </div> <div id="stage3" class="collapse fade" aria-labelledby="headingThird" data-parent="#custom-accordion-kr"> <div class="card-body custom-body-kr"> <p class="d-none d-lg-block">Настраиваем рекламную кампанию</p> <ul> <li>Загружаем согласованную с вами рекламную кампанию в соответствующую поисковую систему</li> <li>Настраиваем регион, время и режим показов</li> <li>Выбираем наиболее эффективную стратегию показов</li> <li>Устанавливаем дневные ограничения на расход бюджета</li> <li>Добавляем расширения для объявления (уточнения, списки услуг, дополнительных товаров, телефоны, адреса и т.д.)</li> </ul> </div> </div> </div> <div class="card custom-card-kr"> <div class="card-header custom-card-header-kr"> <button class="btn btn_green_square collapsed" data-toggle="collapse" data-target="#stage4" aria-expanded="true" aria-controls="stage4"> 4 </button> <p class="d-block d-lg-none">Сопровождение (ежедневное)</p> </div> <div id="stage4" class="collapse fade" aria-labelledby="headingFour" data-parent="#custom-accordion-kr"> <div class="card-body custom-body-kr"> <p class="d-none d-lg-block">Сопровождение (ежедневное)</p> <ul> <li>Корректировка стратегии показов</li> <li>Добавление минус-слов</li> <li>Дополнительная кроссминусация для групп и кампаний</li> <li>Расширение списка ключевых слов</li> <li>А/В тестирование объявлений</li> <li>Анализ поведенческих факторов посетителей из рекламных объявлений на сайте</li> <li>Рекомендации по улучшению сайта на основе анализа поведения пользователей</li> <li>Ежемесячный отчёт об эффективности рекламной кампании по фиксированным KPI</li> </ul> </div> </div> </div> <hr class="dotted-line d-none d-lg-block"> </div> </div> </div> <div class="row d-none d-lg-block"> <div class="col"> <section class="s-accordion"> <div class="panel panel--one active-tab"> <div class="panel--wrap"> <p class="step-number">1</p> <div class="panel--text"> <p>Планирование</p> <ul> <li>Изучение вашего бизнеса и ниши</li> <li>Анализ конкурентов</li> <li>Выявление ваших преимуществ и составление уникального торгового предложения</li> </ul> </div> </div> </div> <div class="panel panel--two"> <div class="panel--wrap"> <p class="step-number">2</p> <div class="panel--text"> <p>Разработка рекламной кампании</p> <ul> <li>Сбор ключевых слов</li> <li>Составление списка минус-слов</li> <li>Создание эффективных объявлений (2-3 объявления для каждой ключевой фразы, из которых через время выберем самые конверсионные)</li> <li>Кроссминусация для того, чтобы ключевые слова и объявления в вашей кампании не конкурировали друг с другом</li> </ul> </div> </div> </div> <div class="panel panel--three"> <div class="panel--wrap"> <p class="step-number">3</p> <div class="panel--text"> <p>Настраиваем рекламную кампанию</p> <ul> <li>Загружаем согласованную с вами рекламную кампанию в соответствующую поисковую систему</li> <li>Настраиваем регион, время и режим показов</li> <li>Выбираем наиболее эффективную стратегию показов</li> <li>Устанавливаем дневные ограничения на расход бюджета</li> <li>Добавляем расширения для объявления (уточнения, списки услуг, дополнительных товаров, телефоны, адреса и т.д.)</li> </ul> </div> </div> </div> <div class="panel panel--four"> <div class="panel--wrap"> <p class="step-number">4</p> <div class="panel--text"> <p>Сопровождение (ежедневное)</p> <ul> <li>Корректировка стратегии показов</li> <li>Добавление минус-слов</li> <li>Дополнительная кроссминусация для групп и кампаний</li> <li>Расширение списка ключевых слов</li> <li>А/В тестирование объявлений</li> <li>Анализ поведенческих факторов посетителей из рекламных объявлений на сайте</li> <li>Рекомендации по улучшению сайта на основе анализа поведения пользователей</li> <li>Ежемесячный отчёт об эффективности рекламной кампании по фиксированным KPI</li> </ul> </div> </div> </div> <hr class="dotted-line d-none d-lg-block"> </section> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-6"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-order-kr" data-wipe="Заполнить заявку на контекстную рекламу">Заполнить заявку на контекстную рекламу</a> </div> </div> </div> </div> </div> <p><a name="seo_smm"></a></p> <div class="promotion"> <div class="container"> <div class="row wrap-title justify-content-end"> <div class="col-12 col-md-12 col-xl-11"> <h2 class="title_light">Другие способы продвижения сайта</h2> </div> </div> <div class="row append-dots"> <div class="other-mathods owl-carousel slider-other-mathods"> <div class="item"> <div class="card-wrap"> <a href="/smm/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SMM</p> </div> <div class="description-card"> <p>Повышения узнаваемости компании и бренда, завоевания доверия потенциальных клиентов</p> </div> </div> </a> </div> </div> <div class="item"> <div class="card-wrap"> <a href="/seo/" class="link-to-other-page" target="_blank"> <div class="card"> <div class="title-card"> <p>SEO</p> </div> <div class="description-card"> <p>Увеличение видимости интернет-магазина в поисковой системе и привлечение пользователей</p> </div> </div> </a> </div> </div> </div> </div> <div class="row wrap-btn align-items-center justify-content-center"> <div class="col-12 col-xl-4"> <div class="button button_green"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-free-cosult-kr" data-wipe="Бесплатная консультация">Бесплатная консультация</a> </div> </div> </div> </div> </div> <div class="call-back-kr"> <a href="#" ontouchstart="" data-toggle="modal" data-target="#modal-callback-kr"> <img src="<?=$templateUriA?>/img/icons/shake-phone.png" alt="Phone"> <div class="overlay"> <div class="text">Обратный звонок</div> </div> </a> </div> <div class="footer-kr"> <div class="container"> <div class="row items justify-content-center align-items-center no-gutters"> <div class="col-12 col-md-12 col-xl-12 item justify-content-center align-items-center"> <div class="logo-footer"> <a href=""><img src="<?=$templateUriA?>/img/logo-green.png" alt="WeDo"></a> <div class="footer-phone"> <a href="tel:+38(098)151-20-15">+38(098)151-20-15</a> </div> <p>© Copyright 2018, Все права защищены</p> </div> </div> </div> </div> </div> <div class="modal call-us fade modal-kr" id="modal-callback-kr"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Заказ обратного звонка</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="callback-form-kr"> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="Username-kr" name="Username-kr" required> <label for="Username-kr">Имя</label> <div class="bar"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-kr" value="" name="phone-kr" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-kr">Телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-kr" id="modal-discover-kr"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="modal-body"> <div class="card"> <form id="discover-form"> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="address-discover" name="address-discover"> <label for="address-discover">Адрес сайта</label> <div class="bar"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-discover" value="" name="phone-discover" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-discover">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="input-container"> <input type="text" id="budget-discover" name="budget-discover" required> <label for="budget-discover">Плановый бюджет в месяц</label> <div class="bar"></div> </div> <div class="input-container"> <input type="text" id="goods-discover" name="goods-discover" required> <label for="goods-discover">Рекламируемые товары и услуги</label> <div class="bar"></div> </div> <div class="input-container"> <input type="text" id="regions-discover" name="regions-discover" required> <label for="regions-discover">Регионы для показа рекламы</label> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Получить предложение">Получить предложение</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-kr" id="modal-order-kr"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <p class="modal-title">Наш менеджер свяжется с Вами, чтобы обсудить контекстную рекламу</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="order-kr-form"> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="address-order-kr" name="address-order-kr"> <label for="address-order-kr">Адрес сайта</label> <div class="bar"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-order-kr" value="" name="phone-order-kr" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-order-kr">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="input-container"> <select class="form-control" id="select-tariff" name="select-tariff" required> <option value="" disabled selected>не указано</option> <option value="разработка">разработка</option> <option value="основной">основной</option> </select> <label for="select-tariff">Тариф</label> <div class="bar"></div> </div> <div class="input-container"> <input type="text" id="regions-order-kr" name="regions-order-kr" required> <label for="regions-order-kr">Регионы для показа рекламы</label> <div class="bar"></div> </div> <div class="input-container"> <label for="comment">Комментарий</label> <textarea id="comment" name="comment"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-kr" id="modal-freecalc-kr"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Заказ бесплатного расчёта</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="freecalc-kr-form"> <div class="row"> <div class="col-xl-6"> <div class="input-container"> <input type="text" id="address-freecalc" name="address-freecalc"> <label for="address-freecalc">Адрес сайта</label> <div class="bar"></div> </div> </div> <div class="col-xl-6"> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-freecalc" value="" name="phone-freecalc" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-freecalc">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> </div> </div> <div class="input-container"> <input type="text" id="goods-freecalc" name="goods-freecalc" required> <label for="goods-freecalc">Рекламируемые товары и услуги</label> <div class="bar"></div> </div> <div class="input-container"> <input type="text" id="regions-freecalc" name="regions-freecalc" required> <label for="regions-freecalc">Регионы для показа рекламы</label> <div class="bar"></div> </div> <div class="input-container"> <label for="comment">Комментарий</label> <textarea id="comment-freecalc" name="comment-freecalc"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal fade modal-kr" id="modal-free-cosult-kr"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Укажите, пожалуйста, Ваши контактные данные, и мы предоставим Вам бесплатную консультацию</p> </div> </div> <div class="modal-body"> <div class="card"> <form id="free-cosult-kr-form"> <div class="input-container"> <input type="text" id="name-free-cosult-kr" name="name-free-cosult-kr" required> <label for="name-free-cosult-kr">Имя</label> <div class="bar"></div> </div> <div class="input-container number"> <input class="form-control bfh-phone" type="text" id="phone-free-cosult-kr" value="" name="phone-free-cosult-kr" data-format="+380 (dd) ddd-dd-dd" required> <label for="phone-free-cosult-kr">Ваш телефон</label> <div class="bar"></div> </div> <div class="errorMessage" style="display: none">Укажите Ваш телефон. (см. подсказку)</div> <div class="input-container"> <label for="comment-free-cosult-kr">Комментарий</label> <textarea id="comment-free-cosult-kr" name="comment-free-cosult-kr"></textarea> <div class="bar"></div> </div> <div class="button-container"> <div class="wrap-btn"> <div class="button button_green"> <button type="submit" ontouchstart="" class="btn" data-wipe="Отправить">Отправить</button> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <div class="modal modal-kr modal-thank fade" id="modal-thank" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="container-fluid"> <div class="row justify-content-end"> <div class="col-2 justify-content-end"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <img src="<?=$templateUriA?>/img/icons/close(black).png" alt="close"> </button> </div> </div> <div class="row justify-content-center"> <div class="col-10"> <p class="modal-title">Cпасибо!!! Мы свяжемся с вами в ближайшее время.</p> </div> </div> </div> <div class="wrap-btn"> <div class="button button_green"> <a href="#" ontouchstart="" data-dismiss="modal" data-wipe="ok">ok</a> </div> </div> </div> </div> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?=$templateUriA?>/js/owl.carousel.min.js"></script> <script src="<?=$templateUriA?>/js/config.js"></script> <script src="<?=$templateUriA?>/js/waypoints.min.js"></script> <script src="<?=$templateUriA?>/js/animate-css.js"></script> <script src="<?=$templateUriA?>/js/main.js"></script> </body> </html>
7cb6e0c8f63dac96a247dd0f6123b33326dd2e98
[ "Markdown", "PHP" ]
11
PHP
alexkorn22/wp_wedo_landing
fdf21bb53696f22cd9ffc6b68d727bd7da8bbc9c
bb1721039c881f411dfedfcd25a3d685bed9dfa0
refs/heads/master
<file_sep>// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: <PASSWORD> #include <Rcpp.h> using namespace Rcpp; // gng_cpp List gng_cpp(NumericMatrix x, int max_iterations, float epsilon_b, float epsilon_n, int age_max, int max_nodes, int lambda, float alpha, float beta, bool verbose); RcppExport SEXP _gng_gng_cpp(SEXP xSEXP, SEXP max_iterationsSEXP, SEXP epsilon_bSEXP, SEXP epsilon_nSEXP, SEXP age_maxSEXP, SEXP max_nodesSEXP, SEXP lambdaSEXP, SEXP alphaSEXP, SEXP betaSEXP, SEXP verboseSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type x(xSEXP); Rcpp::traits::input_parameter< int >::type max_iterations(max_iterationsSEXP); Rcpp::traits::input_parameter< float >::type epsilon_b(epsilon_bSEXP); Rcpp::traits::input_parameter< float >::type epsilon_n(epsilon_nSEXP); Rcpp::traits::input_parameter< int >::type age_max(age_maxSEXP); Rcpp::traits::input_parameter< int >::type max_nodes(max_nodesSEXP); Rcpp::traits::input_parameter< int >::type lambda(lambdaSEXP); Rcpp::traits::input_parameter< float >::type alpha(alphaSEXP); Rcpp::traits::input_parameter< float >::type beta(betaSEXP); Rcpp::traits::input_parameter< bool >::type verbose(verboseSEXP); rcpp_result_gen = Rcpp::wrap(gng_cpp(x, max_iterations, epsilon_b, epsilon_n, age_max, max_nodes, lambda, alpha, beta, verbose)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_gng_gng_cpp", (DL_FUNC) &_gng_gng_cpp, 10}, {NULL, NULL, 0} }; RcppExport void R_init_gng(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } <file_sep>#' Growing Neural Gas #' #' @import dplyr #' @import tidyr #' @import methods #' @import tibble #' @importFrom purrr %>% map map_df map_chr map_lgl map_int map_dbl keep set_names #' @importFrom magrittr %<>% %$% set_rownames set_colnames #' #' @docType package #' @name gng-project NULL <file_sep>--- output: md_document editor_options: chunk_output_type: console --- ```{r setup1, include=FALSE} knitr::opts_chunk$set(fig.path = "man/figures/README_", warning = FALSE, message = FALSE, error = FALSE, echo = TRUE) ``` # gng [![Build Status](https://travis-ci.org/rcannood/gng.svg?branch=master)](https://travis-ci.org/rcannood/gng) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/rcannood/gng?branch=master&svg=true)](https://ci.appveyor.com/project/rcannood/gng) [![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/gng)](https://cran.r-project.org/package=gng) [![Coverage Status](https://codecov.io/gh/rcannood/gng/branch/master/graph/badge.svg)](https://codecov.io/gh/rcannood/gng?branch=master) An implementation of the Growing Neural Gas algorithm in Rcpp. ## Example You can run gng as follows: ```{r iris} library(gng) data(iris) gng_fit <- gng(as.matrix(iris[,1:4])) ``` And visualise it as follows: ```{r plot} plot_gng(gng_fit, iris[,5], max_size = 0.05, max_size_legend = .15) ``` <file_sep>gng === [![Build Status](https://travis-ci.org/rcannood/gng.svg?branch=master)](https://travis-ci.org/rcannood/gng) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/rcannood/gng?branch=master&svg=true)](https://ci.appveyor.com/project/rcannood/gng) [![CRAN\_Status\_Badge](https://www.r-pkg.org/badges/version/gng)](https://cran.r-project.org/package=gng) [![Coverage Status](https://codecov.io/gh/rcannood/gng/branch/master/graph/badge.svg)](https://codecov.io/gh/rcannood/gng?branch=master) An implementation of the Growing Neural Gas algorithm in Rcpp. Example ------- You can run gng as follows: library(gng) data(iris) gng_fit <- gng(as.matrix(iris[,1:4])) And visualise it as follows: plot_gng(gng_fit, iris[,5], max_size = 0.05, max_size_legend = .15) ![](man/figures/README_plot-1.png) <file_sep># Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: <PASSWORD> #' @useDynLib gng gng_cpp <- function(x, max_iterations, epsilon_b, epsilon_n, age_max, max_nodes, lambda, alpha, beta, verbose) { .Call('_gng_gng_cpp', PACKAGE = 'gng', x, max_iterations, epsilon_b, epsilon_n, age_max, max_nodes, lambda, alpha, beta, verbose) } <file_sep>#include <Rcpp.h> #include <boost/config.hpp> #include <iostream> #include <boost/graph/adjacency_list.hpp> #include <boost/lexical_cast.hpp> // [[Rcpp::depends(RcppProgress)]] #include <progress.hpp> #include <progress_bar.hpp> using namespace Rcpp; struct node_prop_t { int index; double error; double dist; NumericVector position; }; struct edge_prop_t { int age; }; typedef boost::adjacency_list < boost::listS, boost::vecS, boost::undirectedS, node_prop_t, edge_prop_t > Graph; typedef boost::graph_traits<Graph>::vertex_descriptor Vertex; typedef boost::graph_traits<Graph>::edge_descriptor Edge; typedef boost::graph_traits<Graph>::vertex_iterator Vertex_iter; typedef boost::graph_traits<Graph>::edge_iterator Edge_iter; typedef boost::graph_traits<Graph>::out_edge_iterator Edge_o_iter; typedef boost::graph_traits<Graph>::adjacency_iterator Adj_iter; //' @useDynLib gng // [[Rcpp::export]] List gng_cpp(NumericMatrix x, int max_iterations, float epsilon_b, float epsilon_n, int age_max, int max_nodes, int lambda, float alpha, float beta, bool verbose) { RNGScope rngScope; Progress p(max_iterations, verbose); std::pair<Edge_o_iter, Edge_o_iter> eop; std::pair<Edge_iter, Edge_iter> ep; std::pair<Vertex_iter, Vertex_iter> vp; std::pair<Adj_iter, Adj_iter> ap; Vertex s0, s1; std::pair<Edge, bool> e01; // Calculate ranges of the dimensionality of the dataset int num_features = x.ncol(); int num_samples = x.nrow(); NumericVector mins(num_features), maxs(num_features); for (int i = 0; i < num_features; i++) { mins(i) = min(x(_,i)); maxs(i) = max(x(_,i)); } // 0a. Initialise the graph with two nodes Graph graph(2); int next_r = 0; // 0b. The locations are uniformily sampled for (vp = vertices(graph); vp.first != vp.second; ++vp.first) { Vertex node = *vp.first; NumericVector pos(num_features); for (int j = 0; j < num_features; j++) { pos(j) = R::runif(mins(j), maxs(j)); } graph[node].position = pos; graph[node].index = next_r; graph[node].error = 0; next_r++; } // 0b. Add an edge between the two nodes vp = vertices(graph); s0 = *vp.first; vp.first++; s1 = *vp.first; e01 = edge(s0, s1, graph); if (!e01.second) { e01 = boost::add_edge(s0, s1, graph); } graph[e01.first].age = 0; // While stopping criterion not met. // In the future, this function might check whether nodes have converged int current_iter = 0; while (current_iter < max_iterations) { ++current_iter; p.increment(); // update progress if (current_iter % 10000 == 0 && Progress::check_abort() ) return NULL; // 1. generate input signal int i = floor(R::runif(0, num_samples)); NumericVector x_i = x(i, _); // 2a. calculate distances between each node and the input signal for (vp = vertices(graph); vp.first != vp.second; ++vp.first) { Vertex node = *vp.first; NumericVector n_i = graph[node].position; graph[node].dist = sqrt(sum(pow(x_i - n_i, 2.0))); } // find nearest node s0 and second nearest node s1 vp = vertices(graph); s0 = *vp.first; vp.first++; s1 = *vp.first; vp.first++; if (graph[s1].dist < graph[s0].dist) { Vertex swap = s1; s1 = s0; s0 = swap; } for (; vp.first != vp.second; ++vp.first) { Vertex node = *vp.first; if (graph[node].dist < graph[s0].dist) { s1 = s0; s0 = node; } else if (graph[node].dist < graph[s1].dist) { s1 = node; } } // 3. increment the age of all edges eminating from s0 for (eop = boost::out_edges(s0, graph); eop.first != eop.second; ++eop.first) { graph[*eop.first].age++; } // 4. add the distance between the input signal and the s0 to the error graph[s0].error += graph[s0].dist; // 5. move s0 and its direct topological neighbours toward input signal by // fractions epsilon_b and epsilon_n respectively graph[s0].position += epsilon_b * (x_i - graph[s0].position); for (ap = boost::adjacent_vertices(s0, graph); ap.first != ap.second; ++ap.first) { Vertex node = *ap.first; graph[node].position += epsilon_n * (x_i - graph[node].position); } // 6. if s0 and s1 are connected by an edge, set the age of this edge to zero. // otherwise, create a new edge of age 0 e01 = edge(s0, s1, graph); if (!e01.second) { e01 = boost::add_edge(s0, s1, graph); } graph[e01.first].age = 0; // 7. remove edges with an age larger than age_max. ep = edges(graph); for (Edge_iter enext = ep.first; ep.first != ep.second; ep.first = enext) { ++enext; Edge edge = *ep.first; if (graph[edge].age > age_max) { Vertex from = boost::source(edge, graph); Vertex to = boost::target(edge, graph); boost::remove_edge(edge, graph); if (boost::degree(from, graph) == 0) { boost::remove_vertex(from, graph); } if (boost::degree(to, graph) == 0) { boost::remove_vertex(to, graph); } } } // 8. insert a new node if (current_iter % lambda == 0 && boost::num_vertices(graph) < max_nodes) { // 8a. determine node p with maximum accumulated error vp = boost::vertices(graph); Vertex p = *vp.first; vp.first++; for (; vp.first != vp.second; ++vp.first) { Vertex node = *vp.first; if (graph[p].error < graph[node].error) { p = node; } } // 8b. determine node q neighbouring p with the largest error ap = adjacent_vertices(p, graph); Vertex q = *ap.first; ap.first++; for (; ap.first != ap.second; ++ap.first) { Vertex node = *ap.first; if (graph[q].error < graph[node].error) { q = node; } } // 8c. insert a new node r halfway between p and q Vertex r = boost::add_vertex(graph); graph[r].index = next_r; next_r++; graph[r].position = (graph[p].position + graph[q].position) / 2; graph[r].error = 0; // 8d. remove (p, q) and add (p, r) and (q, r) remove_edge(p, q, graph); e01 = add_edge(p, r, graph); graph[e01.first].age = 0; e01 = add_edge(q, r, graph); graph[e01.first].age = 0; // 8e. decrease error or p and q by factor alpha // and initialise error of r as the error of p graph[p].error *= alpha; graph[q].error *= alpha; graph[r].error = graph[p].error; } // 9. decrease all errors by factor beta for (vp = boost::vertices(graph); vp.first != vp.second; ++vp.first) { Vertex node = *vp.first; graph[node].error *= beta; } } // Create nodes output int num_nodes = boost::num_vertices(graph); CharacterVector nodedf_names(num_nodes); IntegerVector nodedf_index(num_nodes); NumericVector nodedf_error(num_nodes); NumericMatrix node_space (num_nodes, num_features); int nodedf_i = 0; for (vp = vertices(graph); vp.first != vp.second; ++vp.first) { Vertex node = *vp.first; int index = graph[node].index; nodedf_index(nodedf_i) = index; nodedf_names(nodedf_i) = "Node" + boost::lexical_cast<std::string>(index); nodedf_error(nodedf_i) = graph[node].error; node_space(nodedf_i, _) = graph[node].position; nodedf_i++; } // CharacterVector nodedf_names = CharacterVector("Comp") + nodedf_index; DataFrame nodes = DataFrame::create( Named("name") = nodedf_names, Named("index") = nodedf_index, Named("error") = nodedf_error); rownames(node_space) = nodedf_names; colnames(node_space) = colnames(x); // Create edges output int num_edges = boost::num_edges(graph); IntegerVector edgedf_from(num_edges), edgedf_to(num_edges); NumericVector edgedf_age(num_edges); int edgedf_i = 0; for (ep = edges(graph); ep.first != ep.second; ++ep.first) { Edge edge = *ep.first; edgedf_from(edgedf_i) = graph[boost::source(edge, graph)].index; edgedf_to(edgedf_i) = graph[boost::target(edge, graph)].index; edgedf_age(edgedf_i) = graph[edge].age; edgedf_i++; } DataFrame edges = DataFrame::create( Named("i") = edgedf_from, Named("j") = edgedf_to, Named("age") = edgedf_age); // also return clustering // Return everything return List::create( _["nodes"] = nodes, _["node_space"] = node_space, _["edges"] = edges ); } // x <- matrix(runif(200), ncol = 10) // Rcpp::sourceCpp('src/gng.cpp') // gng_cpp(x, max_iterations = 20000, epsilon_b = .05, epsilon_n = .001, age_max = 200, max_nodes = 30, lambda = 200, alpha = .5, beta = .99, verbose = T, weights = .1) <file_sep>#' Produce a FlowSOM-like plot #' #' @param gng_fit The GNG produced by the \code{\link{gng}} function #' @param plot_labels Labels for the training samples. Is NULL, by default. #' @param plot_expression Whether or not to plot the expression. #' @param max_size The maximum size of visualised nodes #' @param max_size_legend The maximum size of the legend nodes. #' #' @importFrom igraph graph_from_data_frame layout_with_kk #' @importFrom ggforce geom_circle geom_arc_bar #' @importFrom RColorBrewer brewer.pal #' @importFrom reshape2 melt #' @importFrom cowplot theme_cowplot #' @importFrom ggplot2 ggplot geom_segment scale_fill_identity coord_equal labs aes geom_text #' @importFrom utils head tail #' #' @export #' #' @examples #' data(iris) #' gng_out <- gng( #' x = as.matrix(iris[,1:4]), #' max_iter = 20000, #' epsilon_b = 0.05, #' epsilon_n = 0.001, #' age_max = 200, #' max_nodes = 30, #' lambda = 200, #' alpha = 0.5, #' beta = 0.99, #' assign_cluster = TRUE, #' verbose = TRUE, #' make_logs_at = NULL, #' cpp = TRUE #' ) #' plot_gng(gng_out, iris[,5], max_size = 0.05) #' plot_gng <- function( gng_fit, plot_labels = NULL, plot_expression = gng_fit$node_space, max_size = .05, max_size_legend = .15 ) { nodes <- gng_fit$nodes %>% mutate(name = as.character(name)) edges <- gng_fit$edges %>% mutate(i = as.character(i), j = as.character(j)) gr <- igraph::graph_from_data_frame(edges, directed = FALSE, vertices = nodes$name) # apply dimred to graph lay <- apply(igraph::layout_with_kk(gr), 2, function(x) (x - min(x)) / (max(x) - min(x))) colnames(lay) <- c("X", "Y") rownames(lay) <- nodes$name lay_df <- data.frame(nodes, lay, r = max_size, stringsAsFactors = FALSE, row.names = NULL) # combine edges with dimred gr_df_with_pos <- data.frame( edges, i = lay[edges$i, , drop = F], j = lay[edges$j, , drop = F], row.names = NULL ) # make a colour scheme annotation_colours <- list() arc_df <- NULL do_plot_expression <- !is.null(plot_expression) && !(is.logical(plot_expression) && !plot_expression) do_plot_labels <- !is.null(plot_labels) && !(is.logical(plot_labels) && !plot_labels) # If the user wants to plot the expression if (do_plot_expression) { annotation_colours$expr <- set_names(RColorBrewer::brewer.pal(ncol(plot_expression), "Dark2"), colnames(plot_expression)) # scale expression between 0 and 1 plot_expression_sc <- apply(plot_expression, 2, function(x) (x - min(x)) / (max(x) - min(x))) plot_expression_df <- plot_expression_sc %>% reshape2::melt(varnames = c("name", "gene"), value.name = "expr") %>% mutate(name = as.character(name)) %>% left_join(lay_df %>% mutate(name = as.character(name)), by = "name") %>% group_by(name, gene) %>% mutate( gene_index = match(gene, colnames(plot_expression)), start = (gene_index - 1) / ncol(plot_expression) * 2 * pi, end = gene_index / ncol(plot_expression) * 2 * pi ) %>% ungroup() %>% mutate(colour = annotation_colours$expr[gene]) arc_df <- plot_expression_df %>% mutate( r0 = ifelse(is.null(do_plot_labels), 0, 0.5 * max_size), r = { if (is.null(do_plot_labels)) expr else .5 + expr / 2 } * max_size, plot_label = FALSE ) %>% select(node = name, X, Y, start, end, r0, r, colour, plot_label) %>% bind_rows(arc_df, .) # create legend plot num <- length(annotation_colours$expr) rads <- seq(0, 2 * pi, length.out = num + 1) leg_df <- data_frame( node = names(annotation_colours$expr), X = 1.4, Y = ifelse(is.null(do_plot_labels), .5, 0.75), start = rads %>% head(-1), end = rads %>% tail(-1), r0 = ifelse (is.null(do_plot_labels), 0, 0.5 * max_size_legend), r = { if (is.null(do_plot_labels)) seq(.5, 1, length.out = num) else seq(.75, 1, length.out = num) } * max_size_legend, colour = annotation_colours$expr, plot_label = TRUE ) arc_df <- bind_rows(arc_df, leg_df) lay_df <- lay_df %>% add_row(name = "Expression", X = 1.4, Y = ifelse(is.null(do_plot_labels), .5, 0.75), r = max_size_legend) } # if labels are provided if (!is.null(plot_labels)) { clustering <- gng_fit$clustering # check how many of each label are in each node categories <- if (is.factor(plot_labels)) levels(plot_labels) else sort(unique(plot_labels)) category_counts <- crossing(category = categories, cluster = seq_len(nrow(nodes))) %>% rowwise() %>% mutate(number = sum(categories == category, clustering == cluster)) %>% ungroup() annotation_colours$count <- set_names(RColorBrewer::brewer.pal(length(categories), "Set1"), categories) # generate pie df with positioning pie_df <- data_frame(label = as.character(plot_labels), name = as.character(clustering)) %>% group_by(name, label) %>% summarise(n = n()) %>% mutate( value = n / sum(n) * 2 * pi, end = cumsum(value), start = end - value ) %>% ungroup() %>% left_join(lay_df %>% select(-r), by = "name") %>% mutate(colour = annotation_colours$count[label]) # add to arc df arc_df <- pie_df %>% mutate(r0 = 0, r = ifelse(do_plot_expression, .5 * max_size, max_size), plot_label = FALSE) %>% select(node = name, X, Y, start, end, r0, r, colour, plot_label) %>% bind_rows(arc_df) # create legend plot num <- length(annotation_colours$count) rads <- seq(0, 2 * pi, length.out = num + 1) leg_df <- data_frame( node = names(annotation_colours$count), X = 1.4, Y = ifelse(is.null(do_plot_expression), .5, 0.25), start = rads %>% head(-1), end = rads %>% tail(-1), r0 = 0, r = ifelse(is.null(do_plot_expression), 1, .5) * max_size_legend, colour = annotation_colours$count, plot_label = TRUE ) arc_df <- bind_rows(arc_df, leg_df) lay_df <- lay_df %>% add_row(name = "Expression", X = 1.4, Y = ifelse(is.null(do_plot_labels), .5, 0.25), r = max_size_legend) } # Make a line plot label_df <- arc_df %>% filter(plot_label) %>% mutate( rad = (start + end) / 2, xpos = X + max_size_legend * 1.2 * sin(rad), ypos = Y + max_size_legend * 1.2 * cos(rad) ) ggplot() + geom_segment(aes(x = i.X, xend = j.X, y = i.Y, yend = j.Y), gr_df_with_pos) + ggforce::geom_circle(aes(x0 = X, y0 = Y, r = r), fill = "white", lay_df) + ggforce::geom_arc_bar(aes(x0 = X, y0 = Y, r0 = r0, r = r, start = start, end = end, fill = colour), data = arc_df %>% filter(!(start == 0 & end == 2 * pi))) + ggforce::geom_circle(aes(x0 = X, y0 = Y, r = r, fill = colour), data = arc_df %>% filter((start == 0 & end == 2 * pi))) + geom_text(aes(xpos, ypos, label = node), label_df) + scale_fill_identity() + cowplot::theme_nothing() + coord_equal() + labs(x = NULL, y = NULL) } <file_sep>#' Growing Neural Gas #' #' @references Fritzke, Bernd. "A growing neural gas network learns topologies." Advances in neural information processing systems 7 (1995): 625-632. #' #' @param x The input data. Must be a matrix! #' @param max_iter The max number of iterations. #' @param epsilon_b Move the winning node by epsilon_b times the distance. #' @param epsilon_n Move the neighbours of the winning node by epsilon_n times the distance. #' @param age_max Remove edges older than age_max. #' @param max_nodes The maximum number of nodes. #' @param lambda Insert new nodes every lambda iterations. #' @param alpha The decay parameter for error when a node is added. #' @param beta The decay parameter for error in every node every iteration. #' @param assign_cluster Whether or not to assign each sample to a GNG node. #' @param verbose Will output progress if \code{TRUE}. #' @param cpp Whether or not to use the C++ implementation over the R implementation. The C++ implementation is a lot faster. #' @param make_logs_at At which iterations to store the GNG, for visualisation purposes. #' #' @export gng <- function( x, max_iter = 20000, epsilon_b = .05, epsilon_n = .001, age_max = 200, max_nodes = 30, lambda = 200, alpha = .5, beta = .99, assign_cluster = TRUE, verbose = TRUE, cpp = TRUE, make_logs_at = NULL ) { if (cpp) { if (!is.null(make_logs_at)) stop("make_logs_at is only supported using the R implementaton of GNG") o <- gng_cpp( x = x, max_iterations = max_iter, epsilon_b = epsilon_b, epsilon_n = epsilon_n, age_max = age_max, max_nodes = max_nodes, lambda = lambda, alpha = alpha, beta = beta, verbose = verbose ) o$nodes$name <- as.character(o$nodes$name) o$edges$i <- o$nodes$name[match(o$edges$i, o$nodes$index)] o$edges$j <- o$nodes$name[match(o$edges$j, o$nodes$index)] } else { o <- gng_r( x = x, max_iter = max_iter, epsilon_b = epsilon_b, epsilon_n = epsilon_n, age_max = age_max, max_nodes = max_nodes, lambda = lambda, alpha = alpha, beta = beta, verbose = verbose, make_logs_at = make_logs_at ) } # Determine assignment of the samples to the nodes if (assign_cluster) { o$clustering <- o$nodes$name[apply(x, 1, function(xi) which.min(apply(o$node_space, 1, function(si) mean((xi-si)^2))))] } o } #' @importFrom stats runif gng_r <- function(x, max_iter, epsilon_b, epsilon_n, age_max, max_nodes, lambda, alpha, beta, verbose, make_logs_at) { # Calculate ranges of the dimensionality of the dataset ranges <- apply(x, 2, range) # Initialise a node position matrix S <- matrix(NA, nrow = max_nodes, ncol = ncol(x), dimnames = list(NULL, colnames(x))) # A dataframe containing the error of each node S_meta <- data.frame(i = seq_len(nrow(S)), error = rep(0, nrow(S))) # A list containing the neighbours of each node E <- lapply(seq_len(max_nodes), function(i) numeric(0)) E[[1]] <- 2 E[[2]] <- 1 # A matrix containing the ages of each edge Age <- matrix(NA, nrow = max_nodes, ncol = max_nodes) # 0. start with two units a and b at random positions in R^n S[1:2,] <- apply(ranges, 2, function(r) { stats::runif(2, r[[1]], r[[2]]) }) Age[1,2] <- 0 Age[2,1] <- 0 # This variable is the index of a new node nextr <- 3 # I separated out the distance and move functions in case I want to try a different approach distance_function <- function(xi, Si) { diff <- xi - Si sqrt(mean(diff * diff)) } move_function <- function(xi, Si, epsilon) { Si + epsilon * (xi - Si) } sample_input_signal <- function() { x[sample.int(nrow(x), 1),] } current.iter <- 0L # create data structures for saving the intermediary gngs log <- list() if (current.iter %in% make_logs_at) { current_log <- list(current.iter = current.iter, S = S, S_meta = S_meta, Age = Age, E = E) log[[length(log) + 1]] <- current_log } # while stopping criterion not met. # In the future, this function might check whether nodes have somewhat converged to a steady position. while (current.iter <= max_iter) { current.iter <- current.iter + 1L if (verbose && current.iter %% 1000L == 0L) cat("Iteration ", current.iter, "\n", sep = "") # 1. generate input signal xi <- sample_input_signal() # 2. find nearest unit s1 and second nearest unit s2 sdist <- apply(S, 1, function(Si) distance_function(xi, Si)) sord <- order(sdist) s1 <- sord[[1]] s2 <- sord[[2]] # 3. increment the age of all edges eminating from s1 Age[s1,] <- Age[s1,] + 1 Age[,s1] <- Age[,s1] + 1 # 4. add the squared distance between input signal and the nearest unit to the error variable S_meta$error[[s1]] <- S_meta$error[[s1]] + sdist[[s1]] # 5. move s1 and its direct topological neighbours towards input signal by fractions epsilon_b and epsilon_n respectively S[s1, ] <- move_function(xi, S[s1,], epsilon_b) neighs <- E[[s1]] for (n1 in neighs) { S[n1,] <- move_function(xi, S[n1,], epsilon_n) } # 6. if s1 and s2 are connected by an edge, set the age of this edge to zero. otherwise, create edge of age 0 if (is.na(Age[[s1, s2]])) { E[[s1]] <- c(E[[s1]], s2) E[[s2]] <- c(E[[s2]], s1) } Age[[s1, s2]] <- 0 Age[[s2, s1]] <- 0 edge.nods <- unique(neighs, s2) # 7. remove edges with an age larger than age_max. if a point has no remaining edge, remove as well rem <- which(Age[s1,] > age_max) if (length(rem) > 0) { Age[s1, rem] <- NA Age[rem, s1] <- NA E[[s1]] <- setdiff(E[[s1]], rem) for (sj in rem) { E[[sj]] <- setdiff(E[[sj]], s1) } # edge_loglist[[length(edge_loglist)+1]] <- data.frame(added = F, i = s1, j = rem, iteration = current.iter, reason = "age") s1rem <- c(s1, rem) removed.nodes <- s1rem[which(sapply(s1rem, function(i) length(E[s1rem]) == 0))] } # 8. If the number of input signals generated so far is an integer multiple of a parameter lambda, insert a new node if (current.iter %% lambda == 0) { if (nextr <= max_nodes) { r <- nextr nextr <- nextr + 1 # 8a. determine node p with the maximum accumulated error p <- which.max(S_meta$error) # 8b. determine node q neighbouring p with the largest error np <- E[[p]] q <- np[which.max(S_meta$error[np])] # 8c. insert new node r halfway between p and q S[r,] <- (S[p,] + S[q,]) / 2 # 8d. remove (p, q), add (p, r) and (q, r) Age[p, q] <- NA Age[q, p] <- NA E[[p]] <- c(setdiff(E[[p]], q), r) E[[q]] <- c(setdiff(E[[q]], p), r) E[[r]] <- c(p, q) Age[p, r] <- 0 Age[r, p] <- 0 Age[q, r] <- 0 Age[r, q] <- 0 # 8e. decrease error of p and q by factor alpha and initialise error of r as the error of p Ep <- S_meta$error[[p]] Eq <- S_meta$error[[q]] S_meta$error[c(p, q, r)] <- c(alpha * Ep, alpha * Eq, alpha * Ep) } } # 9. decrease all variables by multiplying them with a constant beta S_meta$error <- S_meta$error * beta # store intermediary gng if so desired if (current.iter %in% make_logs_at) { current_log <- list(current.iter = current.iter, S = S, S_meta = S_meta, Age = Age, E = E) log[[length(log) + 1]] <- current_log } } # Construct GNG output data structures nodes <- data.frame(node = seq_len(nrow(S)), S_meta[,2,drop=F]) node_space <- S filt <- !is.na(node_space[,1]) nodes <- nodes[filt,,drop=F] node_space <- node_space[filt,,drop=F] edges <- bind_rows(lapply(seq(2, nrow(S)), function(nj) { ni <- E[[nj]] ni <- ni[ni < nj] if (length(ni) > 0) { data.frame(i = ni, j = nj) } else { NULL } })) list( nodes = nodes, node_space = node_space, edges = edges, log = log ) } #' Perform FR dimensionality reduction on GNG and project cells to same space #' #' @param gng_out The object generated by \code{\link{gng}} #' @param x If desired, the original dimred can also be projected using a randomForest #' #' @importFrom stats predict na.omit #' @importFrom randomForestSRC rfsrc #' @importFrom igraph graph_from_data_frame layout_with_fr #' #' @export gng_project <- function(gng_out, x = NULL) { # Project the nodes to a 2D plane igr <- gng_out$edges %>% select(i, j) %>% igraph::graph_from_data_frame( vertices = gng_out$nodes$name, directed = FALSE ) node_proj <- igraph::layout_with_fr(igr) colnames(node_proj) <- c("GNG_X", "GNG_Y") rownames(node_proj) <- gng_out$nodes$name # Apply minmax-scale mins <- apply(node_proj, 2, min, na.rm = TRUE) maxs <- apply(node_proj, 2, max, na.rm = TRUE) scale <- maxs - mins scale[scale == 0] <- 1 node_proj <- t(apply(node_proj, 1, function(x) (x - mins) / scale)) # Map the positions to the original space x if (!is.null(x)) { rf <- randomForestSRC::rfsrc(Multivar(GNG_X, GNG_Y) ~ ., data.frame(stats::na.omit(gng_out$node_space), node_proj, check.names = FALSE)) pred <- stats::predict(rf, data.frame(x, check.names = FALSE, stringsAsFactors = FALSE)) space_proj <- sapply(colnames(node_proj), function(n) pred$regrOutput[[n]]$predicted) rownames(space_proj) <- rownames(x) } else { space_proj <- NULL } list( node_proj = node_proj, space_proj = space_proj, igraph = igr ) }
d6ab28b7f647660ce670cab88116a3e0687b9464
[ "Markdown", "R", "C++", "RMarkdown" ]
8
C++
rcannood/gng
a6136a4bec30f4b408038ba4ba6cd1eb4b6b8a88
c4728750c1dde0dc0567676f0e4e5cefac5a530a
refs/heads/master
<file_sep>#include <QApplication> #include <QIcon> #include <iostream> #include "widget.h" #include "board.h" #include "board.h" #include "agent.h" #include "humanplayer.h" #include "game.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Player *player1 = new HumanPlayer(1); Player *player2 = new HumanPlayer(2); Player *player3 = new Agent(1); Player *player4 = new Agent(2); GameState *state = new GameState(9, player1->getPlayerNumber()); Board *board = new Board(state); Game *game = new Game(player1, player2, player3, player4, board, state); Widget *window; window = new Widget(board, game); board->setParent(window); window->setWindowTitle("Tic Tac Toe"); window->show(); game->nextRound(); return a.exec(); } <file_sep>#include "gamestate.h" void GameState::deepCopy(GameState *copy) { for (int i = 0; i < boardSize; i++) { copy->getBoard()[i] = board[i]; } } GameState::GameState(int n, int player) { player1 = 1; player2 = 2; currentPlayer = player; boardSize = n; board = new int[boardSize]; for (int i = 0; i < boardSize; i++) { board[i] = 0; } } GameState::~GameState() { delete board; } void GameState::printBoard() { int a = sqrt(boardSize); for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { if (board[a*i+j] == 0) { std::cout << " "; } else if (board[a*i+j] == 1) { std::cout << "x "; } else if (board[a*i+j] == 2) { std::cout << "o "; } } std:: cout << "\n"; } } int GameState::otherPlayer(int currentPlayer) { if (currentPlayer == player1) { return player2; } else if (currentPlayer == player2) { return player1; } } void GameState::changePlayer() { if (currentPlayer == player1) { currentPlayer = player2; } else if (currentPlayer == player2) { currentPlayer = player1; } } void GameState::makeMove(int &move) { board[move] = currentPlayer; changePlayer(); } int GameState::getBoardSize() { return boardSize; } int* GameState::getBoard() { return board; } int GameState::getCurrentPlayer() { return currentPlayer; } void GameState::initiate() { for (int i = 0; i < boardSize; i++) { board[i] = 0; } currentPlayer = player1; } <file_sep>#ifndef AGENT_H #define AGENT_H #include "gamestate.h" #include "gamelogic.h" #include "player.h" struct possibleMove{ int move; int score; int depth; }; class Agent: public Player{ private: GameLogic *logic; int playerNumber; bool human; public: Agent(int); ~Agent(); bool isHuman(); int getPlayerNumber(); void generateNextMove(int&, GameState*); possibleMove possibleMovesMinimum(possibleMove*, int); possibleMove possibleMovesMaximum(possibleMove*, int); int minimax(GameState*); int minValue(GameState*, int); int maxValue(GameState*, int); void printPossibleMoves(possibleMove*, int); }; #endif // AGENT_H <file_sep>#ifndef GAME_H #define GAME_H #include "player.h" #include "gamelogic.h" #include "board.h" #include "board.h" #include <QWidget> #include <QApplication> #include <QTimer> #include <QTime> class Game : public QWidget { Q_OBJECT private: Player *player1; Player *player2; Player *player3; Player *player4; Player *currentPlayer; Player *currentPlayer1; Player *currentPlayer2; Player *nextPlayer1; Player *nextPlayer2; Board *board; GameLogic *logic; GameState *state; void setNextMove(int&); public: Game(Player*, Player*, Player*, Player*, Board*, GameState*, QWidget *parent = 0); QTimer *timer; int nextMove; void changePlayers(); void delay(int); public slots: void nextRound(); void restart(); void changeNextPlayer1(QString); void changeNextPlayer2(QString); }; #endif // GAME_H <file_sep># Tic Tac Toe This is a free Tic Tac Toe Game written in C++ and Qt. The computer agent uses the Minimax algorithm to determine its next move. Due to the search space size, the computer agent plays perfect and can not loose a game. ![screenshot](./tictactoe_example.png) The project was developed in Qt-Creator 3.5.1. ## Game features - HumanPlayer vs. HumanPlayer - HumanPlayer vs. Computer ## Computer Agent - uses a MiniMax algorithm to decide for the next move. - can play as first or second player. <file_sep>#include "agent.h" Agent::Agent(int p) { logic = new GameLogic(); playerNumber = p; human = false; } Agent::~Agent() { delete logic; } bool Agent::isHuman() { return human; } int Agent::getPlayerNumber() { return playerNumber; } void Agent::generateNextMove(int& move, GameState *state) { move = minimax(state); } possibleMove Agent::possibleMovesMaximum(possibleMove *arr, int size) { possibleMove result; if (size >= 1) { result = arr[0]; } for (int i = 1; i < size; i++) { if (arr[i].score > result.score) { result = arr[i]; } } return result; } possibleMove Agent::possibleMovesMinimum(possibleMove *arr, int size) { possibleMove result; if (size >= 1) { result = arr[0]; } for (int i = 1; i < size; i++) { if (arr[i].score < result.score) { result = arr[i]; } } return result; } void Agent::printPossibleMoves(possibleMove *arr, int size) { std::cout << "possibleMoves: " << std::endl; for (int i = 0; i < size; i++) { std::cout << i << ": " << arr[i].move << ", " << arr[i].score << ", " << arr[i].depth << std::endl; } } int Agent::maxValue(GameState *state, int depth) { int newDepth = depth + 1; if (logic->gameWon(state)) { return -1; } if (logic->gameOver(state)) { return 0; } int vmSize = logic->numOfValidMoves(state); int validMoves[state->getBoardSize()]; logic->generateValidMoves(state, validMoves); possibleMove *moves; moves = new possibleMove[vmSize]; for (int i = 0; i < vmSize; i++) { GameState *nState; int boardSize = state->getBoardSize(); int currentPlayer = state->getCurrentPlayer(); nState = new GameState(boardSize, currentPlayer); state->deepCopy(nState); nState->makeMove(validMoves[i]); moves[i].move = validMoves[i]; moves[i].score = minValue(nState, newDepth); moves[i].depth = depth; } return possibleMovesMaximum(moves, vmSize).score; } int Agent::minValue(GameState *state, int depth) { int newDepth = depth + 1; if (logic->gameWon(state)) { return 1; } if (logic->gameOver(state)) { return 0; } int vmSize = logic->numOfValidMoves(state); int validMoves[state->getBoardSize()]; logic->generateValidMoves(state, validMoves); possibleMove *moves; moves = new possibleMove[vmSize]; for (int i = 0; i < vmSize; i++) { GameState *nState; int boardSize = state->getBoardSize(); int currentPlayer = state->getCurrentPlayer(); nState = new GameState(boardSize, currentPlayer); state->deepCopy(nState); nState->makeMove(validMoves[i]); moves[i].move = validMoves[i]; moves[i].score = maxValue(nState, newDepth); moves[i].depth = depth; } // printPossibleMoves(moves, vmSize); return possibleMovesMinimum(moves, vmSize).score; } int Agent::minimax(GameState *state) { int depth = 0; int vmSize = logic->numOfValidMoves(state); int validMoves[state->getBoardSize()]; logic->generateValidMoves(state, validMoves); possibleMove *moves; moves = new possibleMove[vmSize]; for (int i = 0; i < vmSize; i++) { GameState *nState; int boardSize = state->getBoardSize(); int currentPlayer = state->getCurrentPlayer(); nState = new GameState(boardSize, currentPlayer); state->deepCopy(nState); nState->makeMove(validMoves[i]); moves[i].move = validMoves[i]; moves[i].score = minValue(nState, depth); moves[i].depth = depth; } printPossibleMoves(moves, vmSize); return possibleMovesMaximum(moves, vmSize).move; } <file_sep>#ifndef GAMESTATE_H #define GAMESTATE_H #include <iostream> #include <cmath> class GameState { private: int boardSize; int *board; int player1; int player2; int currentPlayer; public: GameState(int, int); ~GameState(); void printBoard(); void makeMove(int&); void changePlayer(); int otherPlayer(int); void deepCopy(GameState*); void initiate(); int getBoardSize(); int* getBoard(); int getCurrentPlayer(); }; #endif // GAMESTATE_H <file_sep>#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QComboBox> #include <QLabel> #include "board.h" #include "board.h" #include "game.h" class Widget : public QWidget { Q_OBJECT public: // explicit MyWidget(QWidget *parent = 0); Widget(Board *board, Game *game, QWidget *parent = 0); ~Widget(); signals: public slots: private slots: private: QComboBox *combo1, *combo2; QLabel *statusLabel; }; #endif // WIDGET_H <file_sep>#include "widget.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QTextEdit> #include <QLabel> #include <QPushButton> #include <QApplication> #include <QStringList> #include "board.h" #include "board.h" #include "gamestate.h" #include "agent.h" #include "humanplayer.h" Widget::Widget(Board *board, Game *game, QWidget *parent) : QWidget(parent) { QHBoxLayout *hbox = new QHBoxLayout(this); QVBoxLayout *vbox = new QVBoxLayout(); QVBoxLayout *players = new QVBoxLayout(); QHBoxLayout *buttons = new QHBoxLayout(); statusLabel = new QLabel("Have Fun", this); QPushButton *quit = new QPushButton("Quit", this); QPushButton *restart = new QPushButton("Restart", this); connect(quit, &QPushButton::clicked, qApp, &QApplication::quit); connect(restart, &QPushButton::clicked, game, &Game::restart); QStringList *pselection; pselection = new QStringList(); pselection->append(""); pselection->append("Human"); pselection->append("Computer"); combo1 = new QComboBox(); combo1->addItems(*pselection); combo2 = new QComboBox(); combo2->addItems(*pselection); connect(combo1, static_cast<void(QComboBox::*)(const QString &)>(&QComboBox::activated), game, &Game::changeNextPlayer1); connect(combo2, static_cast<void(QComboBox::*)(const QString &)>(&QComboBox::activated), game, &Game::changeNextPlayer2); vbox->addWidget(board); vbox->addWidget(statusLabel, 1, Qt::AlignTop); buttons->addWidget(restart); buttons->addWidget(quit); vbox->addLayout(buttons); hbox->addLayout(vbox); players->addWidget(combo1, 0); players->addWidget(combo2, 1, Qt::AlignTop); hbox->addLayout(players); setLayout(hbox); } Widget::~Widget() { } <file_sep>#ifndef HUMANPLAYER_H #define HUMANPLAYER_H #include "player.h" class HumanPlayer: public Player { public: HumanPlayer(int); void generateNextMove(int&, GameState*); bool isHuman(); int getPlayerNumber(); private: int playerNumber; bool human; }; #endif // HUMANPLAYER_H <file_sep>#include "board.h" #include <cmath> #include <iostream> #include <QMouseEvent> Board::Board(GameState *state, QWidget *parent) : QWidget(parent) { tileSize = 100; setMaximumSize(3*tileSize, 3*tileSize); setMinimumSize(3*tileSize, 3*tileSize); setToolTip("Board"); this->state = state; clicked = -1; allowed = false; } Board::~Board() { } void Board::paintEvent(QPaintEvent *e) { Q_UNUSED(e); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(QPen(QBrush("#000000"), 4)); int a = sqrt(state->getBoardSize()); for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { switch(state->getBoard()[i*a+j]) { case 0: painter.setBrush(QBrush("#ffffff")); painter.drawRect(j*tileSize, i*tileSize, j*tileSize+tileSize, i*tileSize+tileSize); break; case 1: painter.setBrush(QBrush("#ffffff")); painter.drawRect(j*tileSize, i*tileSize, j*tileSize+tileSize, i*tileSize+tileSize); painter.setBrush(QBrush("#000000")); painter.drawLine(j*tileSize+10, i*tileSize+10, j*tileSize+tileSize-10, i*tileSize+tileSize-10); painter.drawLine(j*tileSize+10, i*tileSize+tileSize-10, j*tileSize+tileSize-10, i*tileSize+10); break; case 2: painter.setBrush(QBrush("#ffffff")); painter.drawRect(j*tileSize, i*tileSize, j*tileSize+tileSize, i*tileSize+tileSize); painter.setBrush(QBrush("#000000")); painter.drawEllipse(j*tileSize+10, i*tileSize+10, 80, 80); painter.setBrush(QBrush("#ffffff")); painter.drawEllipse(j*tileSize+12, i*tileSize+12, 76, 76); break; } } } } void Board::mousePressEvent(QMouseEvent *e) { std::cout << state->getCurrentPlayer() << std::endl; if (allowed){ std::cout << "mousePressEvent" << std::endl; // Get clicked tile int x, y; x = e->pos().rx() / 100; y = e->pos().ry() / 100; clicked = y*3 + x; } } void Board::getClicked(int& val) { val = this->clicked; } void Board::setAllowed(bool value) { this->allowed = value; } <file_sep>#include "gamelogic.h" GameLogic::GameLogic() { } void GameLogic::generateValidMoves(GameState *state, int *validMoves) { int validMovesCounter = 0; for (int i = 0; i < state->getBoardSize(); i++) { if (state->getBoard()[i] == 0) { validMoves[validMovesCounter] = i; validMovesCounter++; } } } int GameLogic::numOfValidMoves(GameState *state) { int result = 0; for (int i = 0; i < state->getBoardSize(); i++) { if (state->getBoard()[i] == 0) { result++; } } return result; } bool GameLogic::validMove(int &move, int *validMoves, int &size, GameState *state) { bool available = false; for (int i = 0; i < size; i++) { if (move == validMoves[i]) { available = true; } } return available & (0 <= move && move < state->getBoardSize()); } bool GameLogic::gameOver(GameState *state) { bool gameOver = true; for (int i = 0; i < state->getBoardSize(); i++) { gameOver = gameOver & (state->getBoard()[i] != 0); } return gameOver; } bool GameLogic::gameWon(GameState *state) { int a = sqrt(state->getBoardSize()); int *board = state->getBoard(); for (int i = 0; i < a; i++) { bool row = true; bool col = true; bool diagonal1 = true; bool diagonal2 = true; for (int j = 0; j < a; j++) { row = row & (board[a*i+j] == state->otherPlayer(state->getCurrentPlayer())); } for (int j = 0; j < a; j++) { col = col & (board[a*j+i] == state->otherPlayer(state->getCurrentPlayer())); } for (int j = 0; j < a; j++) { diagonal1 = diagonal1 & (board[j*a+j] == state->otherPlayer(state->getCurrentPlayer())); } for (int j = 1; j <= a; j++) { diagonal2 = diagonal2 & (board[j*a-j] == state->otherPlayer(state->getCurrentPlayer())); } if (row || col || diagonal1 || diagonal2) return true; } return false; } <file_sep>#include "game.h" Game::Game(Player *player1, Player *player2, Player *player3, Player *player4, Board *board, GameState *state, QWidget *parent) : QWidget(parent) { this->player1 = player1; this->player2 = player2; this->player3 = player3; this->player4 = player4; this->currentPlayer1 = player1; this->currentPlayer2 = player3; this->nextPlayer1 = player1; this->nextPlayer2 = player3; this->currentPlayer = currentPlayer1; this->board = board; this->state = state; logic = new GameLogic(); nextMove = -1; timer = new QTimer(); connect(timer, &QTimer::timeout, this, &Game::nextRound); } void Game::changeNextPlayer1(QString s) { std::cout << "changePlayer1" << std::endl; if (s == "Human") { std::cout << "it's player1 now" << std::endl; this->nextPlayer1 = player1; } else if (s == "Computer") { std::cout << "it's player3 now" << std::endl; this->nextPlayer1 = player3; } } void Game::changeNextPlayer2(QString s) { std::cout << "changePlayer2" << std::endl; if (s == "Human") { this->nextPlayer2 = player2; } else if (s == "Computer") { this->nextPlayer2 = player4; } } void Game::changePlayers() { if (currentPlayer == currentPlayer1) { std::cout << "this worked" << std::endl; currentPlayer = currentPlayer2; } else if (currentPlayer == currentPlayer2) { currentPlayer = currentPlayer1; } } void Game::restart() { this->currentPlayer1 = this->nextPlayer1; this->currentPlayer2 = this->nextPlayer2; this->currentPlayer = this->currentPlayer1; state->initiate(); board->clicked = -1; board->update(); nextRound(); } void Game::nextRound() { delay(100); if (!(logic->gameOver(state) || logic->gameWon(state))) { if (currentPlayer->isHuman()) { board->setAllowed(true); board->getClicked(nextMove); if (nextMove != -1) { setNextMove(nextMove); } else { timer->start(100); } } else if (!currentPlayer->isHuman()) { currentPlayer->generateNextMove(nextMove, state); setNextMove(nextMove); } } else { timer->stop(); if (logic->gameWon(state)) { std::cout << "The game has ended, and Player " << state->otherPlayer(state->getCurrentPlayer()) << " has won!" << std::endl; } else { std::cout << "No more moves are possible." << std::endl; } } } void Game::setNextMove(int &move) { nextMove = move; int vmSize = logic->numOfValidMoves(state); int validMoves[vmSize]; logic->generateValidMoves(state, validMoves); // is changed by the function. if (logic->validMove(nextMove, validMoves, vmSize, state)) { board->setAllowed(false); state->makeMove(nextMove); state->printBoard(); board->update(); changePlayers(); nextRound(); } else { //std::cout << "Invalid move" << std::endl; } nextMove = -1; } void Game::delay(int ms) { QTime dieTime= QTime::currentTime().addMSecs(ms); while (QTime::currentTime() < dieTime) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } <file_sep>#ifndef PLAYER #define PLAYER #include <iostream> #include "gamestate.h" class Player { public: virtual void generateNextMove(int&, GameState*) = 0; virtual bool isHuman() = 0; virtual int getPlayerNumber() = 0; }; #endif // PLAYER <file_sep>#include "humanplayer.h" HumanPlayer::HumanPlayer(int n) { playerNumber = n; human = true; } void HumanPlayer::generateNextMove(int& move, GameState*) { std::cin >> move; } bool HumanPlayer::isHuman() { return human; } int HumanPlayer::getPlayerNumber() { return playerNumber; } <file_sep>#ifndef GAMELOGIC_H #define GAMELOGIC_H #include "gamestate.h" class GameLogic { public: GameLogic(); void generateValidMoves(GameState*, int*); bool validMove(int&, int*, int&, GameState*); bool gameWon(GameState*); int numOfValidMoves(GameState*); bool gameOver(GameState*); }; #endif // GAMELOGIC_H <file_sep>#ifndef BOARD_H #define BOARD_H #include <QWidget> #include <QCursor> #include <QLabel> #include <QPainter> #include "gamestate.h" #include "gamelogic.h" #include "player.h" class Board : public QWidget { Q_OBJECT public: Board(GameState *state, QWidget *parent = 0); ~Board(); signals: public slots: void setAllowed(bool); void getClicked(int&); protected: void paintEvent(QPaintEvent *e); void mousePressEvent(QMouseEvent *e); private: GameState *state; QLabel *statusLabel; int tileSize; public: bool allowed; int clicked; }; #endif // BOARD_H
72f91b6159916507950e1df336c4e75c1faad676
[ "Markdown", "C++" ]
17
C++
paraficial/tictactoe
1a763e28070b723f26b385ec9d57a7febfa67784
51cf719c74665b546a46735841ba576b5ff6f920
refs/heads/master
<file_sep>import React from 'react'; import Burger from './Burger'; const Nav = styled.nav` // css goes here `; const Navbar = () => { return ( <Nav> <div className="logo"> Nav Bar </div> <Burger /> </Nav> ) } export default Navbar
7be445250f608a1594b343b588499da880dfa1d5
[ "JavaScript" ]
1
JavaScript
edbbarros/front-inspeauto-app
fcba6c9fa812a866ae55887fb5ed5294ddd48e41
389a1727b830b1f18d38ed36a0197a83bd0b56ce
refs/heads/master
<repo_name>wenqieqiu/vue-template<file_sep>/vue-custom-webpack-single-spa/src/views/system/store/menu.ts /** * Created by huhaichao on 2018-11-16. */ let menu = { namespaced: true, state: { table_columns: [ { text: '编码', value: 'code' }, { text: '菜单名称', value: 'menuTitle' }, { text: '菜单路径', value: 'menuPath' }, { text: '图标', value: 'menuIcon' }, { text: '备注', value: 'remark' }, { text: '序号', value: 'menuSort' } ], table_data: [], menu_detail_model: {}, menu_detail_dialog: false, menu_detail_operator: null, search_text: null }, mutations: { /** * 给菜单列表设置数据 * @param state * @param payload * @constructor */ SET_TABLE_DATA(state, payload) { // console.log(payload) state.table_data = payload != null && payload != '' ? payload : [] }, /** * 根据ID查询菜单明细 * @param state * @param payload * @constructor */ SET_MENU_DETAIL_MODEL(state, payload) { state.menu_detail_model = payload }, /** * 控制菜单明细弹出框显示与隐藏 * @param state * @param payload * @constructor */ SET_MENU_DETAIL_DIALOG(state, payload) { state.menu_detail_dialog = payload }, /** * 设置操作类型:新增菜单(new)、修改菜单(edit) * @param state * @param payload * @constructor */ SET_MENU_DETAIL_OPERATOR(state, payload) { state.menu_detail_operator = payload } } } export default menu <file_sep>/vue-custom-webpack-template(ts)/src/types/index.d.ts declare namespace Vuex { //================================================= interface Permission { authName: string manage: Auth edit: Auth children?: Child[] } interface Child { authName: string manage: Auth edit: Auth children: any[] } interface Auth { show: boolean disable: boolean checked: boolean } //--------------------------------------------------------- export interface LogForm { userName?: string dateRange?: any[] description?: string type?: string } export interface LogSearchCondition { userName?: string operatorBeginDate?: string operatorEndDate?: string description?: string type?: string } export interface Module { namespaced?: boolean state?: any getters?: any actions?: any mutations?: any modules?: any } interface UserPermission { authCode: string authName: string id?: string authDetail?: UserPermission[] | null [propName: string]: any } export interface UserState { user_info: UserInfo | null menus: Menu[] | null } export interface Menu { id: string menuTitle: string menuRouteName: string menuIcon: string menuPath: string menuSort: number [propName: string]: any } export interface UserInfo { permission: any[] menus?: Menu[] userName: string manage: any[] } //基础章节数 interface OrgNode { danweicengji: string jiancheng?: string leixing: string leixingmingcheng?: string paixuma?: number quancheng: string sequence_number?: any shangjizhujian?: string xunizuzhi?: boolean zhujian?: string zuzhibianma: string zuzhilujing: string id: string [propName: string]: any } // 章节管理权限树 export interface ChapterManageNode extends OrgNode { children?: ChapterManageNode[] } //章节授权树 export interface UserAuthNode extends OrgNode { permissionDetail: string[] children?: UserAuthNode[] } // elTree原生节点结构 export interface ChapterELNode { checked: boolean childNodes: ChapterELNode[] data: any expanded: boolean id: string | number indeterminate: boolean isLeaf: boolean level: number parent: ChapterELNode | null [propName: string]: any } //章节成员 export interface Member { memberId?: string memberName: string memberOrgCode: string memberOrgName: string memberType: string extends?: boolean add?: boolean edit?: boolean delete?: boolean deploy?: boolean view?: boolean updateTime?: any version?: number [propName: string]: any } } interface IBaseWorkCenterModule { current_page: number page_size: number total: number table_columns: any[] table_rows: any[] table_loading: boolean current_row?: any selected_rows: any[] } interface UserPermission { authMap: any authCode: any } interface APIResponse { data: any message: string success: boolean } interface Router { path: string meta?: { title: string name?: string code?: string icon?: string } component?: any children?: Router[] [propName: string]: any } //接口获取到的有权限的菜单 interface IApiMenus { updatedTime: string code: string updatedPerson: string menuGrantType?: any menuIcon: string menuPath: string menuTitle: string remark?: any version: string parentCode?: any children: IApiMenusChild[] menuRouteName: string menuRegular?: any createdTime: string createdPerson: string id: string ifUse?: any menuSort: string [propsName: string]: any } interface IApiMenusChild { updatedTime: string code: string updatedPerson: string menuGrantType?: string menuIcon: string menuPath: string menuTitle: string remark?: any version: string parentCode: string menuRouteName: string menuRegular?: any createdTime: string createdPerson: string id: string ifUse?: any menuSort: string } <file_sep>/vuepack/docs/using-css-frameworks.md # CSS frameworks You may intend to load CSS files from Bootstrap, Bulma.css, Element-UI, there're various ways to do this: ## Option 1. load in JavaScript files ```js import '/path/to/file.css' // or commonjs require('/path/to/file.css') // if you're loading something like `file.scss` // be sure to add sass-loader in webpack config for `.scss` files import '/path/to/file.scss' ``` ## Option 2. load in single file component This way is way more easier, since you don't need to modify webpack config, just installing the relevant loaders is enough. ```vue <style src="/path/to/file.css"></style> <!-- or sass with sass-loader and node-sass installed --> <style src="/path/to/file.scss" lang="sass"></style> <!-- for example, loading sass files and update variables in bulma css framework --> <style lang="sass"> $blue: #72d0eb; $pink: #ffb3b3; $family-serif: "Georgia", serif; @import "~bulma"; </style> ``` <file_sep>/vue-custom-webpack-single-spa/src/mock/utils.ts import qs from 'qs' export const parseUrl = url => { return qs.parse(url.split('?')[1]) } <file_sep>/vuepack/docs/testcafe.md # TestCafe This template contains an example of e2e tests written with [TestCafe](http://github.com/devexpress/testcafe). ## Structure `test/e2e/index.js` contains a test. `test/e2e/page-model.js` contains the [Page Model](https://martinfowler.com/bliki/PageObject.html) that describes the `index.html` page. ## Run `npm run test` e2e tests will run for all browsers installed on the target machine. For details, see the `scripts.test` section of the `package.json` file and [TestCafe documentation](https://devexpress.github.io/testcafe/documentation/) <file_sep>/vuepack/docs/css-modules.md # CSS Modules If you want to use CSS modules in single file component, simply add `module` attribute: ```vue <style module> .foo { color: blue; } </style> <template> <div id="app"> <div :class="$style.foo">foo</div> </div> </template> ``` CSS modules is disabled in your non-vue components by default (eg: `import 'style.css'` in a JS file), but when you enabled JSX components in CLI prompts it will be set to `true` by default. However you can always toggle it on and off by setting `cssModules` in `./build/config.js`: ```diff - cssModules: true + cssModules: false ``` For more documentations on the usage of CSS modules, please head to http://vue-loader.vuejs.org/en/features/css-modules.html <file_sep>/vue-custom-webpack-template(ts)/src/main-prod.ts import Vue from 'vue' import './plugins/axios' import App from './App.vue' import router from './router' import store from './store' import 'normalize.css' import '@/views/system/index.ts' //自动注册系统模块 import '@/libs/directive' import '@/libs/filter' import dayjs from 'dayjs' import { get } from 'lodash' const isProduction = process.env.NODE_ENV === 'production' Vue.config.productionTip = false Vue.config.devtools = !isProduction // 开启vue-devtools调试工具 Vue.config.performance = !isProduction Vue.prototype.$dayjs = dayjs Vue.prototype.$get = get new Vue({ router, store, render: h => h(App) }).$mount('#app') <file_sep>/vue-custom-webpack-template(ts)/src/router/index.ts import Vue from 'vue' import Router from 'vue-router' import store from '@/store/index' import NProgress from 'nprogress' // progress bar import 'nprogress/nprogress.css' Vue.use(Router) const router = new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', redirect: '/home' //默认跳转到首页 }, { path: '/home', meta: { title: '首页', icon: 'el-icon-s-home_light', code: '001' }, component: () => import('@/views/Index.vue'), children: [ { path: '', name: 'home', component: () => import('@/views/home/Index.vue') } ] }, { path: '/login', name: 'login', component: () => import('@/views/common/Login.vue') }, { path: '/logout', name: 'logout', component: () => import('@/views/common/Logout.vue') }, { path: '/error/:id', name: '404', component: () => import('@/views/common/404.vue') } ] }) const whiteList = store.state.token_white_list router.beforeEach(async (to, from, next) => { NProgress.start() let isNotNeedAuth = whiteList.some(name => { return to.name === name }) //判断是否需要token---------------------------- if (isNotNeedAuth) { next() NProgress.done() } else { next() NProgress.done() } }) export default router <file_sep>/vue-custom-webpack-single-spa/src/views/system/api/system/hr.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' let serverName = urls.system /** * @desc 获取下级单位,只包含单位 * @param orgCode */ export function queryNextLevelOrg(orgCode) { return http.get(`${serverName}sys/hr/v1.0/${orgCode}/next/dw`) } /** * @desc 获取下级组织,包含全部 * @param orgCode */ export function queryNextLevelAllOrg(orgCode) { return http.get(`${serverName}sys/hr/v1.0/${orgCode}/next/all`) } /** * @desc 获取岗位下的人员列表 * @param orgCode */ export function queryHRPsnByPostCode(postCode) { return http.get(`${serverName}sys/hr/v1.0/${postCode}/users`) } /** * @desc 人员模糊搜索 * @param orgCode */ export function psnMosaic(params) { return http.get(`${serverName}sys/hr/v1.0/psn/mosaic`, params) } /** * @desc 岗位模糊搜索 * @param orgCode */ export function postMosaic(params) { return http.get(`${serverName}sys/hr/v1.0/post/mosaic?`, params) } <file_sep>/vue-ssr-template-ts-webpack/src/plugins/axios.ts // import Vue, { PluginObject } from 'vue' // import router from '@/router/index' import axios,{AxiosRequestConfig} from 'axios' import { IAxiosInstance } from './index' // Full config: https://github.com/axios/axios#request-config // axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || ''; // axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; const config = { // baseURL: process.env.baseURL || process.env.apiUrl || "" // timeout: 60 * 1000, // Timeout // withCredentials: true, // Check cross-site Access-Control } // @ts-ignore: Unreachable code error export const _axios: IAxiosInstance = axios.create(config) _axios.interceptors.request.use( cfg => { // Do something before request is sent cfg.headers['Authorization'] = `Bearer ${sessionStorage.getItem('Authorization')}` return cfg }, err => { // Do something with request error return Promise.reject(err) } ) // Add a response interceptor _axios.interceptors.response.use( res => { const { data } = res if (data.code == 1) { return data } else if (data.code === 403) { // Notice.error({ desc: '登录已失效!' }) // router.push({ name: 'login' }) return Promise.reject(data) } else { // Notice.error({ desc: `请求错误:${data.message}` }) return Promise.reject(data) } }, err => { // Notice.error({ desc: `请求失败: ${err}` }) // Do something with response error return Promise.reject(err) } ) ;(_axios as IAxiosInstance).upload = (url, params = {}) => { let config = { method: 'post', url, data: params, headers: { 'Content-Type': 'multipart/form-data' } } //@ts-ignore return _axios(config).catch(error => { return Promise.reject(error) }) } ;(_axios as IAxiosInstance).delPost = (url, params = {}) => { let config = { method: 'delete', url, data: params, headers: { 'Content-Type': 'application/json;charset=UTF-8' } } // @ts-ignore return _axios(config).catch(error => { return Promise.reject(error) }) } <file_sep>/vue-custom-webpack-single-spa/src/views/system/store/userAuth.ts // ------------------------------------------------------------- import { Notification } from 'element-ui' import Vue from 'vue' import { cloneDeep, get } from 'lodash' import { getPageAuthorizeList, getPermissionList } from '@/views/system/api/system/userAuth' interface IUserAuthState { loading: boolean chapter_auth_tree: Vuex.UserAuthNode[] current_org_node: Vuex.UserAuthNode | null current_chapter_member: Vuex.Member[] permission_list: Permission[] | null user_page_size: number user_page_current: number user_page_total: number user_total: number multiple_selection: any[] single_selected: any[] query_extends: Boolean } interface Permission { authCode: string authName: string authSort?: string id: string } let state: IUserAuthState = { current_org_node: null, current_chapter_member: [], loading: true, permission_list: null, user_page_size: 10, user_page_current: 1, user_page_total: 0, user_total: 0, multiple_selection: [], single_selected: [], chapter_auth_tree: [], query_extends: false } const UserAuth: Vuex.Module = { namespaced: true, state, getters: { get_permission_list: state => { let { permission_list, current_chapter_member = [] } = state let permissionStatusTemp = cloneDeep(permission_list) || [] // console.log('修改全选状态') if (current_chapter_member.length <= 0) { permissionStatusTemp.map((item: Vuex.UserPermission) => { Vue.set(item, `isCheckedAll`, false) Vue.set(item, 'isCheckedPart', false) }) } else { permissionStatusTemp.map(item => { let { authCode } = item let temp = current_chapter_member.filter((itemMember: Vuex.Member) => { return itemMember[`${authCode}`] //权限为true }) // debugger switch (true) { case temp.length === current_chapter_member.length: Vue.set(item, `isCheckedAll`, true) Vue.set(item, 'isCheckedPart', false) break case temp.length < current_chapter_member.length && temp.length > 0: Vue.set(item, `isCheckedAll`, false) Vue.set(item, 'isCheckedPart', true) break case temp.length == 0: Vue.set(item, `isCheckedAll`, false) Vue.set(item, 'isCheckedPart', false) break } }) } return permissionStatusTemp } }, mutations: { SET_CURRENT_NODE(state: IUserAuthState, payload: Vuex.UserAuthNode) { state.current_org_node = payload }, SET_CURRENT_MEMBER(state: IUserAuthState, payload: any[]) { state.current_chapter_member = payload }, SET_PERMISSION_LIST(state, payload) { state.permission_list = payload }, SET_USER_PAGE_SIZE(state, payload) { state.user_page_size = payload }, SET_USER_PAGE_CURRENT(state, payload) { state.user_page_current = payload }, SET_USER_PAGE_TOTAL(state, payload) { state.user_page_total = payload }, SET_USER_TOTAL(state, payload) { state.user_total = payload }, SET_SELECT_MORE_LIST(state, payload) { state.multiple_selection = payload }, SET_SELECT_ONE_LIST(state, payload) { state.single_selected = payload }, SET_LOADING(state, status) { state.loading = status }, SET_TREE(state, payload: Vuex.UserAuthNode[]) { state.chapter_auth_tree = payload }, SET_QUERY_EXTENDS(state, payload: Boolean) { state.query_extends = payload } }, actions: { async COMMIT_CURRENT_MEMBER({ commit, state, dispatch }) { commit('SET_LOADING', true) await dispatch('COMMIT_PERMISSION_LIST') let params = { current: state.user_page_current, size: state.user_page_size, condition: { orgCode: get(state, 'current_org_node.zuzhibianma', ''), extends: state.query_extends }, sorts: [ { property: 'create_time', direction: 'ASC' } ] } let data = [] let res = await getPageAuthorizeList(params) data = res.data ? res.data.records : [] commit('SET_CURRENT_MEMBER', data) commit('SET_USER_TOTAL', res.data.total) commit('SET_USER_PAGE_TOTAL', res.data.pages) commit('SET_LOADING', false) }, async COMMIT_PERMISSION_LIST({ state, commit }) { if (!state.permission_list || state.permission_list.length <= 0) { let res = await getPermissionList() commit('SET_PERMISSION_LIST', res.data) } } } } export default UserAuth <file_sep>/vue-faster-vux(配置vux_rem)/build/build.js require('./check-versions')() var config = require("../config") process.env.NODE_ENV = 'production' var opn = require("opn") var ora = require('ora') var rm = require('rimraf') var path = require('path') var express = require("express") var chalk = require('chalk') var webpack = require('webpack') var config = require('../config') var webpackConfig = require('./webpack.prod.conf') var spinner = ora('building for production...') spinner.start() rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, function (err, stats) { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n') console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) if(process.env.npm_config_preview){ var app = express() var staticPath = path.posix.join( config.build.assetsPublicPath, config.build.assetsSubDirectory ) console.log('staticPath:'+staticPath) app.use('/', express.static(path.join(__dirname, '../dist'))) var port = 8081 var uri = "http://localhost:" + port +"" var server = app.listen(port) console.log('> Listening at ' + 'http://localhost:'+ port + '\n') opn(uri) } }) }) <file_sep>/vue-faster-vux(配置vux_rem)/src/filters/index.js /** * 性别 1 男;2 女; * @export * @param {any} val * @returns {string} */ export function sex(val) { switch (+val) { case 1: return "男" case 2: return "女" default: return "" } } <file_sep>/vuepack/docs/eslint.md # ESLint The default eslint config is [eslint-config-vue](https://github.com/vuejs/eslint-config-vue), but you can change it to anything you want in `.eslintrc`. <file_sep>/vue-custom-webpack-template(ts)/build/dev.config.js module.exports = { compress: true, publicPath: '/', host: 'localhost', port: 8080, open: false, proxy: { '/LZB': { target: 'http://192.168.31.212:9090/', // 组件服务 ws: true, changeOrigin: true, pathRewrite: { '^/LZB': '' } }, '/local': { target: 'http://192.168.31.212:9090/', // 组件服务 ws: true, changeOrigin: true, pathRewrite: { '^/local': '' } }, '/Online': { target: 'http://36.111.84.153:9090/', //project 服务器 ws: true, changeOrigin: true, pathRewrite: { '^/Online': '' } } } } <file_sep>/vue-custom-webpack-single-spa/src/components/base/userAuth.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' let serverName = urls.system // let serverName = urls.Mock export function getNextOrgList(orgCode) { //获取下级机构列表,最末级为人员 return http.get(`${serverName}system/org/v1.0/${orgCode}/next/all`) } export function getNextDwList(orgCode) { //获取下级机构列表,最末级为单位 return http.get(`${serverName}system/org/v1.0/${orgCode}/next/dw`) } export function getPostPersonList(orgCode) { //获取岗位下人员列表 return http.get(`${serverName}system/user/v1.0/sysUser/hr/${orgCode}`) } export function getAuthorizeList(orgCode) { // 获取组织下人员 return http.get(`${serverName}system/user/v1.0/sysUser/local/${orgCode}`) } export function getPageAuthorizeList(data) { //分页获取人员 return http.post(`${serverName}system/user/v1.0/sysUsers`, data) } export function getPermissionList() { //获取所有权限分类 return http.get(`${serverName}system/user/v1.0/auth/query`) } export function getPersonList(orgCode) { // 获取组织下人员 return http.get(`${serverName}system/user/v1.0/sysUser/hr/${orgCode}`) } export function postSearchPersonList(data) { // 模糊搜索组织下人员 return http.post(`${serverName}system/user/v1.0/mosaic`, data) } <file_sep>/vue-custom-webpack-single-spa/src/main.ts import Vue from 'vue' import './plugins/axios' import App from './App.vue' import router from './router' import store from './store' import 'normalize.css' import '@/views/system/index.ts' //自动注册系统模块 import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import '@/libs/directive' import '@/libs/filter' import dayjs from 'dayjs' import { get } from 'lodash' Vue.use(ElementUI, { size: 'small', zIndex: 3000 }) Vue.config.productionTip = false Vue.config.devtools = process.env.NODE_ENV !== 'production' // 开启vue-devtools调试工具 Vue.config.performance = process.env.NODE_ENV !== 'production' Vue.prototype.$get = get Vue.prototype.$dayjs = dayjs new Vue({ router, store, render: h => h(App) }).$mount('#app') <file_sep>/vue-custom-webpack-template(ts)/src/mock/index.ts import Mock from 'mockjs' import User from './user' import System from './system' Mock.setup({ timeout: '100-600' }) //获取下级组织 Mock.mock(/mockjs\/sys\/org\/v1\.0\/\d+\/next\/all\.*/, 'get', User.getTreeLevel0) //获取人员列表 Mock.mock(/mockjs\/system\/v1\.0\/sysUsers\.*/, 'post', User.getPageAuthorizeList) // 获取权限分类 Mock.mock(/mockjs\/sys\/v1\.0\/permission\/query\.*/, 'get', User.getPermissionList) //获取数据字典 Mock.mock(/mockjs\/system\/category\/v1\.0\/wholetree/, 'get', User.getWholeTree) //获取userInfo Mock.mock(/mockjs\/system\/user\/v1\.0\/userinfo/, 'get', User.getUserInfo) //获取系统菜单 // Mock.mock(/mockjs\/system\/menu\/v1\.0\/sysmenu/, 'get', User.getSysMenu) //获取系统菜单 Mock.mock(/mockjs\/system\/user\/v1\.0\/sysmenu/, 'get', System.getSystemMenu) <file_sep>/vue-custom-webpack-template(ts)/build/webpack.base.js const path = require('path') var webpack = require('webpack') const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') const ProgressPlugin = require('progress-bar-webpack-plugin') const VueLoaderPlugin = require('vue-loader/lib/plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') const PreloadWebpackPlugin = require('preload-webpack-plugin') const HardSourceWebpackPlugin = require('hard-source-webpack-plugin') const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin') function resolve(dir) { return path.join(__dirname, '..', dir) } const isProduction = process.env.NODE_ENV === 'production' const inlineLimit = 4096 console.log('isProduction: ', process.env.NODE_ENV) module.exports = { mode: isProduction ? 'production' : 'development', context: path.resolve(__dirname, '../'), //用于从配置中解析入口起点(entry point)和 loader entry: './src/main.ts', output: { path: path.resolve(__dirname, '../dist'), // filename: 'bundle.js', //对于单个入口起点,filename 可以是静态名称。 // filename: 'js/[name]-[contenthash:8].js', //多页面应该是动态名称 // chunkFilename: 'js/[name]-[contenthash:8].js', publicPath: '/' //所有资源请求的路径,可以为url,或者前缀,默认为'' }, resolve: { extensions: ['.mjs', '.js', '.ts', '.tsx', '.jsx', '.vue', '.json', '.wasm', '.scss'], alias: { '@': resolve('src'), vue$: 'vue/dist/vue.esm.js' }, modules: ['node_modules', resolve('node_modules')] }, module: { noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/, rules: [ { test: /\.vue$/, use: [ { loader: 'vue-loader', options: { compilerOptions: { // preserveWhitespace: false }, cacheIdentifier: '3f1ace22' } } ] }, { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'thread-loader' }, { loader: 'babel-loader' } ] }, { test: /\.tsx?$/, use: [ { loader: 'thread-loader' }, { loader: 'babel-loader' }, { loader: 'ts-loader', options: { transpileOnly: true, appendTsSuffixTo: ['\\.vue$'], happyPackMode: true } } ] }, //动态注入css的相关loader { test: /\.(png|jpe?g|gif|webp)(\?.*)?$/, loader: 'url-loader', options: { limit: inlineLimit, fallback: { loader: 'file-loader', options: { name: 'img/[name].[hash:8].[ext]' } } } }, { test: /\.(woff2?|eot|ttf|otf|svg)(\?.*)?$/i, loader: 'url-loader', options: { limit: inlineLimit, fallback: { loader: 'file-loader', options: { name: 'fonts/[name].[hash:8].[ext]' } } } }, { test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: { limit: inlineLimit, fallback: { loader: 'file-loader', options: { name: 'media/[name].[hash:8].[ext]' } } } }, { enforce: 'pre', test: /\.(vue|(j|t)sx?)$/, exclude: [/node_modules/], use: [ { loader: 'eslint-loader', options: { fix: true, extensions: ['.js', '.jsx', '.vue', '.ts', '.tsx'], cache: true, cacheIdentifier: '770ad02b', emitWarning: true, emitError: false, formatter: require('eslint-friendly-formatter') } } ] } ] }, stats: { entrypoints: false, //关闭不必要的提示 children: false }, plugins: [ new VueLoaderPlugin(), new ProgressPlugin(), new FriendlyErrorsPlugin(), new HardSourceWebpackPlugin({ cacheDirectory: '../.cache/hard-source/[confighash]' }), new webpack.optimize.ModuleConcatenationPlugin(), //作用域提升,减少函数申明语句产生的代码 new HtmlWebpackPlugin({ filename: 'index.html', template: isProduction ? resolve('/public/index-cdn.html') : path.join(__dirname, '../public', 'index.html'), chunksSortMode: 'none' }), new CopyWebpackPlugin([ { from: './public', to: './public', toType: 'dir', ignore: ['.DS_Store', '*.html'] } ]), new PreloadWebpackPlugin({ rel: 'preload', include: 'initial', fileBlacklist: [/\.map$/, /hot-update\.js$/] }), new PreloadWebpackPlugin({ rel: 'prefetch', include: 'asyncChunks' }), new ForkTsCheckerWebpackPlugin({ vue: true, tslint: true, formatter: 'codeframe', checkSyntacticErrors: true }) ] } <file_sep>/vue-custom-webpack-single-spa/src/views/system/api/system/process.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' let serverName = urls.system // let serverName = urls.Mock //查询审批流程信息 export function getProcessList() { return http.get(`${serverName}system/workflow/v1.0/flows`) } //添加工作流程 export function addProcess(data) { return http.post(`${serverName}system/workflow/v1.0/sysWorkFlow`, data) } //删除工作流程 export function deleteProcess(id) { return http.delete(`${serverName}system/workflow/v1.0/${id}`) } //查询流程具体信息 export function getProcessDetail(flowId, orgCode) { return http.get(`${serverName}system/workflow/v1.0/${flowId}/${orgCode}`) } //获取nodeid获取审核人员/岗位信息 export function getProcessAuditors(nodeId) { return http.get(`${serverName}system/workflow/v1.0/${nodeId}/auditors`) } //新增流程和机构映射 export function addProcessOrgMap(data) { return http.post(`${serverName}system/workflow/v1.0/mapping`, data) } //新增流程和机构映射 export function putProcessOrgMap(data) { return http.put(`${serverName}system/workflow/v1.0/mapping`, data) } //发布流程和机构映射 export function publishProcessOrgMap(data) { return http.post(`${serverName}system/workflow/v1.0/mapping/publish`, data) } //取消发布流程和机构映射 export function rollbackProcessOrgMap(data) { return http.post(`${serverName}system/workflow/v1.0/mapping/rollback`, data) } //根据流程和机构映射ID查询单条记录 export function getMapSingleDetail(mappingId) { return http.get(`${serverName}system/workflow/v1.0/mapping/${mappingId}`) } //根据流程和机构映射ID查询删除记录 export function deleteMapSingle(mappingId) { return http.delete(`${serverName}system/workflow/v1.0/mapping/${mappingId}`) } //添加流程节点 export function addProcessNode(data) { return http.post(`${serverName}system/workflow/v1.0/node`, data) } //根据ID删除节点 export function deleteProcessNode(id) { return http.delete(`${serverName}system/workflow/v1.0/node/${id}`) } //交换节点顺序 export function exchangeProcessNode(data) { return http.post(`${serverName}system/workflow/v1.0/node/exchangeSort`, data) } <file_sep>/VueWebpackTemplate/template/src/store/states.js // states.js用来定义需要使用vuex保存的数据 const states = { testObj: {} }; export default states; <file_sep>/vux2/template/src/main.js {{#if_eq build "standalone"}} // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. {{/if_eq}} import Vue from 'vue'{{#if_eq lintConfig "airbnb"}};{{/if_eq}} import FastClick from 'fastclick'{{#if_eq lintConfig "airbnb"}};{{/if_eq}} import VueRouter from 'vue-router'{{#if_eq lintConfig "airbnb"}};{{/if_eq}} import App from './App'{{#if_eq lintConfig "airbnb"}};{{/if_eq}} import Home from './components/HelloFromVux'{{#if_eq lintConfig "airbnb"}};{{/if_eq}} Vue.use(VueRouter){{#if_eq lintConfig "airbnb"}};{{/if_eq}} const routes = [{ path: '/', component: Home{{#if_eq lintConfig "airbnb"}},{{/if_eq}} }]{{#if_eq lintConfig "airbnb"}};{{/if_eq}} const router = new VueRouter({ routes{{#if_eq lintConfig "airbnb"}},{{/if_eq}} }){{#if_eq lintConfig "airbnb"}};{{/if_eq}} FastClick.attach(document.body){{#if_eq lintConfig "airbnb"}};{{/if_eq}} Vue.config.productionTip = false{{#if_eq lintConfig "airbnb"}};{{/if_eq}} /* eslint-disable no-new */ new Vue({ router, render: h => h(App){{#if_eq lintConfig "airbnb"}},{{/if_eq}} }).$mount('#app-box'){{#if_eq lintConfig "airbnb"}};{{/if_eq}} <file_sep>/README.md >## vue项目模板 ### 包括 > ### webpack-dev webpack 官方vue-cli模板 > ### mpvue 使用vue编写微信小程序 > ### vue-faster (免安装_配置rem_dll_happypack) > ### vue-faster-vux (配置vux_rem) > ### vuepack 免配置模板,已配置elementUI、px2rem > ### pwa ``` $ vue init ./ ``` <file_sep>/vue-custom-webpack-template(ts)/src/views/system/store/process.ts import { getProcessDetail } from '@/views/system/api/system/process' import { Notification } from 'element-ui' import { get } from 'lodash' const process = { namespaced: true, state: { current_selected_process: null, current_org_tree_node: null, process_map_info: [] }, getters: {}, mutations: { SET_CURRENT_SELECTED_PROCESS(state, payload) { state.current_selected_process = payload }, SET_CURRENT_ORG_TREE_NODE(state, payload) { state.current_org_tree_node = payload }, SET_PROCESS_MAP_INFO(state, payload) { state.process_map_info = payload } }, actions: { async COMMIT_PROCESS_MAP_INFO({ commit, state }) { let processId = get(state, 'current_selected_process.id', null) let zuzhibianma = get(state, 'current_org_tree_node.data.zuzhibianma', null) let processMapInfo = [] getProcessDetail(processId, zuzhibianma) .then(res => { processMapInfo = res.data }) .catch(e => { processMapInfo = [] Notification.error(`查询审批流程失败 ${e.message}`) }) .finally(() => { commit('SET_PROCESS_MAP_INFO', processMapInfo) }) } } } export default process <file_sep>/vue-custom-webpack-single-spa/src/views/system/log/log.d.ts declare namespace NLog { export interface LogForm { userName?: string dateRange?: any[] description?: string type?: string } export interface LogSearchCondition { userName?: string operatorBeginDate?: string operatorEndDate?: string description?: string type?: string } } <file_sep>/vue-custom-webpack-single-spa/src/libs/directive.ts import Vue from 'vue' import store from '@/store/index' //取交集 import { intersection } from 'lodash' Vue.directive('permission', { inserted: (el, binding) => { const btnPermissionCodeArray = Array.isArray(binding.value) ? binding.value : [binding.value] const modifiers = binding.modifiers let hasAccessList = intersection(btnPermissionCodeArray, store.state.all_has_permission_code) if (hasAccessList.length > 0) { return } if (modifiers.disable) { //禁用元素 el.style.filter = 'grayscale(60%)' el.style.opacity = '0.4' el.style.cursor = 'not-allowed' setTimeout(() => { el.setAttribute('disabled', 'disabled') }, 0) } else { //移除元素 el.parentNode && el.parentNode.removeChild(el) } } }) <file_sep>/vue-custom-webpack-template(ts)/src/store/index.ts import Vue from 'vue' import Vuex, { Store } from 'vuex' import router from '@/router' import createPersistedState from 'vuex-persistedstate' import treeFlatten from 'tree-flatten' import { getPermissionRouterTree } from '@/libs/commonUtils' import { login, getWholeTree, changeManageOrg, getMessageList, getUserAuthOrgs, getUserAuthMenus, getUserAction } from '@/api/common' import { Notification } from 'element-ui' import { get, map, flatten } from 'lodash' import system from '@/router/system' import Message from './modules/message' Vue.use(Vuex) interface IRootState { [propName: string]: any token_white_list: string[] router_name_whiteList: string[] base_has_permission_router: any[] api_has_permission_router: any[] all_has_permission_router: any[] all_has_permission_code: any[] api_permission_menus: any[] api_permission_menus_name: string[] api_permission_menus_path: string[] user_info: any category: any[] user_auth_orgs: any[] current_selected_manage_org?: any is_mounted_routers: boolean } const store: Store<IRootState> = new Vuex.Store({ plugins: [ createPersistedState({ storage: window.sessionStorage, reducer(state) { return { user_info: state.user_info, user_auth_orgs: state.user_auth_orgs, all_has_permission_code: state.all_has_permission_code } } }) ], modules: { Message }, state: { token_white_list: ['login', 'logout', '404'], // 无需token的路由 router_name_whiteList: ['home'], // 无需权限路由name base_has_permission_router: [], // 基础无需权限路由code api_has_permission_router: [], // 接口返回有权限的路由 all_has_permission_router: [], // 所有有访问权限的路由 all_has_permission_code: [], // 所有有访问权限的按钮code // 从接口获取到的权限菜单列表,平铺数组 api_permission_menus: [], api_permission_menus_name: [], //所有有权限的路由的name[] api_permission_menus_path: [], user_info: null, category: [], //用户所有可管理机构 user_auth_orgs: [], //当前选择的管理机构 current_selected_manage_org: null, //是否已经挂载路由 is_mounted_routers: false, //当前用户接收到的提示信息 message_list: null, current_message_page: 1, message_total: 0 }, getters: { get_all_permission_menu(state, getter) { const { get_system_permission_menu } = getter let allPermissionMenu = [get_system_permission_menu] allPermissionMenu = allPermissionMenu.filter(Boolean) return allPermissionMenu }, get_system_permission_menu(state) { // const router = getPermissionRouterTree(system, state.api_permission_menus_name, state.api_permission_menus_path) // return router return system } }, mutations: { SET_ALL_HAS_PERMISSION_CODE(state, payload) { state.all_has_permission_code = payload }, SET_API_HAS_PERMISSION_ROUTER(state, payload) { state.api_has_permission_router = payload }, SET_ALL_HAS_PERMISSION_ROUTER(state, payload) { state.all_has_permission_router = payload }, SET_USER_INFO(state, payload) { state.user_info = payload }, SET_CATEGORY(state, payload) { state.category = payload }, SET_USER_AUTH_ORGS(state, payload) { state.user_auth_orgs = payload }, SET_CURRENT_SELECTED_MANAGE_ORG(state, payload) { state.current_selected_manage_org = payload }, SET_API_PERMISSION_MENUS(state, payload) { state.api_permission_menus = payload }, SET_API_PERMISSION_MENUS_NAME(state, payload) { state.api_permission_menus_name = payload }, SET_API_PERMISSION_MENUS_PATH(state, payload) { state.api_permission_menus_path = payload }, SET_IS_MOUNTED_ROUTERS(state, payload) { state.is_mounted_routers = payload } }, actions: { // 登录时获取用户信息 COMMIT_USER_LOGIN({ commit }) { return new Promise((resolve, reject) => { login() .then((res: any) => { console.time('user') commit('SET_USER_INFO', res.data) //================设置管理机构==================== const userAuthOrgs = get(res, 'data.managerOrgList', []) commit('SET_USER_AUTH_ORGS', userAuthOrgs) //=============设置权限菜单==================== const apiMenu = get(res, 'data.menuPermission', []) let menusArray: any[] = [] //平铺后的菜单 apiMenu.map(item => { menusArray.push(...treeFlatten(item, 'children')) }) // console.log('menusArray: ', map(menusArray, 'menuRouteName')) let allHasPermissionCode: string[] = map(menusArray, 'actionCode') allHasPermissionCode = flatten(allHasPermissionCode) console.timeEnd('user') // console.log('allHasPermissionCode: ', allHasPermissionCode) commit('SET_API_PERMISSION_MENUS', menusArray) commit('SET_API_PERMISSION_MENUS_NAME', map(menusArray, 'menuRouteName')) commit('SET_API_PERMISSION_MENUS_PATH', map(menusArray, 'menuPath')) commit('SET_ALL_HAS_PERMISSION_CODE', allHasPermissionCode) resolve() }) .catch(e => { Notification.error(`用户信息获取失败: ${e.message}`) reject(e) }) }) }, //切换当前管理机构 COMMIT_CHANGE_MANAGE_ORG({ state, getters, commit, dispatch }) { return new Promise((resolve, reject) => { const orgCode = get(state.current_selected_manage_org, 'orgCode', '') // console.log('orgCode: ', orgCode)console.log('authdata: ', data) changeManageOrg(orgCode) .then((res: any) => { console.time('user') commit('SET_USER_INFO', res && res.data) // //================设置管理机构==================== const userAuthOrgs = get(res, 'data.managerOrgList', []) commit('SET_USER_AUTH_ORGS', userAuthOrgs) //=============设置权限菜单==================== const apiMenu = get(res, 'data.menuPermission', []) let menusArray: any[] = [] //平铺后的菜单 apiMenu.map(item => { menusArray.push(...treeFlatten(item, 'children')) }) // console.log('menusArray: ', map(menusArray, 'menuRouteName')) let allHasPermissionCode: string[] = map(menusArray, 'actionCode') allHasPermissionCode = flatten(allHasPermissionCode) console.timeEnd('user') // console.log('allHasPermissionCode: ', allHasPermissionCode) commit('SET_API_PERMISSION_MENUS', menusArray) commit('SET_API_PERMISSION_MENUS_NAME', map(menusArray, 'menuRouteName')) commit('SET_API_PERMISSION_MENUS_PATH', map(menusArray, 'menuPath')) commit('SET_ALL_HAS_PERMISSION_CODE', allHasPermissionCode) resolve() }) .catch(e => { Notification.error(`获取管理机构失败: ${e.message}`) setTimeout(() => { router.push({ name: 'home' }) }, 5000) reject(e) }) }) }, //挂载路由 async COMMIT_MOUNT_ROUTER({ state, getters, commit, dispatch }) { return new Promise((resolve, reject) => { dispatch('COMMIT_MESSAGE_LIST') // dispatch('COMMIT_USER_LOGIN') dispatch('COMMIT_CHANGE_MANAGE_ORG') .then(() => { commit('SET_IS_MOUNTED_ROUTERS', true) setTimeout(() => { resolve(getters.get_all_permission_menu) }, 0) }) .catch(e => { reject(e) }) }) }, // 获取数据字典信息 async COMMIT_CATEGORY({ state, commit }) { return new Promise((resolve, reject) => { let token = sessionStorage.getItem('Authorization') let hasCategory = get(state, 'category[0]') if (token && !hasCategory) { getCategoryFromApi(resolve, reject) } else { resolve() } }) function getCategoryFromApi(resolve, reject) { //通过api获取 getWholeTree() .then(res => { let index = res.data.findIndex(item => { return item.categoryCode === 'api' }) if (index >= 0) { res.data[index].children.forEach(item => { item.details.forEach(item1 => { item1.detailCode = parseInt(item1.detailCode) item1.detailSort = parseInt(item1.detailSort) }) }) } commit('SET_CATEGORY', res.data) resolve() }) .catch(e => { Notification.error(`获取数据字典失败: ${e.message}`) reject() }) } }, // 登出 async COMMIT_LOGOUT({ state, commit }) { sessionStorage.clear() localStorage.clear() clearAllCookie() function clearAllCookie() { let keys = document.cookie.match(/[^ =;]+(?==)/g) if (keys) { for (let i = keys.length; i--; ) document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString() } } router.push({ name: 'logout' }) // logout() // .then(() => { // router.push({ name: 'logout' }) // }) // .catch(e => { // router.push({ name: 'logout' }) // Notification.error(`登出失败: ${e.message}`) // }) } } }) export default store <file_sep>/vue-custom-webpack-single-spa/src/views/system/index.ts import store from '@/store' import router from '@/router' import systemRoute from './router/index' // 注册路由 router.addRoutes(systemRoute) // 注册store模块 import Log from './store/log' import Menu from './store/menu' import UserAuth from './store/userAuth' import System from './store/system' import Process from './store/process' const modules = { Log, Menu, UserAuth, Process, System } for (const module in modules) { store.registerModule(module, modules[module]) } // 注册api <file_sep>/vue-ssr-template-ts-webpack/src/api/user.ts import urls from '@/plugins/urls' import { _axios as http } from '@/plugins/axios' const serverName = urls.local interface Login { userName: string password: string } interface Response { code: number data: any massage: string } //登录接口,使用用户名登录 export function login(data: Login) { return http.post(`${serverName}/login`, data) } //使用用户名注册 export function register(data: Login) { return http.post(`${serverName}/regist`, data) } //获取用户信息 export function getUserInfo() { return http.get(`${serverName}/userInfo`) } //验证登录状态 export function authUserLogin() { return http.get(`${serverName}/authUserLogin`) } <file_sep>/vue-custom-webpack-template(ts)/src/views/system/menus/menu.d.ts interface IMenuForm { parentCode?:string code?: string; menuTitle: string; menuIcon: string; menuPath: string; menuRouteName: string; menuSort: string; inUse: boolean; remark?: string; children?: any[]; }<file_sep>/vuepack/docs/static-files.md # Static Files We are using [file-loader](https://github.com/webpack/file-loader) to handle static files, which mean you can directly import the file you need and it will give you the path of that file: ```js import foo from './assets/foo.png' //=> /public-path/foo.8a3c262cfd45869e351f.png ``` But we also use [raw-loader](https://github.com/webpack/raw-loader) to handle `.svg` files, it would direcly give you the raw content of the SVG so that you can inline it to your component, since [Inline SVG is Best SVG](https://www.youtube.com/watch?v=af4ZQJ14yu8). --- For something like **favicon.ico**, we use [copy-webpack-plugin](https://github.com/kevlened/copy-webpack-plugin) to copy everything inside `./static` folder to the root of dist folder. <file_sep>/vue-ssr-template-ts-webpack/src/entry-client.js import createApp from './main' import { isLogin } from './util' const { app, router, store } = createApp() const islogin = isLogin() if (router.history.pending.name === 'login') { if (islogin) { router.push('/') } } else if (!islogin) { router.replace('/login') } router.onReady(() => { app.$mount('#app') }) if (window.__INITIAL_STATE__) { store.replaceState(window.__INITIAL_STATE__) } <file_sep>/VueWebpackTemplate/template/src/common/js/config.js // config.js用来保存通用的js配置 <file_sep>/vue-faster-vux(配置vux_rem)/build/build-dll.js var path = require("path") var webpack = require("webpack") var dllConfig = require("./webpack.dll.conf") var chalk = require("chalk") var rm = require("rimraf") var ora = require("ora") var spinner = ora({ color: "green", text: "building for Dll..." }) spinner.start() rm(path.resolve(__dirname, "../libs"), err => { if (err) throw err webpack(dllConfig, function(err, stats) { spinner.stop() if (err) throw err process.stdout.write( stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + "\n\n" ) console.log(chalk.cyan(" build dll succeed !.\n")) }) }) <file_sep>/vue-ssr-template-ts-webpack/build/webpack.base.config.js const path = require('path') const webpack = require('webpack') const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') const ProgressPlugin = require('progress-bar-webpack-plugin') const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin') const { VueLoaderPlugin } = require('vue-loader') const HardSourceWebpackPlugin = require('hard-source-webpack-plugin') const { HashedModuleIdsPlugin } = require('webpack') const HtmlWebpackPlugin = require('html-webpack-plugin') const WebpackCdnPlugin = require('webpack-cdn-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') // const PreloadWebpackPlugin = require('preload-webpack-plugin') // const MiniCssExtractPlugin = require('mini-css-extract-plugin') // const OptimizeCssnanoPlugin = require('@intervolga/optimize-cssnano-plugin') // const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const inlineLimit = 4096 const isProd = process.env.NODE_ENV === 'production' function resolve(dir) { return path.join(__dirname, '..', dir) } module.exports = { mode: isProd ? 'production' : 'development', devtool: isProd ? false : '#cheap-module-source-map', output: { //由于使用node做服务器,故需设置静态资源文件夹,所以项目资源请求添加/dist前缀,用于区分 publicPath: '/dist/' }, resolve: { extensions: ['.mjs', '.js', '.ts', '.tsx', '.jsx', '.vue', '.json', '.wasm', '.scss', 'styl'], alias: { '@': resolve('src'), public: resolve('public'), vue$: 'vue/dist/vue.esm.js' }, modules: ['node_modules', resolve('node_modules'), resolve('node_modules/@vue/cli-service/node_modules')] }, module: { noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/, rules: [ { enforce: 'pre', test: /\.(vue|(j|t)sx?)$/, exclude: [/node_modules/], use: [ /* config.module.rule('eslint').use('eslint-loader') */ { loader: 'eslint-loader', options: { fix: true, extensions: ['.js', '.jsx', '.vue', '.ts', '.tsx'], cache: true, emitWarning: true, emitError: false } } ] }, { test: /\.jsx?$/, exclude: /node_modules/, use: [ { loader: 'babel-loader' } ] }, { test: /\.vue$/, use: [ { loader: 'vue-loader', options: { compilerOptions: { preserveWhitespace: false } } }, { loader: 'iview-loader', options: { prefix: true } } ] }, { test: /\.(css|scss)$/, use: [ 'vue-style-loader', 'css-loader', 'postcss-loader', { loader: 'sass-loader', options: { sourceMap: !isProd, prependData: '@import "@/assets/scss/variable.scss";' } } ] }, { test: /\.(less)$/, use: ['vue-style-loader', 'css-loader', 'less-loader', 'postcss-loader'] }, { test: /\.(styl|stylus)$/, use: ['vue-style-loader', 'css-loader', 'stylus-loader', 'postcss-loader'] }, { test: /\.(png|jpe?g|gif|webp)(\?.*)?$/, loader: 'url-loader', options: { limit: inlineLimit, fallback: { loader: 'file-loader', options: { name: 'img/[name].[hash:8].[ext]' } } } }, { test: /\.(woff2?|eot|ttf|otf|svg)(\?.*)?$/i, loader: 'url-loader', options: { limit: inlineLimit, fallback: { loader: 'file-loader', options: { name: 'fonts/[name].[hash:8].[ext]' } } } }, { test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: { limit: inlineLimit, fallback: { loader: 'file-loader', options: { name: 'media/[name].[hash:8].[ext]' } } } }, { test: /\.tsx?$/, exclude: [], use: [ { loader: 'babel-loader' }, { loader: 'ts-loader', options: { transpileOnly: true, appendTsSuffixTo: ['\\.vue$'], happyPackMode: false, reportFiles: [] } } ] } ] }, performance: { // maxEntrypointSize: 300000, hints: isProd ? 'warning' : 'warning' }, externals: isProd ? { vue: 'Vue', 'vue-router': 'VueRouter', vuex: 'Vuex', lodash: '_', axios: 'axios', echarts: 'echarts', 'v-charts': 'VeIndex', iview: 'iview' } : {}, plugins: isProd ? [ new VueLoaderPlugin(), new ProgressPlugin(), new CopyWebpackPlugin([ { from: './public', to: './', toType: 'dir', ignore: ['.DS_Store', '*.html'] } ]), new CopyWebpackPlugin([ { from: './server-prod.js', to: './server-prod.js', toType: 'file' } ]), // new HardSourceWebpackPlugin({ cacheDirectory: '../.cache/hard-source/[confighash]' }), new FriendlyErrorsPlugin(), new webpack.optimize.ModuleConcatenationPlugin(), // new PreloadWebpackPlugin({ // rel: 'preload', // include: 'initial', // fileBlacklist: [/\.map$/, /hot-update\.js$/] // }), // new PreloadWebpackPlugin({ // rel: 'prefetch', // include: 'asyncChunks' // }), new HtmlWebpackPlugin({ filename: 'index.html', template: resolve('/public/index.cdn.html'), chunksSortMode: 'none' }), //自动根据当前package.json生成CDN链接 new WebpackCdnPlugin({ modules: [ { name: 'vue', var: 'Vue', path: 'vue.runtime.min.js' }, { name: 'vue-router', var: 'VueRouter', path: 'vue-router.min.js' }, { name: 'vuex', var: 'Vuex', path: 'vuex.min.js' }, { name: 'lodash', cdn: 'lodash.js', //cdn中的名称,默认与name相同,用于匹配package.json里的依赖 var: '_', path: 'lodash.min.js' }, { name: 'element-ui', var: 'ELEMENT', path: 'index.js', style: 'theme-chalk/index.css' }, { name: 'iview', var: 'iview', path: 'iview.min.js', style: 'styles/iview.css' }, { name: 'axios', var: 'axios', path: 'axios.min.js' }, { name: 'echarts', var: 'echarts', path: 'echarts.min.js' }, { name: 'sortablejs', var: 'Sortable', path: 'Sortable.min.js' } ], prodUrl: 'https://cdn.bootcss.com/:name/:version/:path' }), new ForkTsCheckerWebpackPlugin({ vue: true, tslint: true, formatter: 'codeframe', checkSyntacticErrors: false }), new HashedModuleIdsPlugin({ hashDigest: 'hex' }) // new MiniCssExtractPlugin({ // filename: 'css/[name].[contenthash:8].css', // chunkFilename: 'css/[name].[contenthash:8].chunk.css' // }), // new OptimizeCssnanoPlugin({ // sourceMap: false, // cssnanoOptions: { // preset: [ // 'default', // { // discardComments: { // removeAll: true // }, // mergeLonghand: false, // cssDeclarationSorter: false // } // ] // } // }), // new BundleAnalyzerPlugin() ] : [ new VueLoaderPlugin(), new ProgressPlugin(), new HardSourceWebpackPlugin({ cacheDirectory: '../.cache/hard-source/[confighash]' }), new webpack.optimize.ModuleConcatenationPlugin() ] } <file_sep>/vue-ssr-template-ts-webpack/src/main.ts import Vue from 'vue' import { sync } from 'vuex-router-sync' import App from './App.vue' import createStore from './store' import createRouter from './router' // Detect environment const isBrowser = process.env.VUE_ENV === 'client' // const iView = isBrowser ? require('iview') : undefined const InfiniteLoading = isBrowser ? require('vue-infinite-loading') : undefined const VueLazyload = isBrowser ? require('vue-lazyload') : undefined if (isBrowser) { Vue.use(require('iview')) require('iview/dist/styles/iview.css') Vue.use(InfiniteLoading, { system: { throttleLimit: 500 } }) Vue.use(VueLazyload, { preLoad: 1.3, error: '/public/default.jpg', loading: '/public/default.jpg', attempt: 3 }) // Vue.component('water-fall', Waterfall) // Vue.component('waterfall-slot', WaterfallSlot) } Vue.config.productionTip = false export default function createApp() { const router = createRouter() const store = createStore() // sync router & state sync(store, router) // @ts-ignore const app = new Vue({ router, store, render: h => h(App) }) return { app, router, store } } <file_sep>/vue-ssr-template-ts-webpack/build/setup-dev-server.js const fs = require('fs') const path = require('path') const MFS = require('memory-fs') const webpack = require('webpack') const chokidar = require('chokidar') const devMiddlewareFn = require('webpack-dev-middleware') const hotMiddlewareFn = require('webpack-hot-middleware') const clientConfig = require('./webpack.client.config') const serverConfig = require('./webpack.server.config') const chalk = require('chalk') const { log } = console const readFile = (fileSystem, file) => { try { return fileSystem.readFileSync(path.join(clientConfig.output.path, file), 'utf-8') } catch (e) { console.log(e) return e } } module.exports = function setupDevServer(app, templatePath, cb) { let bundle let template let clientManifest let ready // export ready promise const readyPromise = new Promise(resolve => { ready = resolve }) const update = () => { // when bundle and clientManifest were compiled completely, then call resolve method of promise if (bundle && clientManifest) { ready() cb(bundle, { template, clientManifest }) } } // read and watch template from disk template = fs.readFileSync(templatePath, 'utf-8') chokidar.watch(templatePath).on('change', () => { template = fs.readFileSync(templatePath, 'utf-8') log('✅ index.html template updated') update() }) // modify client config to work with hot middleware clientConfig.entry.app = ['webpack-hot-middleware/client', clientConfig.entry.app] clientConfig.output.filename = '[name].js' clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()) // ====================client renderer======================= // dev middleware const clientCompiler = webpack(clientConfig) const devMiddleware = devMiddlewareFn(clientCompiler, { publicPath: clientConfig.output.publicPath, noInfo: true }) app.use(devMiddleware) function handle(stats) { return new Promise((resolve, reject) => { const json = stats.toJson() if (json.errors.length) { reject() } json.errors.forEach(err => console.error(err)) json.warnings.forEach(err => console.warn(err)) resolve() }) } clientCompiler.hooks.done.tap('done', stats => { handle(stats).catch(() => { return }) clientManifest = JSON.parse(readFile(devMiddleware.fileSystem, 'vue-ssr-client-manifest.json')) log(chalk.green('✅ vue-ssr-client-manifest.json done')) update() }) // hot middleware app.use(hotMiddlewareFn(clientCompiler, { heartbeat: 5000 })) // ====================server renderer======================= // watch and update server renderer const serverCompiler = webpack(serverConfig) const mfs = new MFS() serverCompiler.outputFileSystem = mfs serverCompiler.watch({}, (err, stats) => { if (err) throw err // if (json.errors.length) return handle(stats).catch(() => { return }) const port = process.env.PORT || 8080 // read bundle generated by vue-ssr-webpack-plugin bundle = JSON.parse(readFile(mfs, 'vue-ssr-server-bundle.json')) log(chalk.green('✅ vue-ssr-server-bundle.json done')) log(chalk.green(`server started at http://localhost:${port}`)) update() }) return readyPromise } <file_sep>/vue-custom-webpack-single-spa/src/views/system/router/index.ts const systemRoute = [ { path: '/system', meta: { title: '首页', name: 'home', code: 'SY' }, // component: () => import('@/views/common/Index.vue'), component: () => import('@/views/Index.vue'), children: [ { path: '', meta: { title: '系统管理', code: 'SY001' }, component: () => import('@/views/system/Index.vue'), children: [ { path: 'menus', name: 'menus', meta: { title: '菜单管理', code: 'SY001001' }, component: () => import('@/views/system/menus/Index.vue') }, { path: 'category', name: 'category', meta: { title: '数据字典', code: '' }, component: () => import('@/views/system/category/Index.vue') }, { path: 'user', name: 'userAuth', meta: { title: '用户管理', code: 'SY001003' }, component: () => import('@/views/system/userAuth/Index.vue') }, { path: 'auth', name: 'auth', meta: { title: '授权demo', code: 'SY001006' }, component: () => import('@/views/system/auth/Index.vue') }, { path: 'process', name: 'process', meta: { title: '流程管理', code: 'SY001004' }, component: () => import('@/views/system/process/Index.vue') }, { path: 'log', name: 'log', meta: { title: '日志管理', code: 'SY001005' }, component: () => import('@/views/system/log/Index.vue') } ] } ] } ] export default systemRoute <file_sep>/vuepack/docs/electron.md # Electron app **Hot reloading also works in your Electron app!** If you enable Electron support during the setup, it's a little different to develop the app: ```bash # same as regular app $ npm run dev $ npm run build # open your electron app by running: $ npm run app ``` **Note:** In Electron mode, if you open http://localhost:4000 in browser you will get a `require is not defined` error or something similar, because we're using webpack target `electron-renderer`, native modules like `querystring` or `electron` won't be "browserified" when you `require` them. <file_sep>/vuepack/docs/babel.md # Babel By default, we're using the official [babel-preset-vue-app](https://github.com/vuejs/babel-preset-vue-app). ```json { "presets": [ ["vue-app", { "useBuiltIns": true }] ] } ``` You can update `babel` field in `package.json` to use custom presets and plugins. <file_sep>/vue-custom-webpack-single-spa/src/views/system/api/system/userAuth.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' let serverName = urls.system // let serverName = urls.Mock export function getNextOrgList(orgCode) { //获取下级机构列表,最末级为人员 return http.get(`${serverName}system/org/v1.0/${orgCode}/next/all`) } export function getNextDwList(orgCode) { //获取下级机构列表,最末级为单位 return http.get(`${serverName}system/org/v1.0/${orgCode}/next/dw`) } export function getPostPersonList(orgCode) { //获取岗位下人员列表 return http.get(`${serverName}system/user/v1.0/sysUser/hr/${orgCode}`) } export function getAuthorizeList(orgCode) { // 获取组织下人员 return http.get(`${serverName}system/user/v1.0/sysUser/local/${orgCode}`) } export function getPageAuthorizeList(data) { //分页获取人员 return http.post(`${serverName}system/user/v1.0/sysUsers`, data) } export function addMember(data) { //添加人员 return http.post(`${serverName}system/user/v1.0/sysUser`, data) } export function delPersonList(data) { //data为数组拼接字符串 return http.delete(`${serverName}system/user/v1.0/sysUser?ids=${data}`) } export function getOneselfTree(personID) { //TODO: 改为传[] return http.post(`${serverName}system/user/v1.0/sysUser/${personID}`) } export function getPermissionList() { //获取所有权限分类 return http.get(`${serverName}system/user/v1.0/auth/query`) } export function getPersonList(orgCode) { // 获取组织下人员 return http.get(`${serverName}system/user/v1.0/sysUser/hr/${orgCode}`) } export function postSearchPersonList(data) { // 模糊搜索组织下人员 return http.post(`${serverName}system/user/v1.0/mosaic`, data) } export function updateAuthorize(data) { //添加用户授权 return http.post(`${serverName}system/user/v1.0/auth/grant`, data) } export function deleteAuthorize(data) { //删除用户权限 return http.delete(`${serverName}system/user/v1.0/auth/deprive?mappingids=${data}`) } export function getSysUser(data) { return http.get(`${serverName}system/user/v1.0/sysUsers`, data) } <file_sep>/vue-faster-vux(配置vux_rem)/src/assets/js/remAdapt.js class RemAdapt { constructor() { this.rem = "100px"; this.scale = 1.0; this.init(); } init() { window.addEventListener("load", () => { this.setScale(); //先设置scale再设置rem可以修复获取deviceWidth不一致的BUG this.setRem(); // console.log("load"); }); window.addEventListener("resize", () => { this.setScale(); this.setRem(); // console.log("resize!"); }); } setRem() { // let deviceWidth = document.documentElement.clientWidth > 1300 ? 1300 : document.documentElement.clientWidth; // let deviceWidth = document.documentElement.clientWidth; //layout viewport let deviceWidth = window.innerWidth; //获取设备屏幕宽度,visual viewport //idea viewport,设备理想宽度,即实际宽度 this.rem = (deviceWidth / 3.75) + "px"; //已iPhone6为设计稿(宽度为750px),设置1rem=200px, //【可以使得无需将设计稿减半】; document.documentElement.style.fontSize = this.rem; console.log("deviceWidth=", deviceWidth, ",rem=", this.rem); } setScale() { //自动设置scale值,如果DPR(设备像素比)>2.0则=2,用于直接使用设计稿标注,而不用取半 this.scale = 1 / devicePixelRatio; // let viewportContentArray = ["initial-scale=", scale, ",maximum-scale=", scale, ",minimum-scale=", scale, ",user-scalable=no"]; // let viewportContent = viewportContentArray.join(''); let viewportContent = `initial-scale=${this.scale},maximum-scale=${this.scale},minimum-scale=${this.scale},user-scalable=no`; console.log("scale=", this.scale); console.log("devicePixelRatio=", devicePixelRatio); document.querySelector('meta[name="viewport"]').setAttribute('content', viewportContent); } } // let _rem = new RemAdapt(); export default { RemAdapt }<file_sep>/vue-custom-webpack-template(ts)/src/store/index.d.ts import { GetterTree, ActionTree, MutationTree, ModuleTree } from 'vuex' export interface Module<S, R> { namespaced?: boolean state?: S | (() => S) getters?: GetterTree<S, R> actions?: ActionTree<S, R> mutations?: MutationTree<S> modules?: ModuleTree<R> } <file_sep>/vue-custom-webpack-single-spa/src/views/system/category/Category.d.ts declare namespace NCategory { export interface CategoryInfo { id: number categoryName: string categoryCode: string isLeaf: boolean | string isUse: boolean remark?: string children?: CategoryInfo[] | null } export interface CategoryDetail { id: number detailName?: string detailCode: string detailSort: string categoryId?: string | null isLeaf: boolean | string isNull?: boolean children?: CategoryDetail[] | null } } // export default NCategory <file_sep>/vue-ssr-template-ts-webpack/src/components/waterFall/index.ts import Waterfall from './waterfall.vue' import WaterfallSlot from './waterfall-slot.vue' module.exports = { Waterfall: Waterfall, WaterfallSlot: WaterfallSlot, waterfall: Waterfall, waterfallSlot: WaterfallSlot } <file_sep>/vue-custom-webpack-template(ts)/src/store/modules/message.ts import { VuexModule, Module, Mutation, Action } from 'vuex-module-decorators' import { getMessageList } from '@/api/common' import { get } from 'lodash' import { Notification } from 'element-ui' @Module({ namespaced: true, name: 'Message' }) class Message extends VuexModule { message_list: any[] = [] current_message_page: number = 1 message_total: number = 0 @Mutation SET_MESSAGE_LIST(payload) { this.message_list = payload } @Mutation SET_CURRENT_MESSAGE_PAGE(payload) { this.current_message_page = payload } @Mutation SET_MESSAGE_TOTAL(payload) { this.message_total = payload } //======================获取通知信息========================== @Action async COMMIT_MESSAGE_LIST() { let { commit } = this.context try { let params = { current: this.current_message_page, size: 1 } const res = await getMessageList(params) let messageList = get(res, 'data.records', []) const messageTotal = get(res, 'data.total', 0) commit('SET_MESSAGE_LIST', messageList) commit('SET_MESSAGE_TOTAL', messageTotal) } catch (e) { Notification.error(`获取通知消息失败: ${e.message}`) commit('SET_MESSAGE_LIST', []) } } } export default Message <file_sep>/vuepack/docs/pwa.md # Progressive Web App A [progressive web app](https://developers.google.com/web/progressive-web-apps/) can work **offline**, **add to homescreen** and even more performance wins! VuePack is using [offline-plugin](https://github.com/NekR/offline-plugin) so that your project will become offline ready by caching all (or some) of the webpack output assets. The offline-plugin is only used in production environment, so no need to worry about the cache during development ;) Check out [./client/pwa.js](https://github.com/egoist/vuepack/blob/master/template/client/pwa.js) / [build/webpack.prod.js](https://github.com/egoist/vuepack/blob/master/template/build/webpack.prod.js#L51-L57) and [offline-plugin](https://github.com/NekR/offline-plugin) to know more. --- To disable PWA support, simply remove [this](https://github.com/egoist/vuepack/blob/master/template/client/index.js#L4-L7) and [this](https://github.com/egoist/vuepack/blob/master/template/build/webpack.prod.js#L49-L57). <file_sep>/vue-custom-webpack-template(ts)/src/mock/user.ts import Mock from 'mockjs' // import qs from 'qs' // import { parseUrl } from './utils.ts' import apiData from './data' let User = { getTreeLevel0: options => { // console.log(options) // let params = options let orgCode = options.url.match(/mockjs\/sys\/org\/v1\.0\/(\d+)\/next\/all/)[1] // let parmas = parseUrl(options.url) // console.log(orgCode) let data = null switch (orgCode) { case '00001': data = Mock.mock({ id: 1, sequence_number: 1, danweicengji: '100101', jiancheng: '中国铁建', leixing: 'danwei', leixingmingcheng: '单位', paixuma: 1, quancheng: '中国铁建', shangjizhujian: '1', xunizuzhi: false, zhujian: '986436', zuzhibianma: '00001', zuzhilujing: '中国铁建股份总公司' }) break case '0000100001': data = Mock.mock([ { danweicengji: "@order('100101','100102','100102','100102','100102','100102')", jiancheng: "@order('中土集团','十一局','十八局','十九局','网信科技')", leixing: "@order('danwei','danwei','danwei','danwei','danwei','danwei')", leixingmingcheng: "@order('单位','单位','单位','单位','单位','单位')", paixuma: '@order(1,3,5,19,21,91)', quancheng: "@order('中国土木工程集团有限公司','中铁十一局集团有限公司','中铁十八局集团有限公司','中铁十九局集团有限公司','中铁建网络信息科技有限公司')", sequence_number: '', shangjizhujian: "@order('1','1','1','1','1','1')", xunizuzhi: '@order(false,false,false,false,false,false)', zhujian: "@order('986436','1117553','1118193','1118184','1041228','1178609')", zuzhibianma: "@order('0000100001','0000100010','0000100011','0000100018','0000100019','0000100054')", zuzhilujing: "@order('中国铁建中土集团','中国铁建十一局','中国铁建十八局','中国铁建十九局','中国铁建网信科技')" } ]) break } let response = { data: data, msg: '', success: true } return response }, getPageAuthorizeList: options => { // console.log(options) let data = Mock.mock({ asc: true, condition: 1, current: 1, limit: 2147483647, offset: 0, offsetCurrent: 0, openSort: true, orderByField: 1, pages: 1, records: [ { createPerson: 1, createTime: 1, enabled: 1, id: '1231231231321321321', orgCode: 1, orgName: 1, orgShortname: 1, personId: '123456', personIdentity: 1, personName: '王浩', postFullname: 1, postId: 1, postName: '研发部长', updatePerson: 1, updateTime: 1, version: 1 } ], searchCount: true, size: 20, total: 1 }) let response = { data: data, msg: '', success: true } return response }, getPermissionList: options => { // console.log(options) let data = Mock.mock([ { permissionCode: '1212', permissionID: '123', permissionName: '管理' }, { permissionCode: '1213', permissionID: '124', permissionName: '编辑' } ]) let response = { data: data, msg: '', success: true } return response }, getWholeTree: options => { // console.log(options) // let data = Mock.mock(apiData[0]) let response = { data: apiData[0], msg: '', success: true } return response }, getUserInfo: options => { // console.log(options) let response = apiData[2] return response }, getSysMenu: options => { // console.log(options) let response = { data: [{ children: apiData[1] }], msg: '', success: true } return response } } export default User <file_sep>/vue-ssr-template-ts-webpack/README.md [# vue-typescript ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Run your tests ``` npm run test ``` ### Lints and fixes files ``` npm run lint ``` ### Run your unit tests ``` npm run test:unit ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). ](# guide-frontend 开发者指南系统-前端代码 运行步骤: 1. ### 安装依赖 ```bash cnpm i ``` 2. ### 修改文件 ``` 1、src/libs/urls.js中 dev更换为开发环境值url, Mock设置为'', pro 的值,更换为生产环境(在线环境)中能访问的接口地址。 ``` ```js const urls = { dev: 'http://10.1.4.233:9090/openid-service', //开发环境中使用的接口地址 pro: 'http://172.16.31.10:8081/exam-server',//生产环境中使用的接口地址 openId: 'https://g1openid.crcc.cn', //获取openId的请求地址, Mock: 'mockjs/', //本地'mockjs'前缀,设为''可替换为dev服务器 RAPMock: 'mock-rap' //RAP mock服务器前缀 } export default urls ``` 3. ### 运行项目 ```bash npm run serve ``` ### 打包构建项目 ```bash npm run build ``` ># ESLint语法规范 * **使用两个空格**进行缩进。 * 句尾**不添加分号** * **下列情况需在句首添加分号**。 ```js ;(function () { console.log('ok') }()) ;[1, 2, 3].forEach(bar) ;`hello`.indexOf('o') ``` * 除需要转义的情况外,**HTML内使用双引号, `<script></script>`内使用单引号**。 * **不允许定义不使用的变量**。 * **对于变量和函数名统一使用驼峰命名法**。 ```js var myVar = 'hello' // ✓ ok function myFunction () { } // ✓ ok function my_function () { } // ✗ avoid var my_var = 'hello' // ✗ avoid ``` * **始终使用** `===` 替代 `==`。<br> 例外: `obj == null` 可以用来检查 `null || undefined`。 * **避免不必要的布尔转换**。 ```js if(!!res){} //bad if(res){} //good ``` * **不允许有连续多行空行**。 * 标签使用**小写横杠连接** 或 **所有首字母大写**。 ```HTML <router-view></router-view> // ✓ ok <<RouterView /> // ✓ ok ``` * **多属性时应该换行显示**。 ```HTML <el-table :data="tableData" border stripe style="width: 100%" v-loading="store.state.User.loading"> </el-table> // ✓ ok <el-table :data="tableData" border stripe style="width: 100%"></el-table> // ✗ avoid ``` * **组件必须有name属性**。 ```js export default { name: "UserTree", props: { }, ... // ✓ ok export default { props: { }, ... // ✗ avoid ``` * **props每个对象需要有默认值**。 ```js props: { treeType: { type: String, default: 'side' } }, ... // ✓ ok export default { props: { treeType: String }, ... // ✗ avoid ``` * **使用v-for时必须设置:key**。 ```html <ul class="icons-list"> <li v-for="data in iconData" :key="data.label"></li> </ui> // ✓ ok <ul class="icons-list"> <li v-for="data in iconData"></li> </ui> // ✗ avoid ``` * **必须处理**异常处理中`err`参数。 ```js // ✓ ok run(function (err) { if (err) throw new Error(err) console.log('done') }) ``` ```js // ✗ avoid run(function (err) { console.log('done') }) ``` * **取对象属性前需先对对象是否存在**进行判断,避免报错导致代码异常,例如: ```js let position = this.userInfo.position // ✗ avoid let position = this.userInfo && this.userInfo.position // ✓ ok ``` vue-markDown----使用方法: https://github.com/hinesboy/mavonEditor )<file_sep>/vue-ssr-template-ts-webpack/src/router/index.ts import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default function createRouter() { return new Router({ mode: 'history', routes: [ { path: '/', redirect: '/home' }, { path: '/home', name: 'Home', component: () => import('../views/Home.vue') }, { path: '/login', name: 'login', component: () => import('../views/login.vue') }, { path: '/waterfall', name: 'waterfall', component: () => import('@/components/WaterFall-scroll.vue') } ] }) } // Router.prototype.back = function back() { // this.back = true // this.go(-1) // } <file_sep>/vue-custom-webpack-template(ts)/src/views/system/api/system/log.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' let serverName= urls.system //日志管理 export function getLogList(params) { return http.post(`${serverName}system/log/v1.0/log`, params) } <file_sep>/vuepack/docs/jsx.md ## JSX components By default, you can also write your components by using `render` function and jsx, but you may also notice there's a `JSX format` option in command-line prompt when your are initializing a new project: <img src="https://ooo.0o0.ooo/2016/09/09/57d22be6583fa.png" width="500"> If you enable this the `vue-cli` won't generate `.vue` components but `.js` components. Either way you can use JSX and single-file components. <file_sep>/vue-custom-webpack-template(ts)/src/mock/data.ts let json = [ //-- [ { id: '98e6850107e511e995e36139581a8568', categoryCode: 'project', categoryName: '项目字典', categorySort: '01', parentId: '0', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [ { id: 'aa6ca51307e611e995e3437d7e2ff510', categoryCode: 'project_member', categoryName: '项目成员', categorySort: '01', parentId: '98e6850107e511e995e36139581a8568', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '86f34e7507e811e995e37fe40aa365e1', categoryId: 'aa6ca51307e611e995e3437d7e2ff510', detailName: '项目开发者', detailCode: 'project_m_50', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'a345370607e811e995e3a58527ce1962', categoryId: 'aa6ca51307e611e995e3437d7e2ff510', detailName: '项目访客', detailCode: 'project_m_10', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '6e8f41e407e811e995e357d3da5cfd51', categoryId: 'aa6ca51307e611e995e3437d7e2ff510', detailName: '项目负责人', detailCode: 'project_m_99', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] } ], details: [] }, { id: '<KEY>', categoryCode: 'api', categoryName: 'api字典', categorySort: '02', parentId: '0', isUse: 1, isLeaf: 1, remark: '保存api状态列表', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [ { id: 'e33b4acc072c11e9acc79752536daac6', categoryCode: 'api_type', categoryName: '接口类型', categorySort: '3', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '3a03c8b1072d11e9acc715e1c7a9e4ac', categoryId: 'e33b4acc072c11e9acc79752536daac6', detailName: '私有', detailCode: '2', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '2ea70040072d11e9acc7e7be862bfcfc', categoryId: 'e33b4acc072c11e9acc79752536daac6', detailName: '公有', detailCode: '1', detailSort: '0', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: '0b8cf28d072d11e9acc71da98af13cb4', categoryCode: 'api_protocol', categoryName: 'api协议类型', categorySort: '4', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '19f3035e072d11e9acc7d1ad8e0a525b', categoryId: '0b8cf28d072d11e9acc71da98af13cb4', detailName: 'HTTP', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '<KEY>', categoryId: '0b8cf28d072d11e9acc71da98af13cb4', detailName: 'HTTPS', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: 'f3754db5072b11e9acc761f06df012ba', categoryCode: 'status', categoryName: '接口状态', categorySort: '0', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '4563ed3112e811e998825f5e8452cae4', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '维护', detailCode: '2', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '5025871312e811e99882a5653a20c576', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '测试', detailCode: '4', detailSort: '4', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '4b315ea212e811e<KEY>', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '开发', detailCode: '3', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '67769d0512e811e9988251f2cd5a45c6', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '弃用', detailCode: '6', detailSort: '6', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '1c140406072c11e9acc769d57f68ca72', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '待定', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 0, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '6ca3afc612e811e99882c3005898801d', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '调试', detailCode: '7', detailSort: '7', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '590da60412e811e998827dc2f0391c7e', categoryId: 'f3754db5072b11e<KEY>012ba', detailName: '规划', detailCode: '5', detailSort: '5', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '<KEY>', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: 'BUG', detailCode: '8', detailSort: '8', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '2dc6f5e7072c11e9acc7715<KEY>', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '启用', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 0, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: 'd0862b2b072c11e9acc737efb7d84a18', categoryCode: 'api_short', categoryName: '接口缩写', categorySort: '2', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: 'api请求缩写', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '1eb15a0812e911e998826d79258a43ce', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'POST', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '471180bc12e911e9988233859139898e', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'OPTS', detailCode: '5', detailSort: '5', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '3ea596ab12e911e99882b1fe86374b2b', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'HEAD', detailCode: '4', detailSort: '4', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '<KEY>', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'DEL', detailCode: '3', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '590d3b6d12e911e99882a904b4673fab', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'PATCH', detailCode: '6', detailSort: '6', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '114e054e07ed11e9a2f5a1d4fd18f5fb', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'GET', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 0, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '2465ec4912e911e998826554efbfb304', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'PUT', detailCode: '2', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: '79e1b008072c11e9acc71d83be57680d', categoryCode: 'request', categoryName: '请求类型', categorySort: '1', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: 'api请求类型', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: 'e26eacaf12e711e998821be251c51d20', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'OPTIONS', detailCode: '5', detailSort: '5', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'e98a972012e711e99882714de24dc72a', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'PATCH', detailCode: '6', detailSort: '6', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '<KEY>', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'PUT', detailCode: '2', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '9fe60c69072c11e9acc72b38ef07130c', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'GET', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '99591c3d12e711e99882a5d8d1f8fe0d', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'DELETE', detailCode: '3', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'c903694e12e711e99882c5fb09063244', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'HEAD', detailCode: '4', detailSort: '4', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'a84c030a072c11e9acc7cd10e27f35d6', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'POST', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] } ], details: [] } ], //系统菜单 [ { id: '57c2a1570b4611e9a41965edb94c593d', code: '0101', menuTitle: '菜单管理', menuIcon: 'el-icon-tb-list', menuPath: '/system/menus', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'menus', menuSort: '1', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T06:56:29.000+0000', version: null, children: [], index: 0 }, { id: '79c34fc80b4611e9a41997ce89591dba', code: '0102', menuTitle: '数据字典', menuIcon: 'el-icon-tb-search', menuPath: '/system/category', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'category', menuSort: '2', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T06:56:38.000+0000', version: null, children: [], index: 1 }, { id: '957f12d90b4611e9a419bf4591c0785a', code: '0103', menuTitle: '人员管理', menuIcon: 'el-icon-tb-friend', menuPath: '/system/user', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'user', menuSort: '3', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T09:22:55.000+0000', version: null, children: [], index: 2 }, { id: '<KEY>', code: '0105', menuTitle: '流程管理', menuIcon: 'el-icon-circle-check-outline', menuPath: '/system/process', menuRegular: null, menuRouteName: 'process', menuSort: '4', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-31T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:32.000+0000', version: null, children: [], index: 3 }, { id: 'a218ef2a0b4611e9a419c58acff119c0', code: '0104', menuTitle: '日志管理', menuIcon: 'el-icon-tb-info', menuPath: '/system/log', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'log', menuSort: '5', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:44.000+0000', version: null, children: [], index: 4 } ], //userInfo -管理+编辑 { success: true, msg: '调用接口成功', data: { sub: 'hr|987837', id: '987837', userName: '张三', posts: [ { jiancheng: '处长', quancheng: '处长', sequence_number: null, shifouzhugangwei: true, zuzhibianma: '000010000104000770198800399001', zuzhilujing: '/中国铁建/股份公司/机关/信息化管理部/基础平台处/处长' }, { jiancheng: '待分配人员', quancheng: '待分配人员', sequence_number: null, shifouzhugangwei: false, zuzhibianma: '000010000100005010007700199001', zuzhilujing: '/中国铁建/股份公司/测试单位5/机关/测试部门5/待分配人员' } ], manage: [ { danweicengji: '100101', jiancheng: '中国铁建', leixing: 'danwei', leixingmingcheng: '单位', paixuma: 1, quancheng: '中国铁建股份有限公司', sequence_number: null, shangjizhujian: '0', xunizuzhi: false, zhujian: '1', zuzhibianma: '00001', zuzhilujing: '中国铁建', id: 1 } ], edit: [ { danweicengji: '100101', jiancheng: '中国铁建', leixing: 'danwei', leixingmingcheng: '单位', paixuma: 1, quancheng: '中国铁建股份有限公司', sequence_number: null, shangjizhujian: '0', xunizuzhi: false, zhujian: '1', zuzhibianma: '00001', zuzhilujing: '中国铁建', id: 1 } ], menus: [] } }, //userInfo -无管理\编辑 { success: true, msg: '调用接口成功', data: { sub: 'hr|987837', id: '987837', userName: '张三', posts: [ { jiancheng: '处长', quancheng: '处长', sequence_number: null, shifouzhugangwei: true, zuzhibianma: '000010000104000770198800399001', zuzhilujing: '/中国铁建/股份公司/机关/信息化管理部/基础平台处/处长' }, { jiancheng: '待分配人员', quancheng: '待分配人员', sequence_number: null, shifouzhugangwei: false, zuzhibianma: '000010000100005010007700199001', zuzhilujing: '/中国铁建/股份公司/测试单位5/机关/测试部门5/待分配人员' } ], menus: [] } }, //项目列表 { offset: 0, limit: 2147483647, total: 3, size: 5, pages: 1, current: 1, searchCount: true, openSort: true, orderByField: null, records: [ { id: '62d160c3157011e991bdb57a3df74659', orgCode: '000010001101', orgName: '机关', remark: '修改时间:2019.01.11', version: 2, projectName: 'API项目(改)', projectVersion: '1.1', projectDescription: 'API项目作为。。。', projectState: 0, createPerson: '张三', createTime: '2019-01-11T07:13:25.000+0000', updatePerson: '张三', updateTime: '2019-01-11T07:14:47.000+0000', detailCode: 'project_m_99' }, { id: 'e3b67f29154711e99845dda34f165c62', orgCode: '000010005401000770198800399001', orgName: '处长', remark: '备注', version: 1, projectName: '开发者中心', projectVersion: 'v1.0', projectDescription: '开发者', projectState: 0, createPerson: '987837', createTime: '2019-01-11T02:23:32.000+0000', updatePerson: null, updateTime: null, detailCode: null }, { id: 'f21f406d157211e991bdfdda24c0a1a7', orgCode: '0000100011', orgName: '中铁十一局', remark: '', version: 1, projectName: '测试项目1-1', projectVersion: 'v0.1', projectDescription: '测试项目1-1', projectState: 0, createPerson: '张三', createTime: '2019-01-11T07:31:44.000+0000', updatePerson: null, updateTime: null, detailCode: 'project_m_99' } ], condition: null, asc: true, offsetCurrent: 0 }, //所有菜单 { success: true, msg: '调用接口成功', data: [ { id: '<KEY>', code: '01', menuTitle: '系统', menuIcon: 'el-icon-setting', menuPath: '/system', menuRegular: '^/system/menu$', menuRouteName: null, menuSort: '1', parentCode: null, inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-22T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-02T06:29:29.000+0000', version: null, children: [ { id: 'd38c16140e7011e9b8fb35eeb048c9d9', code: '0105', menuTitle: '流程管理', menuIcon: 'el-icon-circle-check-outline', menuPath: '/system/process', menuRegular: null, menuRouteName: 'process', menuSort: '4', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-31T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:32.000+0000', version: null, children: [] }, { id: '<KEY>b4611e9a419bf4591c0785a', code: '0103', menuTitle: '人员管理', menuIcon: 'el-icon-tb-friend', menuPath: '/system/user', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'user', menuSort: '3', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T09:22:55.000+0000', version: null, children: [] }, { id: 'a218ef2a0b4611e9a419c58acff119c0', code: '0104', menuTitle: '日志管理', menuIcon: 'el-icon-tb-info', menuPath: '/system/log', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'log', menuSort: '5', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:44.000+0000', version: null, children: [] }, { id: '57c2a1570b4611e9a41965edb94c593d', code: '0101', menuTitle: '菜单管理', menuIcon: 'el-icon-tb-list', menuPath: '/system/menus', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'menus', menuSort: '1', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T06:56:29.000+0000', version: null, children: [] }, { id: '79c34fc80b4611e9a41997ce89591dba', code: '0102', menuTitle: '数据字典', menuIcon: 'el-icon-tb-search', menuPath: '/system/category', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'category', menuSort: '2', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T06:56:38.000+0000', version: null, children: [] } ] }, { id: 'd51211bc0b4911e9a419435c242c2228', code: '03', menuTitle: 'API菜单', menuIcon: null, menuPath: null, menuRegular: null, menuRouteName: null, menuSort: '2', parentCode: null, inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-29T09:12:17.000+0000', updatePerson: null, updateTime: null, version: null, children: [ { id: '3529adc00b4a11e9a419d981ea8eb6ec', code: '0304', menuTitle: '成员', menuIcon: 'el-icon-tb-friend', menuPath: '/member', menuRegular: '^\\/project\\/[\\d\\w]+\\/member', menuRouteName: 'projectMemberList', menuSort: '5', parentCode: '03', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-02T09:16:17.000+0000', version: null, children: [] }, { id: '04b92a7d0b4a11e9a4191d82a54ac879', code: '0301', menuTitle: '概况', menuIcon: 'el-icon-aly-shujukanban', menuPath: '/project', menuRegular: '^\\/project\\/[\\d\\w]+$', menuRouteName: 'projectGeneral', menuSort: '1', parentCode: '03', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-26T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-02T06:42:52.000+0000', version: null, children: [] }, { id: '130a7ace0b4a11e9a4192508093d9729', code: '0302', menuTitle: '接口', menuIcon: 'el-icon-aly-APIshuchu', menuPath: '/api', menuRegular: '^\\/project\\/[\\d\\w]+\\/api', menuRouteName: 'projectApiList', menuSort: '2', parentCode: '03', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-02T06:43:09.000+0000', version: null, children: [] }, { id: '43f7a8210b4a11e9a419e7bab1459839', code: '0305', menuTitle: '管理', menuIcon: 'el-icon-tb-settings', menuPath: '/manage', menuRegular: '^\\/project\\/[\\d\\w]+\\/manage', menuRouteName: 'projectManage', menuSort: '6', parentCode: '03', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-02T09:16:25.000+0000', version: null, children: [] } ] } ] }, //数据字典 { success: true, msg: '调用接口成功', data: [ { id: '98e6850107e511e995e36139581a8568', categoryCode: 'project', categoryName: '项目字典', categorySort: '01', parentId: '0', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [ { id: 'aa6ca51307e611e995e3437d7e2ff510', categoryCode: 'project_member', categoryName: '项目成员', categorySort: '01', parentId: '98e6850107e511e995e36139581a8568', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '86f34e7507e811e995e37fe40aa365e1', categoryId: 'aa6ca51307e611e995e3437d7e2ff510', detailName: '项目开发者', detailCode: 'project_m_50', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'a345370607e811e995e3a58527ce1962', categoryId: 'aa6ca51307e611e995e3437d7e2ff510', detailName: '项目访客', detailCode: 'project_m_10', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '6e8f41e407e811e995e357d3da5cfd51', categoryId: 'aa6ca51307e611e995e3437d7e2ff510', detailName: '项目负责人', detailCode: 'project_m_99', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] } ], details: [] }, { id: 'cfed3bf4072b11e9acc73f6bbecdcff8', categoryCode: 'api', categoryName: 'api字典', categorySort: '02', parentId: '0', isUse: 1, isLeaf: 1, remark: '保存api状态列表', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [ { id: 'e33b4acc072c11e9acc79752536daac6', categoryCode: 'api_type', categoryName: '接口类型', categorySort: '3', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '3a03c8b1072d11e9acc715e1c7a9e4ac', categoryId: 'e33b4acc072c11e9acc79752536daac6', detailName: '私有', detailCode: '2', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '2ea70040072d11e9acc7e7be862bfcfc', categoryId: 'e33b4acc072c11e9acc79752536daac6', detailName: '公有', detailCode: '1', detailSort: '0', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: '<KEY>', categoryCode: 'api_protocol', categoryName: 'api协议类型', categorySort: '4', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '19f3035e072d11e9acc7d1ad8e0a525b', categoryId: '0b8cf28d072d11e9acc71da98af13cb4', detailName: 'HTTP', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '21545b3f072d11e9acc<KEY>', categoryId: '0b8cf28d072d11e9acc71da98af13cb4', detailName: 'HTTPS', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: 'f3754db5072b11e9acc761f06df012ba', categoryCode: 'status', categoryName: '接口状态', categorySort: '0', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: '', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '4563ed3112e811e998825f5e8452cae4', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '维护', detailCode: '2', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '5025871312e811e99882a5653a20c576', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '测试', detailCode: '4', detailSort: '4', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '4b315ea212e811e<KEY>', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '开发', detailCode: '3', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '67769d0512e811e9988251f2cd5a45c6', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '弃用', detailCode: '6', detailSort: '6', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '1c140406072c11e9acc769d57f68ca72', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '待定', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 0, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '6ca3afc612e811e99882c3005898801d', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '调试', detailCode: '7', detailSort: '7', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '590da60412e811e998827dc2f0391c7e', categoryId: 'f3754db5072b11e<KEY>', detailName: '规划', detailCode: '5', detailSort: '5', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '7563110712e811e998<KEY>2', categoryId: 'f375<KEY>e<KEY>', detailName: 'BUG', detailCode: '8', detailSort: '8', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '2dc6f5e7072c11e9acc77159df0984d9', categoryId: 'f3754db5072b11e9acc761f06df012ba', detailName: '启用', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 0, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: 'd0862b2b072c11e9acc737efb7d84a18', categoryCode: 'api_short', categoryName: '接口缩写', categorySort: '2', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: 'api请求缩写', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: '1eb15a0812e911e998826d79258a43ce', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'POST', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '471180bc12e911e9988233859139898e', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'OPTS', detailCode: '5', detailSort: '5', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '3ea596ab12e911e99882b1fe86374b2b', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'HEAD', detailCode: '4', detailSort: '4', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '<KEY>', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'DEL', detailCode: '3', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '590d3b6d12e911e99882a904b4673fab', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'PATCH', detailCode: '6', detailSort: '6', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '114e054e07ed11e9a2f5a1d4fd18f5fb', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'GET', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 0, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '2465ec4912e911e998826554efbfb304', categoryId: 'd0862b2b072c11e9acc737efb7d84a18', detailName: 'PUT', detailCode: '2', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] }, { id: '79e1b008072c11e9acc71d83be57680d', categoryCode: 'request', categoryName: '请求类型', categorySort: '1', parentId: 'cfed3bf4072b11e9acc73f6bbecdcff8', isUse: 1, isLeaf: 1, remark: 'api请求类型', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [], details: [ { id: 'e26eacaf12e711e998821be251c51d20', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'OPTIONS', detailCode: '5', detailSort: '5', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'e98a972012e711e99882714de24dc72a', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'PATCH', detailCode: '6', detailSort: '6', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '<KEY>', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'PUT', detailCode: '2', detailSort: '2', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '9fe60c69072c11e9acc72b38ef07130c', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'GET', detailCode: '0', detailSort: '0', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: '99591c3d12e711e99882a5d8d1f8fe0d', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'DELETE', detailCode: '3', detailSort: '3', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'c903694e12e711e99882c5fb09063244', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'HEAD', detailCode: '4', detailSort: '4', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] }, { id: 'a84c030a072c11e9acc7cd10e27f35d6', categoryId: '79e1b008072c11e9acc71d83be57680d', detailName: 'POST', detailCode: '1', detailSort: '1', isUse: 1, isLeaf: 1, parentDetailId: '0', createPerson: null, createTime: null, updatePerson: null, updateTime: null, version: null, children: [] } ] } ], details: [] } ] }, //项目信息1 { msg: '成功!', code: 1, data: { id: 'f21f406d157211e991bdfdda24c0a1a7', orgCode: '0000100011', orgName: '中铁十一局', projectDescription: 'API项目(改)', projectName: 'API项目(改)', projectState: 0, projectVersion: 'v0.1', remark: '', createPerson: '张三', updatePerson: null, version: 1, apiInfoCount: 0, stateCount: 5, memberCount: 5, detailCode: 'project_m_99', memberId: null }, success: true, appcode: 1 }, //项目信息2 { msg: '成功!', code: 1, data: { id: 'f21f406d157211e991bdfdda24c0a1a7', orgCode: '0000100011', orgName: '中铁十一局', projectDescription: '开发者中心', projectName: '开发者中心', projectState: 0, projectVersion: 'v0.1', remark: '', createPerson: '张三', updatePerson: null, version: 1, apiInfoCount: 0, stateCount: 5, memberCount: 5, detailCode: 'project_m_50', memberId: null }, success: true, appcode: 1 }, //项目信息3 { msg: '成功!', code: 1, data: { id: 'f21f406d157211e991bdfdda24c0a1a7', orgCode: '0000100011', orgName: '中铁十一局', projectDescription: '测试项目1-1', projectName: '测试项目1-1', projectState: 0, projectVersion: 'v0.1', remark: '', createPerson: '张三', updatePerson: null, version: 1, apiInfoCount: 0, stateCount: 5, memberCount: 5, detailCode: 'project_m_10', memberId: null }, success: true, appcode: 1 }, //系统菜单 [ { id: '57c2a1570b4611e9a41965edb94c593d', code: '0101', menuTitle: '菜单管理', menuIcon: 'el-icon-tb-list', menuPath: '/system/menus', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'menus', menuSort: '1', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T06:56:29.000+0000', version: null, children: [], index: 0 }, { id: '<KEY>', code: '0106', menuTitle: '数据字典', menuIcon: 'el-icon-tb-search', menuPath: '/system/category', menuRegular: null, menuRouteName: 'category', menuSort: '2', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2019-01-21T09:28:29.000+0000', updatePerson: null, updateTime: null, version: null, children: [], index: 1 }, { id: '957f12d90b4611e9a419bf4591c0785a', code: '0103', menuTitle: '人员管理', menuIcon: 'el-icon-tb-friend', menuPath: '/system/user', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'user', menuSort: '3', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T09:22:55.000+0000', version: null, children: [], index: 2 }, { id: '<KEY>', code: '0105', menuTitle: '流程管理', menuIcon: 'el-icon-circle-check-outline', menuPath: '/system/process', menuRegular: null, menuRouteName: 'process', menuSort: '4', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-31T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:32.000+0000', version: null, children: [], index: 3 }, { id: 'a218ef2a0b4611e9a419c58acff119c0', code: '0104', menuTitle: '日志管理', menuIcon: 'el-icon-tb-info', menuPath: '/system/log', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'log', menuSort: '5', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:44.000+0000', version: null, children: [], index: 4 } ] ] export default json //获取项目信息 <file_sep>/vue-custom-webpack-single-spa/src/store/modules/index.ts const modules: any = {} export default modules <file_sep>/vue-custom-webpack-template(ts)/README.md **webpack4.x实现vue+ts完全自定义打包配置** ----------------------------------------- vue-cli进入3.0以来,其打包的配置被隐藏到了`@vue/cli-service`包里,webpack配置的修改用户只能通过`vue.config.js`进行合并配置。 ```js "@vue/babel-preset-app": "^3.8.0", "@vue/cli-plugin-babel": "^3.3.0", "@vue/cli-plugin-eslint": "^3.3.0", "@vue/cli-plugin-typescript": "^3.3.0", "@vue/cli-service": "^3.8.0", //vue-cli脚手架的各种命令 ``` 这种模式虽然极大的简化了开发人员的项目配置,但对于想提升自我的前端来说,无疑是不太友好的。 下面我把自己自定义webpack打包配置的经验,总结一下给各位,以供大家参考指正: ![webpack配置1](https://user-gold-cdn.xitu.io/2019/6/11/16b45e9dd754750b?w=219&h=84&f=jpeg&s=4408) 虽然webpack配置较为繁杂,但只要掌握了规律,写起配置就没那么头大了,而且webpack经过这几年的发展也有了[中文文档 ![webpack中文文档](https://user-gold-cdn.xitu.io/2019/6/11/16b45f566c5756a0?w=262&h=441&f=jpeg&s=22477)](https://www.webpackjs.com/concepts/) > ### 总结起来就是四个方面的配置: * 出入口配置 * 文件名自动解析配置 * 各种文件对应的loader配置 * webpack插件 ----------------------------------------------------- 以下面这段配置(`webpack.base.js`)为例: ```js ...... //省略了各模块的引入 module.exports = { mode: isProduction ? 'production' : 'development', //打包类型,webpack4.x新增 context: path.resolve(__dirname, '../'), entry: './src/main.ts', //打包的入口文件,这里使用了.ts output: { path: path.resolve(__dirname, '../dist'), //打包后的输出文件 chunkFilename: 'js/[name]-[contenthash:8].js', //打包后的文件命名规则 //这里是表示放在js下的原来名称+内容8位hash码 publicPath: '/' //打包后文件的引用路径,默认为当前路径'/' }, ....... ``` 上面这段配置就是webpack最基础的,打包`入口/出口`配置。 > 还有常用的自动文件后缀名解析,和路径别名解析,如下: ```js resolve: { //自动识别的文件后缀,比如写 from '@/store',会被依次解析为 '绝对路径/store.mjs/.js等'直到找到文件 extensions: ['.mjs', '.js', '.ts', '.tsx', '.jsx', '.vue', '.json', '.wasm', '.scss'], alias: { '@': resolve('src'), //众所周知,路径别名,resolve()解析绝对路径方法自行实现即可 vue$: 'vue/dist/vue.esm.js' } }, ``` > 再往下就是webpack最为核心的loader配置了,虽然webpack的loader各种各样,但是使用起来却是十分简单,如下面这段`vue + babel + ts + scss + postcss`的loader配置: ```js module: { rules: [ { test: /\.vue$/, //正则匹配.vue后缀文件,使用vue-loader这个loader进行解析 use: [{loader: 'vue-loader'} ] }, { test: /\.js$/, //正则匹配.js后缀文件,使用babel-loader进行解析 exclude: /node_modules/, use: [{loader: 'babel-loader'} ] }, { test: /\.tsx?$/, //正则匹配.ts|tsx后缀文件,使用ts-loader进行解析,这里就是使用TypeScript的关键配置 use: [ {loader: 'babel-loader'}, {loader: 'ts-loader',options: {transpileOnly: true,appendTsSuffixTo: ['\\.vue$'],happyPackMode: true}}] }, { test: /\.(css|scss)$/, //解析scss样式,同时使用了postcss对css进行浏览器兼容等处理 use: ['vue-style-loader','css-loader','postcss-loader','sass-loader'] } ] }, ``` #### 总结起来很简单,就是三部曲: 1. 正则匹配文件后缀名; 2. 指定这种类型文件应该使用的loader; 3. 对于有参数需要配置的loader,写options即可。 > webapck的插件配置非常丰富,正是有了这些插件,才使得打包项目简单起来,如下面的这些插件: ```js plugins: [ //webpack的插件配置,大部分插件都是引入即可用,无需配置 new VueLoaderPlugin(), //vue-loader的伴生插件 new CleanWebpackPlugin(), //清除./dist文件夹 new HtmlWebpackPlugin({ //自动注入打包后的.js文件 filename: 'index.html', template: 'index.html', chunksSortMode: 'none' }), new CopyWebpackPlugin([ //直接拷贝静态文件至输出文件夹,这里是./public文件夹 { from: './public', to: './public', toType: 'dir', ignore: ['.DS_Store', '*.html'] }]) ] ``` --------------------------------------------------- 以上这些,便是webpack打包的全部内容了,,了这些配置,我们的vue项目已经可以打包了,是不是并没有想象中的复杂? #### 后续将继续给分享一下开发环境下的配置,热模块更新,proxyTable代理等配置的经验...<file_sep>/vue-faster(免安装_配置element_rem_dll_happypack)/readme.md # 基于`vue-cli`优化的`webpack`配置 大概分为以下几点 - 通过 `externals` 配置来提取常用库,引用外链 - 配置`CommonsChunkPlugin`提取公用代码 (`vue-cli`已做) - 善用`alias`(`vue-cli`配置了一部分) - 启用`DllPlugin`和`DllReferencePlugin`预编译库文件 - `happypack`开启多核构建项目 - 将`webpack-parallel-uglify-plugin`来替换`webpack`本身的`UglifyJS`来进行代码压缩混淆 - 升级`webpack`至3.x版本开启`Scope Hoisting` ### externals > 文档地址 https://doc.webpack-china.org/configuration/externals/ > > 防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。 ### CommonsChunkPlugin > 文档地址 https://doc.webpack-china.org/plugins/commons-chunk-plugin/ > > CommonsChunkPlugin 插件,是一个可选的用于建立一个独立文件(又称作 chunk)的功能,这个文件包括多个入口 chunk 的公共模块。通过将公共模块拆出来,最终合成的文件能够在最开始的时候加载一次,便存起来到缓存中供后续使用。这个带来速度上的提升,因为浏览器会迅速将公共的代码从缓存中取出来,而不是每次访问一个新页面时,再去加载一个更大的文件。 ### resolve.alias > 文档地址 https://doc.webpack-china.org/configuration/resolve/#resolve-alias > > 创建 import 或 require 的别名,来确保模块引入变得更简单。例如,一些位于 src/ 文件夹下的常用模块: ### DllPlugin和DllReferencePlugin > 文档地址 https://doc.webpack-china.org/plugins/dll-plugin/ > > Dll打包以后是独立存在的,只要其包含的库没有增减、升级,hash也不会变化,因此线上的dll代码不需要随着版本发布频繁更新。使用Dll打包的基本上都是独立库文件,这类文件有一个特性就是变化不大。,只要包含的库没有升级, 增减,就不需要重新打包。这样也提高了构建速度。 > > 一般是用于打包阶段 1. 在`build`文件夹下新建`webpack.dll.conf.js`文件 ```javascript var path = require('path'); var webpack = require('webpack'); var AssetsPlugin = require('assets-webpack-plugin'); var CleanWebpackPlugin = require('clean-webpack-plugin'); var config = require('../config'); var env = config.build.env; module.exports = { entry: { libs: [ 'babel-polyfill', 'vue/dist/vue.esm.js', 'vue-router', 'vuex', 'element-ui', 'echarts', 'mockjs', ], }, output: { path: path.resolve(__dirname, '../libs'), filename: '[name].[chunkhash:7].js', library: '[name]_library', }, plugins: [ new webpack.DefinePlugin({ 'process.env': env, }), new webpack.DllPlugin({ path: path.resolve(__dirname, '../libs/[name]-mainfest.json'), name: '[name]_library', context: __dirname, // 执行的上下文环境,对之后DllReferencePlugin有用 }), new ExtractTextPlugin('[name].[contenthash:7].css'), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), new AssetsPlugin({ filename: 'bundle-config.json', path: './libs', }), new CleanWebpackPlugin(['libs'], { root: path.join(__dirname, '../'), // 绝对路径 verbose: true, dry: false, }), ], module: { rules: [ { test: /\.js$/, loader: 'babel-loader', }, ], }, }; ``` 2. 在`build`文件夹下新建`build-dll.js`文件 ```javascript var path = require("path"); var webpack = require("webpack"); var dllConfig = require("./webpack.dll.conf"); var chalk = require("chalk"); var rm = require("rimraf"); var ora = require("ora"); var spinner = ora({ color: "green", text: "building for Dll..." }); spinner.start(); rm(path.resolve(__dirname, "../libs"), err => { if (err) throw err; webpack(dllConfig, function(err, stats) { spinner.stop(); if (err) throw err; process.stdout.write( stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + "\n\n" ); console.log(chalk.cyan(" build dll succeed !.\n")); }); }); ``` 3. 修改`webpack.prod.conf.js`文件 ```javascript var bundleConfig = require("../libs/bundle-config.json"); ... ... plugins: [ // 增加DllReferencePlugin配置 new webpack.DllReferencePlugin({ context: __dirname, manifest: require("../libs/libs-mainfest.json") // 指向生成的manifest.json }), ... ... new HtmlWebpackPlugin({ ... // 增加两个变量 libJsName: bundleConfig.libs.js, libCssName: bundleConfig.libs.css, }), ... ... // 增加一个静态文件目录 new CopyWebpackPlugin([ ... ... { from: path.resolve(__dirname, "../libs"), to: config.build.assetsSubDirectory, ignore: ["*.json"] } ]) ] ``` 4. 修改模版文件`index.html` ```ejs <body> <div id="app"></div> <!-- built files will be auto injected --> <% if (htmlWebpackPlugin.options.libCssName){ %> <link rel="stylesheet" href="./static/<%= htmlWebpackPlugin.options.libCssName %>"> <% } %> <% if (htmlWebpackPlugin.options.libJsName){ %> <script src="./static/<%= htmlWebpackPlugin.options.libJsName %>"></script> <% } %> </body> ``` 5. 修改`package.json`,增加`scripts` ```json "scripts": { // 增加 "dll": "node build/build-dll.js" }, ``` 6. `npm run dll`先执行预编译,然后在打包项目文件,如果引入的类库文件没有变更就不再需要再次执行预编译 ### happypack > 文档地址 https://github.com/amireh/happypack > > 一般node.js是单线程执行编译,而happypack则是启动node的多线程进行构建,大大提高了构建速度。 > >在插件中new一个新的happypack进程出来,然后再使用使用loader的地方替换成对应的id 1. 修改`webpack.base.conf.js`文件 ```javascript var HappyPack = require('happypack'); var os = require('os'); var happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length }); ... ... // 增加plugins plugins: [ new HappyPack({ id: 'happy-babel-js', loaders: ['babel-loader?cacheDirectory=true'], threadPool: happyThreadPool, }) ] ... ... // 修改对应loader { test: /\.js$/, loader: 'happypack/loader?id=happy-babel-js', include: [resolve('src'), resolve('test')], } ``` ### webpack-parallel-uglify-plugin > 文档地址 https://github.com/gdborton/webpack-parallel-uglify-plugin > > `webpack`提供的`UglifyJS`插件由于采用单线程压缩,速度很慢 , `webpack-parallel-uglify-plugin`插件可以并行运行`UglifyJS`插件,这可以有效减少构建时间。 1. 修改`webpack.prod.conf.js`文件 ```javascript var ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin'); ... ... // 删掉webpack提供的UglifyJS插件 // new webpack.optimize.UglifyJsPlugin({ // compress: { // warnings: false, // drop_console: true // }, // sourceMap: true // }), // 增加 webpack-parallel-uglify-plugin来替换 new ParallelUglifyPlugin({ cacheDir: '.cache/', uglifyJS:{ output: { comments: false }, compress: { warnings: false } } }), ``` ### webpack 3 > webpack3新特性一览 https://juejin.im/entry/5971483951882552681c4a30 > > webpack 3.x 提供了一个新的功能:Scope Hoisting,又译作“作用域提升”。只需在配置文件中添加一个新的插件,就可以让 Webpack 打包出来的代码文件更小、运行的更快。 1. 修改`webpack.prod.conf.js` ```javascript ... ... plugins: [ // 往plugins添加一个配置 // ps 只针对es6的模块化有效 new webpack.optimize.ModuleConcatenationPlugin(), ] ``` # vue-cli-faster-template ## Advanced ```bash # --report to build with bundle size analytics npm run build --report # --preview to start a server in local to preview npm run build --preview <file_sep>/vue-ssr-template-ts-webpack/src/plugins/urls.ts const urls = { local: 'http://127.0.0.1:7001', mock: '/mockjs', online: '/online' } export default urls <file_sep>/vue-custom-webpack-template(ts)/src/libs/urls.ts let prefix = { systemServer: 'system-server/', // 系统服务前缀 guideServer: 'guide-server/', // 开发者指南应用名称 publishServer: 'publish-server/' // 发布服务器 } const urls = { openIdPath: '/openid-service/openid_connect_login', proOpenId: 'http://172.16.58.33:9090', // 开发环境中使用的接口地址 openIdValue: 'https://g1openid.crcc.cn', // 获取openId的请求地址, Mock: 'mockjs/', // RAP mock服务器前缀 // ----------默认为各自的服务地址-------------- // dev: 'http://192.168.31.147:9090', // ZYF开发环境中使用的接口地址 // ---------------切换为ZYF服务---------------------- // dev: 'http://192.168.31.147:9090/web-server', // HHC开发环境中使用的接口地址 // auth: `/ZYF/`,//登录等认证 // system: `/ZYF/${prefix.systemServer}`, // 打包前设置为'' // guide: `/ZYF/${prefix.guideServer}`, // 打包前设置为'' // publish: `/ZYF/${prefix.publishServer}`, // 打包前设置为'' // ----------------切换为 local 服务--------------------- devOpenId: 'http://192.168.31.212:9090', // 开发环境中使用openId的接口地址 auth: `/local/`, //登录等认证 system: `/local/szyd-system/`, // 打包前设置为'' guide: `/local/${prefix.guideServer}`, // 打包前设置为'' publish: `/local/${prefix.publishServer}` // 打包前设置为'' // ----------------切换为 Online 服务--------------------- // devOpenId: 'http://192.168.31.153:9090', // HHC开发环境中使用的接口地址 // auth: `/Online/`, //登录等认证 // system: `/Online/`, // 打包前设置为'' // guide: `/Online/`, // 打包前设置为'' // publish: `/Online/` // 打包前设置为'' // ----------------切换为 Mock 服务--------------------- // devOpenId: 'http://192.168.31.153:9090', // HHC开发环境中使用的接口地址 // auth: `/mockjs/`, //登录等认证 // system: `/mockjs/`, // 打包前设置为'' // guide: `/mockjs/`, // 打包前设置为'' // publish: `/mockjs/` // 打包前设置为'' //------------TODO: 打包时设置------------------- // auth: ``, //登录等认证 // system: `${prefix.systemServer}`, // 打包前设置为'' // guide: `${prefix.guideServer}`, // 打包前设置为'' // publish: `${prefix.publishServer}` // 打包前设置为'' } export default urls <file_sep>/vue-custom-webpack-template(ts)/src/views/system/store/log.ts import { getLogList } from '@/views/system/api/system/log' import dayjs from 'dayjs' import { cloneDeep } from 'lodash' import { Notification } from 'element-ui' function formatDate(date) { if (!date) return '' return dayjs(date).format('YYYY-MM-DD HH:mm:ss') } const Log = { namespaced: true, state: { log_current_page: 1, log_page_size: 10, log_page_total: 1, log_total: 0, log_table_data: [], log_condition: {}, log_loading: false }, mutations: { SET_LOG_PAGE_CURRENT(state, data) { state.log_current_page = data }, SET_LOG_PAGES(state, data) { state.log_page_total = data }, SET_LOG_TOTAL(state, data) { state.log_total = data }, SET_LOG_LIST(state, data) { state.log_table_data = data }, SET_LOG_PAGE_SIZE(state, payload) { state.log_page_size = payload }, SET_LOADING(state, payload) { state.log_loading = payload }, SET_LOG_CONDITION(state, payload: NLog.LogForm) { let formTemp: NLog.LogForm = cloneDeep(payload) let condition: NLog.LogSearchCondition = {} if (Array.isArray(formTemp.dateRange)) { condition.operatorBeginDate = formatDate(formTemp.dateRange[0]) condition.operatorEndDate = formatDate(formTemp.dateRange[1]) } else { condition.operatorBeginDate = '' condition.operatorEndDate = '' } delete formTemp.dateRange condition = Object.assign(condition, formTemp) state.log_condition = condition } }, actions: { async COMMIT_LOG_DATA({ commit, state }) { commit('SET_LOADING', true) let params = { current: state.log_current_page, size: state.log_page_size, condition: state.log_condition, sorts: [ { property: 'operatorDate', direction: 'desc' } ] } await getLogList(params) .then(res => { if (!res.data) return const data = res.data let logTableData = data.records logTableData.map(log => { log.type = log.type === 'success' ? '成功' : '失败' log.exceptionCode = log.exceptionCode ? `${log.exceptionCode}(${log.exceptionDetail})` : '无' log.operatorDate = formatDate(log.operatorDate) }) commit('SET_LOG_PAGE_CURRENT', data.current) commit('SET_LOG_PAGES', data.pages) commit('SET_LOG_TOTAL', data.total) commit('SET_LOG_LIST', logTableData) }) .catch(e => { Notification.error(`获取日志失败! ${e}`) }) .finally(() => { commit('SET_LOADING', false) }) } } } export default Log <file_sep>/VueWebpackTemplate/template/src/common/js/mixins.js // mixins用来保存通用的vue组件配置 <file_sep>/mpvue-quickstart/README.md # mpvue-quickstart > fork 自 [vuejs-templates/webpack](https://github.com/vuejs-templates/webpack)修改而来。 ## 基本用法 ``` bash $ npm install -g vue-cli $ vue init mpvue/mpvue-quickstart my-project $ cd my-project $ npm install $ npm run dev ``` 更多详细文档请查阅 [quickstart](http://mpvue.com/mpvue/quickstart/)。 bug 或者交流建议等请反馈到 [mpvue/issues](https://github.com/Meituan-Dianping/mpvue/issues)。 <file_sep>/vue-custom-webpack-template(ts)/src/views/system/store/system.ts import { Loading, Notification } from 'element-ui' // import { getSystemMenu } from '@/api/common.ts' import { map } from 'lodash' const system = { namespaced: true, state: { system_menu: [ { id: '57c2a1570b4611e9a41965edb94c593d', code: '0101', menuTitle: '菜单管理', menuIcon: 'el-icon-menu', menuPath: '/system/menus', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'menus', menuSort: 1, parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T06:56:29.000+0000', version: null, children: [], index: 0 }, { id: '79c34fc80b4611e9a41997ce89591dba', code: '0102', menuTitle: '数据字典', menuIcon: 'el-icon-search', menuPath: '/system/category', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'category', menuSort: 2, parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-28T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T06:56:38.000+0000', version: null, children: [], index: 1 }, { id: '957f12d90b4611e9a419bf4591c0785a', code: '0103', menuTitle: '授权管理', menuIcon: 'el-icon-user', menuPath: '/system/user', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'user', menuSort: 3, parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T09:22:55.000+0000', version: null, children: [], index: 2 }, { id: '957f12d90b4611e9a419bf4591c0785a', code: '0106', menuTitle: '授权demo', menuIcon: 'el-icon-news', menuPath: '/system/auth', menuRouteName: 'auth', menuSort: 6, parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-04T09:22:55.000+0000', version: null, children: [], index: 6 }, { id: '<KEY>', code: '0105', menuTitle: '流程管理', menuIcon: 'el-icon-check', menuPath: '/system/process', menuRegular: null, menuRouteName: 'process', menuSort: '4', parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-31T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:32.000+0000', version: null, children: [], index: 3 }, { id: 'a<PASSWORD>46<PASSWORD>419c5<PASSWORD>', code: '0104', menuTitle: '日志管理', menuIcon: 'el-icon-info', menuPath: '/system/log', menuRegular: '^\\/project\\/\\d+$', menuRouteName: 'log', menuSort: 5, parentCode: '01', inUse: true, remark: null, createPerson: '987837', createTime: '2018-12-27T16:00:00.000+0000', updatePerson: '987837', updateTime: '2019-01-03T07:01:44.000+0000', version: null, children: [], index: 4 } ], category_data: [] }, getters: {}, mutations: { SET_SYSTEM_MENU(state, payload) { state.system_menu = payload }, SET_CATEGORY_DATA(state, data) { state.category_data = data } }, actions: { //获取系统菜单 async COMMIT_SYSTEM_MENU({ commit }) { // const systemLoading = Loading.service({ target: '#system-index', text: '加载系统菜单中,请稍后...' }) // let systemMenu: any[] = [] // // TODO: 暂时不请求接口 // getSystemMenu() // .then(res => { // systemMenu = (res.data.length > 0 && res.data[0].children) || [] // systemMenu.sort((a, b) => { // return a.menuSort - b.menuSort // }) // systemMenu.map((item, index) => { // //增加实际index // item.index = index // }) // // commit('SET_SYSTEM_MENU', systemMenu) // }) // .catch(e => { // Notification.error(`系统系统菜单获取失败!`) // }) // .finally(() => { // systemLoading.close() // }) } } } export default system <file_sep>/vue-custom-webpack-single-spa/src/api/common.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' let systemServerName = urls.system let serverName = '' // 获取登陆用户信息 export function login() { return http.get(`${systemServerName}system/login`) // return http.get(`${systemServerName}system/v1.0/userinfo`) } // 更改用户管理机构 export function changeManageOrg(orgCode) { return http.get(`${systemServerName}system/v1.0/${orgCode}/userinfo`) } // 注销 export function logout() { return http.get('home/logout') } //获取数据字典 export function getWholeTree() { return http.get(`${systemServerName}system/category/v1.0/wholetree`) } //根据数据字典code获取数据字典 export function getCategoryByCode(categoryCode) { return http.get(`${systemServerName}system/category/detail/v1.0/details/bycode/${categoryCode}`) } //获取当前人员有权限的机构,用于切换管理机构 export function getUserAuthOrgs() { return http.get(`${systemServerName}system/szyd/org/v1.0/auth/orgs`) } //获取当前人员有权限的菜单 export function getUserAuthMenus() { return http.get(`${systemServerName}system/v1.0/userinfo/permission`) } //查询用户的actionUrl export function getUserAction() { return http.get(`${systemServerName}system/v1.0/userinfo/action`) } //当前用户接收到的提示信息 export function getMessageList(params) { return http.post(`${serverName}szyd/message/v1.0/query`, params) } //当关闭用户接收到的提示信息 export function putMessageList(ids) { return http.put(`${serverName}szyd/message/v1.0`, ids) } <file_sep>/vue-faster(免安装_配置element_rem_dll_happypack)/build/webpack.dll.conf.js var path = require('path') var webpack = require('webpack') //调用webpack内置DllPlugin插件 var ExtractTextPlugin = require('extract-text-webpack-plugin') // 提取css var AssetsPlugin = require('assets-webpack-plugin') // 生成文件名,配合HtmlWebpackPlugin增加打包后dll的缓存 var CleanWebpackPlugin = require('clean-webpack-plugin') //清空文件夹 var config = require('../config') var env = config.build.env module.exports = { entry: { libs: [ 'babel-polyfill', 'vue/dist/vue.esm.js', 'vue-router', 'vuex', 'element-ui', "axios", "lodash" ], }, output: { path: path.resolve(__dirname, '../libs'), filename: '[name].[chunkhash:7].js', library: '[name]_library', }, plugins: [ new webpack.DefinePlugin({ 'process.env': env, }), new webpack.DllPlugin({ path: path.resolve(__dirname, '../libs/[name]-mainfest.json'), name: '[name]_library', context: __dirname, // 执行的上下文环境,对之后DllReferencePlugin有用 }), new ExtractTextPlugin('[name].[contenthash:7].css'), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), new AssetsPlugin({ filename: 'bundle-config.json', path: './libs', }), new CleanWebpackPlugin(['libs'], { root: path.join(__dirname, '../'), // 绝对路径 verbose: true, // 是否显示到控制台 dry: false, // 不删除所有 }), ], module: { rules: [{ test: /\.js$/, loader: 'babel-loader', }, ], }, } <file_sep>/vue-custom-webpack-template(ts)/build/build.js process.env.NODE_ENV = 'production' process.env.BASE_URL = '"/"' const webpack = require('webpack') const webpackConfig = require('./webpack.prod.js') const chalk = require('chalk') const { log } = console const serverCompiler = webpack(webpackConfig) function handle(err, stats) { if (err) { throw err } process.stdout.write( stats.toString({ colors: true, modules: false, children: true, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. chunks: false, chunkModules: false, builtAt: true, errors: false, warnings: false, timings: true, performance: true, assets: true }) + '\n\n' ) const result = stats.toJson() if (stats.hasErrors()) { log(chalk.red('ERROR: ')) result.errors.forEach(error => { log(chalk.red(error)) log('--------') }) process.exit(1) } if (stats.hasWarnings()) { log(chalk.yellow('WARNING: ')) result.warnings.forEach(warn => { log(chalk.yellow(warn)) log('--------') }) } } serverCompiler.run((err, stats) => { serverStats = stats handle(err, stats) log(chalk.green(`Build successfully!`)) }) <file_sep>/vue-custom-webpack-template(ts)/src/plugins/index.d.ts import Vue, { VueConstructor } from 'vue' import { AxiosInstance, AxiosStatic, AxiosPromise, AxiosInterceptorManager, AxiosResponse, AxiosRequestConfig, CancelStatic, CancelTokenStatic } from 'axios' declare global { interface Window { http: IAxiosInstance } } declare module 'vue/types/vue' { interface Vue { $http: IAxiosInstance $http_download: IAxiosInstance $get: GetProp $dayjs: Function } interface GetProp { (obj: Object, props: String, defaultVal?: any): any } interface VueConstructor { $http: IAxiosInstance $http_download: IAxiosInstance } } export interface IAxiosInstance extends AxiosInstance { upload: (url: any, params?: {}) => Promise<any> delPost: (url: any, params?: {}) => Promise<any> getDownload: (url: any, params?: {}) => Promise<any> postDownload: (url: any, params?: {}) => Promise<any> (config: AxiosRequestConfig): AxiosPromise (url: string, config?: AxiosRequestConfig): AxiosPromise defaults: AxiosRequestConfig interceptors: { request: AxiosInterceptorManager<AxiosRequestConfig> response: AxiosInterceptorManager<AxiosResponse> } } // export interface IAxiosStatic extends AxiosInstance { // upload: (url: any, params?: {}) => Promise<any> // Cancel: CancelStatic // CancelToken: CancelTokenStatic // create(config?: AxiosRequestConfig): AxiosInstance // isCancel(value: any): boolean // all<T>(values: (T | Promise<T>)[]): Promise<T[]> // spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R // } // declare const Axios: IAxiosStatic // export default Axios <file_sep>/vue-custom-webpack-template(ts)/src/libs/commonUtils.ts // import { getUserInfo } from '@/api/common' // import store from '@/store/index' import { intersection, union, uniqBy, cloneDeep, difference, map, uniqWith, isEqual, get } from 'lodash' // import { Notification } from 'element-ui' /** * uniq //值数组内去重 * uniqWith([], 'a') //对象数组内 根据某个key去重 * * @param arr1 * * @param arr2 */ /** * @description 取交集 */ export function getArrIntersection(arr1, arr2) { return intersection(arr1, arr2) } /** * @description 值数组 取并集 */ export function getArrUnionSet(arr1, arr2) { return union(arr1, arr2) } /** * @description 取补集 */ export function getArrComplementSet(arr1, arr2) { return difference(arr1, arr2) } /** * @description 对象数组 取并集 * */ export function ArrayRemoveDuplicates(arr1: any[], arr2: any[]) { const arrTemp = arr1.concat(arr2) return uniqWith(arrTemp, isEqual) } /** * @description 对象数组多重 keys 取并集 * 去除arr2中与arr1所有指定key相同的元素,返回合并的数组 * */ export function ArrayRemoveRepeatMultiple(arr1: any[], arr2: any[], ...key: string[]): any[] { let arrayTemp: any[] = arr1.concat(arr2) function iteratee(value): string { let concatString: string = '' key.map(item => { concatString += `${value[item]}-` }) return concatString } if (key.length > 1) { arrayTemp = uniqBy(arrayTemp, iteratee) } return arrayTemp } // 递归查找,多维数组使用 export function arrayFindDeep(arr, key, value) { for (let item of arr) { if (item.children) { const menu = arrayFindDeep(item.children, key, value) if (menu) { return menu } } else if (item[key] === value) { return item } } } // 除去请求参数里面的属性值为空的键值对 export function removeNullInObject(config) { if (config instanceof Object && !Array.isArray(config)) { for (let key in config) { if (Array.isArray(config[key]) && config[key].length === 0) { delete config[key] } else if (!config[key] && config[key] !== 0) { delete config[key] } } } return config } /* ** 获取hr系统人员岗位全称 */ export function getFullPostName({ danweiquancheng, bumenquancheng, gangweiquancheng }) { return `${danweiquancheng} ${bumenquancheng} ${gangweiquancheng}`.replace(/\//g, '') } /** * @describe 抽取Tree指定键至当前级 * @param {Array} tree * @param {Array} key */ export function transformTreeData(tree, key) { let dataTemp = cloneDeep(tree) // debugger transform(dataTemp) function transform(data) { data.map(item => { if (item[key] && item[key].length > 0) { // 为每个 api 增加id字段 key === 'apiList' && item[key].map(item_api => { item_api.id = item_api.apiId }) item.children ? item.children.push(...item[key]) : (item.children = item[key]) } if (item.children && item.children.length > 0) { transform(item.children) } }) } return dataTemp } /** * @description 判断数组或者对象是否为空 * @param {Array} arr * */ export function isEmpty(arr) { if (!arr && arr !== 0 && arr !== '') { return true // 检验 undefined 和 null } else if (Array.prototype.isPrototypeOf(arr) && arr.length === 0) { return true } else if (Object.prototype.isPrototypeOf(arr) && Object.keys(arr).length === 0) { return true } else { return false } } /** * @description 更改数组中的组织结构名称 * @param {Array} arr 包含组织信息元素的数组 */ export function changeOrgPostName(arr) { let data = arr for (let item of data) { if (item.zuzhilujing) { if (item.leixing == 'renyuan') { item.postName = item.zuzhilujing.replace(item.jiancheng, '') } else { item.postName = item.zuzhilujing } } } return data } export function setSessionStorage(name, content) { if (!name) { return } let contentTemp if (typeof content !== 'string') { contentTemp = JSON.stringify(content) } window.sessionStorage.setItem(name, contentTemp) } /** * get sessionStorage */ export function getSessionStorage(name) { if (!name) { return } return window.sessionStorage.getItem(name) } /** * delete localStorage */ export function removeSessionStorage(name) { if (!name) { return } window.sessionStorage.removeItem(name) } interface IDictionary { // 字典结构 id: string categoryId: string detailName: string detailCode: string detailSort: string isUse?: number isLeaf?: number parentDetailId?: string createPerson?: string createTime?: any updatePerson?: string updateTime?: any version?: string children?: IDictionary[] } /** * @description code从数据字典获取label * @param {String|Number} code 所需查询的数据字典名称 * @param {Array} dictionary 包含code数据字典数组 * @returns {String|Number} [0,..] 符合的label */ export function getDicCodeToLabel(code, dictionary: IDictionary[]) { // console.log('dictionary: ', dictionary) let resultArr = dictionary.filter(({ detailCode }) => { return detailCode === code }) return map(resultArr, 'detailName')[0] } /**===================================================================== * @description 从数据字典获取code * @param {String} label 所需查询的数据字典名称 * @param {Array} dictionary 包含label数据字典数组 * @returns {Array} [0,..] 符合的code的数组 */ export function getDicLabelToCode(label, dictionary: IDictionary[]) { // console.log('dictionary: ', dictionary) let resultArr = dictionary.filter(item => { return item.detailName === label }) return map(resultArr, 'detailCode') } /**========================================================================= * @description 从数据字典检查当前状态码statusCode是否符合label * @param {String|Number} statusCode * @param {String} label 所需查询的数据字典名称 * @param {Array} dictionary 包含label数据字典数组 * @returns {Boolean} [0,..] 符合的code的数组 */ export function checkStatusCode(statusCode, label, dictionary = []) { let codes = getDicLabelToCode(label, dictionary) let flag = codes.some(code => { return code == statusCode }) return flag } /**========================================================================== * @description 从路由里获取菜单树 * @param router 模块的路由信息 */ export function getRouterTree(router) { let routerTemp = cloneDeep(router) function getRouter(router) { Array.isArray(router.children) && router.children.map(item => { item.path = `${router.path}/${item.path}` item.path = item.path.replace(/\/\//g, '/') Array.isArray(item.children) && getRouter(item) }) } getRouter(routerTemp) // console.log('routerTemp.children[0].children: ', routerTemp.children[0].children) return routerTemp.children[0].children } /**======================================================================== * @description 判断是否有权限 * @param permission * @param allPermissionCode */ export function checkPermission(permission: string[], allPermissionCode: string[]): boolean { let hasAccessList = intersection(permission, allPermissionCode) return hasAccessList.length > 0 } /**=========================================================================== * @description 从路由里过滤有权限的菜单树 * @param router:any[] 模块的路由信息 * @param permissionNameArray:string[] 所有有权限的路由名称的平铺数组 * @param permissionPathArray:string[] 所有有权限的路由路径的平铺数组 */ export function getPermissionRouterTree(router, permissionNameArray: string[], permissionPathArray: string[]) { let routerTemp = cloneDeep(router) function getRouter(router) { // ======================判断当前节点path是否存在======================== let hasCurrentPermission: string | undefined = '' if (!router.path) { hasCurrentPermission = 'true' } else { hasCurrentPermission = permissionPathArray.find(itemPermissionPath => { return itemPermissionPath === router.path }) } if (!hasCurrentPermission) { router.children = [] return } // ======================遍历子节点name是否存在======================== Array.isArray(router.children) && router.children.map((item, index) => { let hasPermission: string | undefined = '' //没有name的路由默认为有权限 if (!item.name) { hasPermission = 'true' } else { hasPermission = permissionNameArray.find(itemPermissionRouter => { return itemPermissionRouter === item.name }) } !hasPermission && (router.children[index] = null) Array.isArray(item && item.children) && getRouter(item) }) //清除空对象 router.children = router.children.filter(Boolean) } getRouter(routerTemp) // console.log('routerTemp: ', routerTemp) //清除没有子菜单的路由 function clearNullRouter(router) { if (Array.isArray(router && router.children)) { router.children = router.children.filter(Boolean) let childrenList = router.children // console.log('childrenList: ', childrenList) if (childrenList.length <= 0) { //@ts-ignore router = null } childrenList.map(item => { Array.isArray(item && item.children) && clearNullRouter(item) }) } } clearNullRouter(routerTemp) //清除没有二级菜单的路由 let childrenList = get(routerTemp, 'children[0].children', []).filter(Boolean) if (childrenList.length <= 0) { //@ts-ignore routerTemp = null } // console.log('routerTemp: ', routerTemp) return routerTemp } <file_sep>/vue-ssr-template-ts-webpack/build/webpack.client.config.js const webpack = require('webpack') const merge = require('webpack-merge') const VueSSRClientPlugin = require('vue-server-renderer/client-plugin') const path = require('path') const base = require('./webpack.base.config') const clientConfig = merge(base, { target: 'web', entry: { app: './src/entry-client.js' }, output: { path: path.resolve('dist'), filename: 'js/[name].[hash:8].bundle.js' }, optimization: { usedExports: true, //js TreeShaking minimize: true, splitChunks: { chunks: 'all', // initial、async和all minSize: 30000, // 形成一个新代码块最小的体积 maxAsyncRequests: 5, // 按需加载时候最大的并行请求数 maxInitialRequests: 3, // 最大初始化请求数 name: true, cacheGroups: { vendors: { name: 'chunk-vendors', test: /[\\\/]node_modules[\\\/]/, priority: -10, chunks: 'all' }, common: { minChunks: 2, priority: -20, chunks: 'all', reuseExistingChunk: true } } } }, plugins: [ // strip dev-only code in Vue source new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'), 'process.env.VUE_ENV': '"client"' }), new VueSSRClientPlugin() ] }) module.exports = clientConfig <file_sep>/vue-custom-webpack-single-spa/src/views/system/api/system/menu.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' let serverName = urls.system let menuApi = { /** * 获取树形菜单 */ queryTreeMenus: () => { return http.get(`${serverName}system/menu/v1.0/tree/menus`) }, /** * 根据ID查询指定菜单信息 */ querySysMenuById: menuId => { return http.get(`${serverName}system/menu/v1.0/menu/${menuId}`) }, /** * 新增菜单 */ saveSysMenu: menuInfo => { return http.post(`${serverName}system/menu/v1.0/menu`, menuInfo) }, /** * 根据ID删除指定菜单数据 */ deleteSysMenuById: menuId => { return http.delete(`${serverName}system/menu/v1.0/menu/${menuId}`) }, /** * 修改菜单数据 */ updateSysMenu: menuInfo => { return http.put(`${serverName}system/menu/v1.0/menu/${menuInfo.id}`, menuInfo) }, /** * 建立菜单和权限关联关系 */ postApplyMenus: params => { return http.post(`${serverName}system/menu/v1.0/buildmappingwithauth`, params) }, /** * 查询菜单和权限关联关系 */ getApplyMenus: menuId => { return http.get(`${serverName}system/menu/v1.0/querymappingwithauth/${menuId}`) } } export default menuApi <file_sep>/vue-custom-webpack-template(ts)/src/mock/system.ts // import qs from 'qs' // import { parseUrl } from './utils.ts' import apiData from './data' let System = { getSystemMenu: options => { console.log('options: ', options) let response = { data: apiData[10], msg: '', success: true, status: 200 } return response } } export default System <file_sep>/vuepack/docs/postcss.md # PostCSS By default we only use `autoprefixer` and `postcss-nested` in PostCSS, you can update `postcss` field in `package.json` to use custom plugins. ## Autoprefixer Autoprefixer respects the `browserslist` field in `package.json`, the default value we use is: `['ie > 8', 'last 2 versions']` <file_sep>/vue-custom-webpack-template(ts)/src/views/system/api/system/category.ts import { _axios as http } from '@/plugins/axios' import urls from '@/libs/urls' //为Mock数据url添加前缀 let serverName = urls.system // 获取数据字典类别(类目)树形列表 export function getCategoryTree() { return http.get(`${serverName}system/category/v1.0/tree`, {}) } // 根据id获取该节点下一级子节点 (根据上级查询数据字典类目) export function getCategoryOneTree(parentId) { return http.get(`${serverName}system/category/v1.0/${parentId}/next`) } // 新增类别节点 export function addCategory(params) { return http.post(`${serverName}system/category/v1.0`, params) } // 更新类别节点 export function updateCategory(id, params) { return http.put(`${serverName}system/category/v1.0`, params) } // 删除类别节点 export function deleteCategory(id) { return http.delete(`${serverName}system/category/v1.0/${id}`) } //========================detail明细============================= // 获取类别明细 export function getCategoryDetail(code) { return http.get(`${serverName}system/category/detail/v1.0/details/${code}`) } // 获取类别明细树 export function getCategoryDetailTree(code) { return http.get(`${serverName}system/category/detail/v1.0/tree/${code}`) } // 新增明细节点 export function addDetail(params) { return http.post(`${serverName}system/category/detail/v1.0`, params) } // 更新明细节点 export function updateDetail(id, params) { return http.put(`${serverName}system/category/detail/v1.0`, params) } // 删除明细节点 export function deleteDetail(id) { return http.delete(`${serverName}system/category/detail/v1.0/${id}`) } export function getWholeTree() { return http.get(`${serverName}system/category/v1.0/wholetree`) } <file_sep>/vuepack(免安装_已配置rem)/README.md # vuePack ### 自定义webpack vue.js项目目录 >### 主要自定义功能 ``` element UI px2rem remAdapt ``` >### 开始: ``` $ cnpm install $ npm run dev $ npm run build ``` Generated by [VuePack](https://github.com/egoist/vuepack). <file_sep>/vue-ssr-template-ts-webpack/src/util/index.js // 公用方法库 /** * 获取 Authorization * @return {String} Authorization值 */ export const getAuthorization = () => { // console.log('sessionStorage', sessionStorage.getItem('Authorization')) return sessionStorage.getItem('Authorization') } /** * 判断是否登录 * @param {String} key cookie键 * @return {Boolean} 是否登录 */ export const isLogin = () => { return Boolean(getAuthorization()) } /** * 字符串后四位转化为万 * @param {String} num * @return {String} */ export const handleCount = num => { if (num) { const str = String(num) if (str.length > 5) { return str.replace(/\d{4}$/, '万') } return str } return '' } /** * 将秒时间转换 -> 分钟:秒 * @param {Number} time 时间 * @return {String} */ export const handleTime = time => { if (time) { let minutes = `${parseInt(time / 60, 10)}` minutes = minutes.length > 1 ? minutes : `0${minutes}` let seconds = `${time % 60}` seconds = seconds.length > 1 ? seconds : `0${seconds}` return `${minutes}:${seconds}` } return '00:00' } /** * 将 Date 对象转换为时间 ymd-hms * @param {Date} data 对象 * @return {String} */ export const convertDateToTime = function convertDateToTime(date) { if (date.constructor !== Date) { return '' } return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}-${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}` } /** * 函数节流 * @param {Function} fn 执行函数 * @param {Number} delay 延时时长 * @param {Object} context 函数执行上下文 * @return {Function} */ export const debounce = (fn, delay) => { let timer = null return function callback() { if (timer) { clearTimeout(timer) timer = null } timer = setTimeout(function handler(...args) { fn.apply(this, args) timer = null }, delay) } } <file_sep>/webpack-config-template/src/router/index.js import Vue from 'vue' import Router from 'vue-router' // import Home from 'components/home/home' // import TestA from 'components/test-a/test-a.vue' // import TestB from 'components/test-b/test-b.vue' // 使用动态载入 const Home = (resolve) => { import ('components/home/home').then((module) => { resolve(module) }) }; const TestA = (resolve) => { import ('components/test-a/test-a').then((module) => { resolve(module) }) }; const TestB = (resolve) => { import ('components/test-b/test-b').then((module) => { resolve(module) }) }; Vue.use(Router) const router = new Router({ routes: [{ // 所有未匹配到的路由,重定向到Index路由上 path: '*', redirect: { name: 'Index' } }, { path: '/', // 每个路由需要取名,采用帕斯卡风格 name: 'Index', redirect: { name: 'Home' } }, { path: '/home', name: 'Home', component: Home, // 利用meta保存一些元信息,用来设置跳转后的title meta: { title: '首页' } }, { path: '/testa', name: 'TestA', component: TestA, meta: { title: 'testa' } }, { path: '/testb', name: 'TestB', component: TestB, meta: { title: 'testb' } } ] }); // 注册全局守卫,路由到达前修改title router.beforeEach((to, from, next) => { if (to.meta && to.meta.title) { document.title = to.meta.title; } next(); }); export default router; <file_sep>/vue-custom-webpack-template(ts)/src/libs/filter.ts import Vue from 'vue' import dayjs from 'dayjs' Vue.filter('DateFormat', date => { if (!date) { return '' } return dayjs(date).format('YYYY-MM-DD HH:mm:ss') }) Vue.filter('DayFormat', date => { if (!date) { return '' } return dayjs(date).format('YYYY-MM-DD') }) <file_sep>/vue-ssr-template-ts-webpack/src/entry-server.js import createApp from './main' export default context => new Promise((resolve, reject) => { const { app, router, store } = createApp() // set current url router.push(context.url) //https://ssr.vuejs.org/zh/guide/structure.html#%E4%BD%BF%E7%94%A8-webpack-%E7%9A%84%E6%BA%90%E7%A0%81%E7%BB%93%E6%9E%84 router.onReady(() => { // 服务器端路由匹配 (server-side route matching) const matchedComponents = router.getMatchedComponents() if (!matchedComponents.length) { return reject(new Error('not found matching component')) } // call `asyncData()` method from components return Promise.all( matchedComponents.map(Component => { if (!context.headers.token) { return undefined } // 数据预取逻辑 (data pre-fetching logic) if (Component.asyncData) { return Component.asyncData({ store, route: router.currentRoute // cookie: context.headers.cookie }) } return undefined }) ) .then(() => { // state convert `window.__INITIAL_STATE__` and write into html context.state = store.state return resolve(app) }) .catch(reject) }, reject) }) <file_sep>/vue-ssr-template-ts-webpack/src/plugins/index.d.ts import Vue, { VueConstructor } from 'vue' import 'iview/types/index' import { AxiosInstance, AxiosStatic, AxiosPromise, AxiosInterceptorManager, AxiosResponse, AxiosRequestConfig, CancelStatic, CancelTokenStatic } from 'axios' declare global { interface Window { http: IAxiosInstance } } declare module 'vue/types/vue' { interface Vue { $http: IAxiosInstance iview } interface VueConstructor { $http: IAxiosInstance } } export interface IAxiosInstance extends AxiosInstance { upload: (url: any, params?: {}) => Promise<any> delPost: (url: any, params?: {}) => Promise<any> (config: AxiosRequestConfig): AxiosPromise (url: string, config?: AxiosRequestConfig): AxiosPromise defaults: AxiosRequestConfig interceptors: { request: AxiosInterceptorManager<AxiosRequestConfig> response: AxiosInterceptorManager<AxiosResponse> } } <file_sep>/vuepack/docs/sass-and-others.md # Sass & Others You may intend to use `sass-loader` or `less-loader` for the CSS section in `.vue` single file component, well, it's easy: ## Install the loader ```bash # for example, use sass npm install -D sass-loader node-sass ``` ## Update the tag `lang` attibute ```vue <style lang="scss"> $color: red; body { color: $color; } </style> ``` <file_sep>/vue-custom-webpack-template(ts)/src/router/system.ts const systemRoute = { path: '/system', component: () => import('@/views/Index.vue'), children: [ { path: '', meta: { title: '系统管理', icon: 'el-icon-setting', code: 'SY001' }, component: () => import('@/views/system/Index.vue'), children: [ { path: 'menus', name: 'menus', meta: { title: '菜单管理', code: 'SY001001', icon: 'el-icon-menu' }, component: () => import('@/views/system/menus/Index.vue') }, { path: 'category', name: 'category', meta: { title: '数据字典', code: '', icon: 'el-icon-notebook-1' }, component: () => import('@/views/system/category/Index.vue') }, { path: 'auth', name: 'auth', meta: { title: '权限管理', code: 'SY001006', icon: 'el-icon-user-solid' }, component: () => import('@/views/system/auth/Index.vue') }, { path: 'process', name: 'process', meta: { title: '流程设置', code: 'SY001004', icon: 'szyd-icon-process' }, component: () => import('@/views/system/process/Index.vue') }, { path: 'systemLog', name: 'systemLog', meta: { title: '系统日志', code: 'SY001005', icon: 'el-icon-time' }, component: () => import('@/views/system/log/Index.vue') } ] } ] } export default systemRoute <file_sep>/vue-custom-webpack-template(ts)/src/plugins/axios.ts import Vue, { PluginObject } from 'vue' import router from '@/router/index' import axios from 'axios' import { Notification } from 'element-ui' import { IAxiosInstance } from './index' import { get } from 'lodash' // import UAParser from 'ua-parser-js' // Full config: https://github.com/axios/axios#request-config // axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || ''; // axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; // let parser = new UAParser() const config = { // baseURL: process.env.baseURL || process.env.apiUrl || "" timeout: 60 * 1000 // Timeout // withCredentials: true, // Check cross-site Access-Control } // @ts-ignore: Unreachable code error export const _axios: IAxiosInstance = axios.create(config) // @ts-ignore: Unreachable code error export const _axios_download: IAxiosInstance = axios.create(config) _axios.interceptors.request.use( cfg => { cfg.headers['Authorization'] = `Bearer ${sessionStorage.getItem('Authorization')}` return cfg }, err => { return Promise.reject(err) } ) _axios_download.interceptors.request.use( cfg => { cfg.headers['Authorization'] = `Bearer ${sessionStorage.getItem('Authorization')}` return cfg }, err => { return Promise.reject(err) } ) /** * 解析下载的文件,可能为后端返回的报错信息 * @param data 下载的数据blob */ function checkDownload(data) { return new Promise((resolve, reject) => { let reader = new FileReader() reader.onload = (evt: any) => { try { let jsonFile = JSON.parse(evt.target.result) const loginSuccess: boolean = get(jsonFile, 'data.loginSuccess', true) if (jsonFile.status === 403 || ['token 已过期!', 'token 非法无效!'].includes(jsonFile.message) || !loginSuccess) { // 登录存在问题 reject(jsonFile.message) } else { resolve() } } catch (error) { // json解析失败,为其他格式文件,下载 // console.log('非json文件,提示下载') resolve(error) } } reader.readAsText(data) }) } let notify: any = null // 单一错误通知,避免多次通知登录失败 _axios_download.interceptors.response.use( async response => { const { data } = response let valid = await checkDownload(data).catch(err => { notify && notify.close() notify = Notification.error(`登录已失效! ${err} 请重新登录`) sessionStorage.clear() sessionStorage.setItem('Authorization', '') setTimeout(() => { router.push({ name: 'login' }) }, 1000) }) if (valid) { if (response.status >= 200 && response.status < 300) { // let browser = parser.getBrowser() // let { name = '' } = browser ? browser : {} if (navigator.msSaveOrOpenBlob) { let blob = new Blob([data]) let parse = decodeURIComponent(response.headers['filename']) // 解码中文 navigator.msSaveOrOpenBlob(blob, parse) } else { // 非ie let blob = new Blob([data]) let downloadElement = document.createElement('a') let href = window.URL.createObjectURL(blob) //创建下载的链接 downloadElement.href = href let parse = decodeURIComponent(response.headers['filename']) // 解码中文 downloadElement.download = parse //下载后文件名 document.body.appendChild(downloadElement) downloadElement.click() //点击下载 document.body.removeChild(downloadElement) //下载完成移除元素 window.URL.revokeObjectURL(href) //释放掉blob对象 } return response.data } else { Notification.error(`请求错误:${response.status}`) return Promise.reject(response) } } else { return Promise.reject(response) } }, error => { // Notification.error(`请求错误:${error}`) return Promise.reject(error) } ) _axios.interceptors.response.use( res => { const { data } = res const loginSuccess: boolean = get(data, 'data.loginSuccess', true) if (res.status == 200 && data.success) { return data } else if (data.status === 403 || ['token 已过期!', 'token 非法无效!'].includes(data.message) || !loginSuccess) { notify && notify.close() notify = Notification.error(`登录已失效! ${data.message} 请重新登录`) sessionStorage.clear() sessionStorage.setItem('Authorization', '') setTimeout(() => { router.push({ name: 'login' }) // router.replace({ path:'/login'}) // window.location.replace('/login') }, 1000) return Promise.reject(data) } else { if (data) { const { message, msg } = data data.message = data.message ? message : msg } return Promise.reject(data) } }, err => { return Promise.reject(err) } ) ;(_axios as IAxiosInstance).get = (url, params = {}) => { let config = { method: 'get', url, params: params, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } return _axios(config).catch(error => { return Promise.reject(error) }) } //=======================添加upload方法=================== ;(_axios as IAxiosInstance).upload = (url, params = {}) => { let config = { method: 'post', url, data: params, headers: { 'Content-Type': 'multipart/form-data' } } return _axios(config).catch(error => { return Promise.reject(error) }) } //===================添加delPost方法========================= ;(_axios as IAxiosInstance).delPost = (url, params = {}) => { let config = { method: 'delete', url, data: params, headers: { 'Content-Type': 'application/json;charset=UTF-8' } } return _axios(config).catch(error => { return Promise.reject(error) }) } //===================添加文件下载Get方法========================= ;(_axios_download as IAxiosInstance).getDownload = (url, params = {}) => { let config = { method: 'get', url, params: params, headers: { 'Content-Type': 'application/json;charset=UTF-8' }, responseType: 'blob' } return _axios_download(config).catch(error => { return Promise.reject(error) }) } //===================添加文件下载Post方法========================= ;(_axios_download as IAxiosInstance).postDownload = (url, params = {}) => { let config = { method: 'post', url, data: params, headers: { 'Content-Type': 'application/json;charset=UTF-8' }, responseType: 'blob' } return _axios_download(config).catch(error => { return Promise.reject(error) }) } const Plugin: PluginObject<any> = { install: Vue => { Vue.$http = _axios Vue.$http_download = _axios_download } } Plugin.install = Vue => { Vue.$http = _axios Vue.$http_download = _axios_download window.http = _axios Object.defineProperties(Vue.prototype, { $http: { get() { return _axios } }, $http_download: { get() { return _axios_download } } }) } Vue.use(Plugin) export default Plugin <file_sep>/vue-custom-webpack-single-spa/build/webpack.dev.js const baseConfig = require('./webpack.base') const webpackMerge = require('webpack-merge') const { HotModuleReplacementPlugin, DefinePlugin } = require('webpack') const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') const merge = require('lodash.merge') const devConfig = require('./devServeConf.js') const cssRule = { test: /\.(css|scss)$/, use: [ 'vue-style-loader', 'css-loader', 'postcss-loader', { loader: 'sass-loader', options: { sourceMap: true, data: '@import "@/assets/scss/variable.scss";' } } ] } baseConfig.module.rules.push(cssRule) module.exports = webpackMerge(baseConfig, { target: 'web', devtool: 'cheap-module-eval-source-map', output: { filename: 'js/[name].js' }, devServer: merge( { clientLogLevel: 'warning', contentBase: false, // since we use CopyWebpackPlugin. historyApiFallback: true, hot: true, compress: true, inline: true, overlay: true, host: 'localhost', port: 8000, open: true, quiet: true // necessary for FriendlyErrorsPlugin }, devConfig ), plugins: [ new DefinePlugin({ 'process.env': { NODE_ENV: '"development"' }, BASE_URL: '"./"' }), new HotModuleReplacementPlugin(), new FriendlyErrorsPlugin({ compilationSuccessInfo: { messages: [`项目运行地址: http://${devConfig.host}:${devConfig.port}`] } }) ] })
bd463462871a129c93eb845f37dc1732e0a188ea
[ "Markdown", "TypeScript", "JavaScript" ]
82
TypeScript
wenqieqiu/vue-template
63835d1b4fea1594bfad86386f61e8876228cd02
d2d2c417d4d224c93cce82a27960d70efbc5c99f
refs/heads/master
<repo_name>olivier-squid/jssdk-base-app<file_sep>/app/widgets/hello.js (function (root, factory) { root.squid_api.view.ContentView = factory(root.Backbone, root.squid_api); }(this, function (Backbone, squid_api) { var View = Backbone.View.extend({ template : null, initialize: function(options) { var Model; if (!this.model) { // create a default Model Model = Backbone.Model.extend(); this.model = new Model({"message" : null}); } // setup options if (options.template) { this.template = options.template; } else { this.template = app.template.hello; } // listen for model changes this.model.on('change', this.render, this); }, setModel: function(model) { this.model = model; this.initialize(); }, render: function() { // display var jsonData = this.model.toJSON(); var html = this.template(jsonData); this.$el.html(html); this.$el.show(); return this; } }); return View; })); <file_sep>/README.md jssdk-base-app ============== Base skeleton App for JSSDK. Handles user login and displays a status message in a sample widget. Uses a Bootstrap layout. Download/Clone a release and use it as a skeleton for your project. ## running Install the dependencies ``` npm install bower install ``` Trigger builds when code changes ``` grunt watch ```` Edit the app/main.js file to match your project's settings ``` squid_api.setup({ "clientId" : "local", "projectId" : null, "domainId" : null, "selection" : null }); ```` View the build results ``` open dist/index.html ````` ## build process 1. delete dist/ dir 2. compile handlebars templates 3. concat js and hbs files to main.js 4. copy assets, index.template.html and main.js to dist/ 5. dist/index.html is then modified by wiredep grunt task to inject javascript dependencies. 6. wiredepCopy copies the javascript dependencies to dist/bower_components
ae2f26428a3fa8a732d57620be1aa984a184bee9
[ "JavaScript", "Markdown" ]
2
JavaScript
olivier-squid/jssdk-base-app
85cdb9e290a367d77e056536a6242cc3acaac248
6ac0bed0ce6add1a1d592de9ddb6e4bf91e9e080
refs/heads/master
<repo_name>Endlessdev1/CCTV<file_sep>/README.md # CCTV CCTV &amp; Webcam Hacking ## Screenshot ![Screenshot](https://i.postimg.cc/JMHgPdV0/Screenshot-20200428-052825-Termux.jpg) ### Installation ``` git clone https://github.com/Err0r-ICA/CCTV.git cd CCTV python2 CCTV ``` ### My Accounts * [TELEGRAM](https://t.me/termuxxhacking) * [FACEBOOK](https://www.facebook.com/termuxxhacking) * [INSTAGRAM](https://instagram.com/termux_hacking) <file_sep>/LIST/fr.py #Jangan ganti author , hargai creator cape loh buat nya import requests,os,re,time b="\033[1;94m" g="\033[1;92m" w="\033[1;97m" r="\033[1;91m" y="\033[1;93m" cyan = "\033[1;96m" lgray = "\033[0;30m" dgray = "\033[1;90m" ir = "\033[0;101m" reset = "\033[0m" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} def france(): global page res = requests.get('https://www.insecam.org/en/bycountry/FR/', headers=headers) findpage = re.findall('"?page=",\s\d+', res.text)[1] rfindpage = findpage.replace('page=", ', '') print ("") time.sleep(1) print(" \033[1;92m +$$$$$$$$$$$$$$$$$$$$$$$$$$\033[1;91m*\033[1;92m$$$$$$$$$$$$$$$$$$$$$$+") print("\033[1;92m # \033[1;90mAuthor \033[1;90m -->>> \033[1;95m*\033[1;97mERR0R\033[1;95m*\033[1;92m #") print("\033[1;92m # \033[1;93mGithub \033[1;90m -->>> \033[1;90mhttps://github.com/Err0r-ICA \033[1;92m #") print("\033[1;92m # \033[1;95mTeam \033[1;90m -->>> \033[1;92mITALIA \033[1;97mCYBER \033[1;91mARMY \033[1;92m #") print("\033[1;92m # \033[1;91mInstagram\033[1;90m -->>> \033[1;97m@termux_hacking \033[1;92m #") print("\033[1;92m # \033[1;96mTelegram \033[1;90m -->>> \033[1;94mhttps://t.me/termuxxhacking \033[1;92m #") print("\033[1;92m # \033[1;97mVersion \033[1;90m -->>> \033[1;91m2.0 \033[1;92m #") print("\033[1;92m +$$$$$$$$$$$$$$$$$$$$$$$$$$\033[1;91m*\033[1;92m$$$$$$$$$$$$$$$$$$$$$$+") print ("") print(" \033[1;93m [ \033[1;92mList page : \033[1;93m]\033[1;92m") print ("") run() def run(): try: page = input("\033[1;93m [ \033[1;92mPage \033[1;93m]\033[1;37m -->>> ") url = ("https://www.insecam.org/en/bycountry/FR/?page="+str(page)) print ("") res = requests.get(url, headers=headers) findip = re.findall('http://\d+.\d+.\d+.\d+:\d+', res.text) count = 1 for _ in findip: hasil = findip[count] print ("{}[ {}{} {}]").format(r,w,hasil,r) count += 1 except: print "" print r+"Thanks for using our tools"+w
3f8f1273f426b12d8b4bca0b240af44fe17c2e77
[ "Markdown", "Python" ]
2
Markdown
Endlessdev1/CCTV
ca4403ff89c54f8c6afe2e1e7b2443f1b6b45bf1
2ebf274ced14ccd488419db3b224fed2787b8f52