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 | <file_sep># Simple NTLM ProxyCommand for SSH
This tool allows you to easily use SSH behind a corporate NTLM firewall, *without providing any credentials*.
## Requirements
* Windows (sorry, the lib that magically gets your credentials is Windows-only)
* corporate proxy address
* another (https) proxy that allows `CONNECT` to any host:port
## Configuration
Your `~/.ssh/config` could look like this then:
```
Host github.com
User git
ProxyCommand /c/some/where/simple-ntlm-proxy -dest %h:%p -corp-proxy "some-proxy.corpintra.net:3128" -hop-proxy "https://user:[email protected]:443"
```
<file_sep>module simple-ntlm-proxy
go 1.12
require (
github.com/anynines/go-ntlm-auth v0.0.0-20170912103015-eff1ed18c75d
github.com/anynines/go-proxy-setup-ntlm v0.0.0-20171026093854-638c5b468c2e
)
<file_sep>package main
import (
"bytes"
"crypto/tls"
"encoding/base64"
"flag"
"io"
"log"
"net"
"net/url"
"os"
"sync"
"time"
"github.com/anynines/go-proxy-setup-ntlm/proxysetup/ntlm"
)
var corpProxyAddr = flag.String("corp-proxy", "corp.proxy.net:3128", "The addr of the ntlm proxy.")
var hopProxyAddr = flag.String("hop-proxy", "https://user:[email protected]:443", "The hop proxy that allows CONNECT to anything")
var destAddr = flag.String("dest", "dest-host:1234", "The addr endpoint to connect to")
func init() {
flag.Parse()
}
func handleConn(localConn io.ReadWriteCloser) {
// connect corp proxy
dialer := &net.Dialer{
KeepAlive: 30 * time.Second,
Timeout: 30 * time.Second,
}
remoteConn, err := dialer.Dial("tcp", *corpProxyAddr)
if err != nil {
log.Fatalln("error dial:", err)
return
}
hopProxyUrl, err := url.Parse(*hopProxyAddr)
if err != nil {
log.Fatalln("error parsing proxy addr:", err)
return
}
err = ntlm.ProxySetup(remoteConn, hopProxyUrl.Host)
if err != nil {
log.Fatalln("error proxy injection:", err)
return
}
if hopProxyUrl.Scheme == "https" {
// create ssl to my proxy
sslConn := tls.Client(remoteConn, &tls.Config{
ServerName: hopProxyUrl.Hostname(),
})
remoteConn = sslConn
err = sslConn.Handshake()
}
// CONNECT via my proxy to some test server
connectLine := "CONNECT " + *destAddr + " HTTP/1.1\n"
if hopProxyUrl.User != nil {
base64credentials := base64.StdEncoding.EncodeToString([]byte(hopProxyUrl.User.String()))
connectLine += "Proxy-Authorization: Basic " + base64credentials + "\n"
}
connectLine += "\n"
_, err = remoteConn.Write([]byte(connectLine))
if err != nil {
log.Fatalln("error writing connect:", err)
return
}
buffer := make([]byte, 256)
n, err := remoteConn.Read(buffer)
if err != nil {
log.Fatalln("error reading connect:", err)
return
}
if !bytes.HasPrefix(buffer, []byte("HTTP/1.1 200 OK")) {
log.Println("no HTTP OK", n, string(buffer), err)
return
}
for n == len(buffer) {
n, _ = remoteConn.Read(buffer)
}
wg := &sync.WaitGroup{}
wg.Add(2)
go func() {
io.Copy(localConn, remoteConn)
remoteConn.Close()
localConn.Close()
wg.Done()
}()
go func() {
io.Copy(remoteConn, localConn)
remoteConn.Close()
localConn.Close()
wg.Done()
}()
wg.Wait()
}
type inout struct {
in io.ReadCloser
out io.WriteCloser
}
func (x inout) Close() error {
err := x.in.Close()
err2 := x.out.Close()
if err != nil {
return err
}
return err2
}
func (x inout) Read(b []byte) (n int, err error) {
return x.in.Read(b)
}
func (x inout) Write(b []byte) (n int, err error) {
return x.out.Write(b)
}
func main() {
handleConn(inout{
in: os.Stdin,
out: os.Stdout,
})
}
| 901e408c754bdbc8a40755b006587ccf5cde6bfd | [
"Markdown",
"Go Module",
"Go"
]
| 3 | Markdown | Hades32/simple-ntlm-proxy | 46f2410bb59ed0d04e740cf01cd764e4541fc61f | 5d815ea5c957f01ff1f25473bbb2a2eb83243d7a |
refs/heads/master | <repo_name>miy4/huecli<file_sep>/main.go
package main
import (
"os"
"github.com/jawher/mow.cli"
)
func newApp() *cli.Cli {
app := cli.App("huecli", "A simple CLI for Philips Hue. Just to flip it on and off.")
for _, cmd := range Commands {
app.Command(cmd.Name, cmd.Desc, cmd.Init)
}
return app
}
func main() {
newApp().Run(os.Args)
}
<file_sep>/color/rgb.go
package color
import "fmt"
import "math"
type RGB struct {
R, G, B float64
}
func hexToRGB(s string) (*RGB, error) {
format := "#%02x%02x%02x"
factor := 1.0 / 255.0
var r, g, b uint8
n, err := fmt.Sscanf(s, format, &r, &g, &b)
if err != nil {
return nil, err
}
if n != 3 {
return nil, fmt.Errorf("conversion failed: %v is not a hex color", s)
}
return &RGB{float64(r) * factor, float64(g) * factor, float64(b) * factor}, nil
}
func applyGammaCorrection(value float64) float64 {
if value > 0.04045 {
return math.Pow((value+0.055)/(1.0+0.055), 2.4)
}
return value / 12.92
}
func RGBToXY(s string) (float64, float64, error) {
rgb, err := hexToRGB(s)
if err != nil {
return -1.0, -1.0, err
}
// https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
red := applyGammaCorrection(rgb.R)
green := applyGammaCorrection(rgb.G)
blue := applyGammaCorrection(rgb.B)
X := red*0.649926 + green*0.103455 + blue*0.197109
Y := red*0.234327 + green*0.743075 + blue*0.022598
Z := red*0.0000000 + green*0.053077 + blue*1.035763
x := X / (X + Y + Z)
y := Y / (X + Y + Z)
return x, y, nil
}
<file_sep>/README.md
# huecli
A simple CLI for Philips Hue. Just to flip it on and off.
## Install
```bash
$ go get github.com/miy4/huecli
```
## Commands
### register
Register new user.
```bash
$ huecli register
```
You must go to the bridge, press the button and then, run `huecli register` within 30 seconds.
Registered user information will be saved to `~/.hue.json`.
### on
Turn on all the lights.
```bash
$ huecli on [--color COLOR] [--bri BRIGHTNESS] [--hue HUE] [--sat SATURATION] [--ct TEMPERATURE]
```
- `COLOR` the color, where value from #000000 to #FFFFFF.
- `BRIGHTNESS` the brightness, where value from 0 to 255.
- `HUE` the hue, where value from 0 to 65535.
- `SATURATION` the saturation where value from 0 to 255.
- `TEMPERATURE` the color temperature where value from 153 to 500.
### off
Turn off all of the lights.
```bash
$ huecli off
```
<file_sep>/app.go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/jawher/mow.cli"
"github.com/miy4/huecli/api"
"github.com/miy4/huecli/color"
)
const (
ExitCodeOK = iota
ExitCodeRegisterCommandError
ExitCodeOnCommandError
ExitCodeOffCommandError
)
const (
configFile = ".hue.json"
)
type Command struct {
Name string
Desc string
Init cli.CmdInitializer
}
var Commands = []Command{
commandRegister,
commandOn,
commandOff,
}
var commandRegister = Command{
"register",
"register new user",
func(cmd *cli.Cmd) {
cmd.Action = func() {
if err := registerUser(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(ExitCodeRegisterCommandError)
}
}
},
}
var commandOn = Command{
"on",
"turn on the lights",
func(cmd *cli.Cmd) {
color := cmd.StringOpt("c color", "", "the color, where value from #000000 to #FFFFFF.")
brightness := cmd.IntOpt("b bri", -1, "the brightness, where value from 0 to 255.")
hue := cmd.IntOpt("h hue", -1, "the hue, where value from 0 to 65535.")
saturation := cmd.IntOpt("s sat", -1, "the saturation, where value from 0 to 255.")
temperature := cmd.IntOpt("t ct", -1, "the color temperature, where value from 153 to 500.")
cmd.Action = func() {
state := api.LightState{
Color: *color,
Brightness: *brightness,
Hue: *hue,
Saturation: *saturation,
Temperature: *temperature,
}
if err := turnOnLights(&state); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(ExitCodeOnCommandError)
}
}
},
}
var commandOff = Command{
"off",
"turn off the lights",
func(cmd *cli.Cmd) {
cmd.Action = func() {
if err := turnOffLights(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(ExitCodeOffCommandError)
}
}
},
}
func exportConfig(hue *api.Hue, configPath string) error {
file, err := json.Marshal(*hue)
if err != nil {
return err
}
if err = ioutil.WriteFile(configPath, file, 0600); err != nil {
return err
}
return nil
}
func importConfig(configPath string) (*api.Hue, error) {
file, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, err
}
var hue api.Hue
if err := json.Unmarshal(file, &hue); err != nil {
return nil, err
}
return &hue, nil
}
func registerUser() error {
var hue api.Hue
ipAddr, err := hue.GetBridgeIP()
if err != nil {
return err
}
hue.IpAddress = ipAddr
user, err := hue.RegisterUser()
if err != nil {
return err
}
hue.UserName = user
configPath := filepath.Join(os.Getenv("HOME"), configFile)
err = exportConfig(&hue, configPath)
if err != nil {
return err
}
return nil
}
func lightStateToParams(state *api.LightState) (map[string]interface{}, error) {
params := make(map[string]interface{})
params["on"] = state.On
if state.Color != "" {
x, y, err := color.RGBToXY(state.Color)
if err != nil {
return nil, err
}
params["xy"] = [2]float64{x, y}
}
if state.Brightness != -1 {
if state.Brightness < 0 || state.Brightness > 255 {
return nil, fmt.Errorf("brightness out of range: %s", state.Brightness)
}
params["bri"] = state.Brightness
}
if state.Hue != -1 {
if state.Hue < 0 || state.Hue > 65535 {
return nil, fmt.Errorf("hue out of range: %s", state.Hue)
}
params["hue"] = state.Hue
}
if state.Saturation != -1 {
if state.Saturation < 0 || state.Saturation > 255 {
return nil, fmt.Errorf("saturation out of range: %s", state.Saturation)
}
params["sat"] = state.Saturation
}
if state.Temperature != -1 {
if state.Temperature < 153 || state.Temperature > 500 {
return nil, fmt.Errorf("color temperature out of range: %s", state.Temperature)
}
params["ct"] = state.Temperature
}
return params, nil
}
func turnOnLights(state *api.LightState) error {
configPath := filepath.Join(os.Getenv("HOME"), configFile)
hue, err := importConfig(configPath)
if err != nil {
return err
}
lights, err := hue.GetAllLights()
if err != nil {
return err
}
state.On = true
params, err := lightStateToParams(state)
if err != nil {
return nil
}
for _, light := range lights {
err = hue.SetLightState(light, params)
if err != nil {
return err
}
}
return nil
}
func turnOffLights() error {
configPath := filepath.Join(os.Getenv("HOME"), configFile)
hue, err := importConfig(configPath)
if err != nil {
return err
}
lights, err := hue.GetAllLights()
if err != nil {
return err
}
params := map[string]interface{}{"on": false}
for _, light := range lights {
err = hue.SetLightState(light, params)
if err != nil {
return err
}
}
return nil
}
<file_sep>/api/api.go
package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"time"
)
type Hue struct {
IpAddress string `json:"ipAddress"`
UserName string `json:"userName"`
}
type Light struct {
Id string
}
type LightState struct {
On bool
Color string
Brightness int
Hue int
Saturation int
Temperature int
Effect string
}
type Bridge struct {
Serial string `json:"id"`
IpAddrress string `json:"internalipaddress"`
}
var httpClient = &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, 2*time.Second)
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(2 * time.Second))
return conn, nil
},
},
}
func nupnpSearch() (*[]Bridge, error) {
response, err := http.Get("https://www.meethue.com/api/nupnp")
if err != nil {
return nil, err
}
defer response.Body.Close()
var bridges []Bridge
err = json.NewDecoder(response.Body).Decode(&bridges)
if err != nil {
return nil, err
}
return &bridges, nil
}
func (hue *Hue) GetBridgeIP() (string, error) {
b, err := nupnpSearch()
if err != nil {
return "", err
}
bridges := *b
if len(bridges) <= 0 {
return "", errors.New("bridges not found")
}
return bridges[0].IpAddrress, nil
}
func (hue *Hue) RegisterUser() (string, error) {
params := map[string]string{"devicetype": "Golang API: huecli"}
requestBody, err := json.Marshal(params)
if err != nil {
return "", err
}
uri := fmt.Sprintf("http://%s/api", hue.IpAddress)
response, err := httpClient.Post(uri, "text/json", bytes.NewReader(requestBody))
if err != nil {
return "", err
}
defer response.Body.Close()
var results []map[string]map[string]string
json.NewDecoder(response.Body).Decode(&results)
username := results[0]["success"]["username"]
return username, nil
}
//func (hue *Hue) SetLightState(state LightState) error {
func (hue *Hue) SetLightState(light *Light, params map[string]interface{}) error {
requestBody, err := json.Marshal(params)
if err != nil {
return err
}
uri := fmt.Sprintf("http://%s/api/%s/lights/%s/state", hue.IpAddress, hue.UserName, light.Id)
httpRequest, err := http.NewRequest("PUT", uri, bytes.NewReader(requestBody))
if err != nil {
return err
}
response, err := httpClient.Do(httpRequest)
if err != nil {
return err
}
defer response.Body.Close()
var results []map[string]interface{}
err = json.NewDecoder(response.Body).Decode(&results)
return err
}
func (hue *Hue) GetAllLights() ([]*Light, error) {
uri := fmt.Sprintf("http://%s/api/%s/lights", hue.IpAddress, hue.UserName)
response, err := httpClient.Get(uri)
if err != nil {
return nil, err
}
defer response.Body.Close()
var results map[string]interface{}
err = json.NewDecoder(response.Body).Decode(&results)
if err != nil {
return nil, err
}
var lights []*Light
for id := range results {
light := Light{Id: id}
lights = append(lights, &light)
}
return lights, nil
}
| 2e0e29e5fad8533560d10e5711b09385562ff2b5 | [
"Markdown",
"Go"
]
| 5 | Go | miy4/huecli | d469491dcfd5e59d13e7fe47d75ceb63b537e5f0 | dc489893f76180e18d595f012076b99a7153708c |
refs/heads/master | <repo_name>biellsantiago/GasolinaXAlcoolBinding<file_sep>/app/src/main/java/com/gabriel/gasolinaxalcool/Combustivel.java
package com.gabriel.gasolinaxalcool;
import java.io.Serializable;
import java.util.Observable;
/**
* Created by GABRIEL on 02/08/2016.
*/
public class Combustivel extends Observable implements Serializable {
public static final int RESULT_NENHUM = 0;
public static final int RESULT_ALCOOL = 1;
public static final int RESULT_GASOLINA = 2;
private String gasolina;
private String etanol;
private int textoResultado;
private int resultado;
public Combustivel(int textoResultado) {
this.textoResultado = R.string.texto_resultado_nenhum;
}
public int getTextoResultado() {
return textoResultado;
}
public void setTextoResultado(int textoResultado) {
this.textoResultado = textoResultado;
}
public int getResultado() {
return resultado;
}
public void setResultado(int resultado) {
this.resultado = resultado;
}
public String getEtanol() {
return etanol;
}
public void setEtanol(String etanol) {
this.etanol = etanol;
}
public String getGasolina() {
return gasolina;
}
public void setGasolina(String gasolina) {
this.gasolina = gasolina;
}
}
| 7f9049cbcb951965b627382343908227242fcf87 | [
"Java"
]
| 1 | Java | biellsantiago/GasolinaXAlcoolBinding | 0fdbd18e3d639c1f4b6eead40d2321ab2bbfc733 | 40fba3cda5602f2d6021644e014862421b6c30e7 |
refs/heads/master | <repo_name>sid17/CompilersProject<file_sep>/asgn2/include/regexDefination.py
from tokensDefination import *
# regular expression for simple tokens
t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_BLOCK_BEGIN = r'{'
t_BLOCK_END = r'}'
t_STATE_END = r';'
t_COLON = r':'
t_ASSIGN = r'='
t_EQUAL = r'=='
t_NEQUAL = r'!='
t_GREATER = r'>'
t_GEQ = r'>='
t_LESS = r'<'
t_LEQ = r'<='
t_DOT = r'\.'
t_LBPAREN = r'\['
t_RBPAREN = r'\]'
t_CHOOSE = r'<-'
t_EXACTEQ = r'=:='
t_SUBTYPE = r'<:<'
t_VIEWABLE = r'<%<'
t_STRING_CONST = r'"(?:\\.|[^"\\])*"'
t_CHARACTER = r'\'([^\\\'\r\n]|\\[^\r\n]|\\u[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])(\'|\\)'
t_TILDA = r'\~'
t_NOT = r'!'
t_COMMA = r','
t_UNDER = r'_'
t_AND = r'&&'
t_OR = r'\|\|'
t_AND_BITWISE = r'&'
t_OR_BITWISE = r'\|'
t_FUNTYPE = r'=>'
t_LOWER_BOUND = r'>:'
t_UPPER_BOUND = r'<:'
t_VIEW = r'<%'
t_INNER_CLASS = r'\#'
t_AT = r'@'
t_QUESTION = r'\?'
t_COMM = r'::'
t_TIMES_ASSIGN = r'\*='
t_DIVIDE_ASSIGN = r'/='
t_REMAINDER_ASSIGN = r'%='
t_PLUS_ASSIGN = r'\+='
t_MINUS_ASSIGN = r'-='
t_LSHIFT_ASSIGN = r'<<='
t_RSHIFT_ASSIGN = r'>>='
t_AND_ASSIGN = r'&='
t_OR_ASSIGN = r'\|='
t_XOR_ASSIGN = r'\^='
t_XOR = r'\^'
t_LSHIFT = r'<<'
t_RSHIFT = r'>>'
t_REMAINDER = r'%'
# Floating literal
def t_FLOAT_CONST(t):
r'((\d+)(\.)(\d+)([Ee][+-]?(\d+))?([FfDd])?)|((\.)(\d+)([Ee][+-]?(\d+))?([FfDd])?)|((\d+)([Ee][+-]?(\d+))([FfDd])?)|((\d+)([Ee][+-]?(\d+))?([FfDd]))' #r'((\d+)(\.\d+)(e(\+|-)?(\d+))?|(\d+)e(\+|-)?(\d+))([lL]|[fF])?'
# print
if (t.value[-1]=='F' or t.value[-1]=='f' or t.value[-1]=='D' or t.value[-1]=='d'):
t.value=t.value[:-1]
# print t.value
t.value = float(t.value)
return t
# Integer literal
def t_INT_CONST(t):
r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU]|[lL]|[uU][lL]|[lL][uU])?)'
t.value = int(t.value)
return t
# Identifier will match itself as well as the other keywords
def t_IDENTIFIER(t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
t.type = reserved.get(t.value, 'IDENTIFIER') # check for reserved values
return t
# track line numbers
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
# return t
pass
# a string for ignored characters
t_ignore = ' \t'
# error handling rule
def t_error(t):
print "Illegal character '%s'" % t.value[0]
t.lexer.skip(1)
pass
def t_MULTIPLE_COMMENT(t):
r'(/\*(.|\n)*?\*/)'
t.lexer.lineno += t.value.count('\n')
def t_SINGLE_COMMENT(t):
r'(//.*?\n)'
t.lexer.lineno += t.value.count('\n')<file_sep>/README.md
# CompilersProject
This is the repository for
Scala Compiler, the Scala to MIPS compiler hosted at [IITK](https://git.cse.iitk.ac.in/smanocha/compilersproject) and [Github](https://github.com/sid17/CompilersProject)
## Contributors
* [<NAME>](http://home.iitk.ac.in/~smanocha)
* [<NAME>](http://home.iitk.ac.in/~satvikg)
* [<NAME>](http://home.iitk.ac.in/~sshekh)
## Credits
This project is done as a part of CS335 course at IIT Kanpur under the guidance of
[Dr.Subhajit Roy](http://web.cse.iitk.ac.in/users/subhajit/).
## Description
### LEXER
Refer to the Readme.md file under Assignment1
## Compilation Instructions
* cd asgn1
* make
* bin/lexer test/HelloWorld.scala
<file_sep>/asgn4/include/mips.py
varStart="temp"
globalTempShootDown=0;
def loadStackAddress(SCOPE,currElement,variable):
retval=list()
if '__' in variable:
startname=variable.split('__')[0]
variable="__".join(variable.split('__')[1:])
if (startname!=currElement.name):
print 'Cannot support access links right now'
print currElement.name
print startname
print variable
assert(False)
variable = variable.split( )[0]
value=currElement.get_attribute_value(variable,'stackOffset',"symbol")
retval.append(str(value)+"($fp)")
return retval
def printCode123(SCOPE,currElement):
# print len(currElement.tempvar)
for i in currElement.code :
print i
t=dict()
for x in range(len(i)):
prev=""
if (x>0):
prev=i[x-1]
# print i[x]
if not (i[x]==None or type(i[x]) !=type("@") or ':' in i[x] or prev=='Lcall'):
if ("@" in i[x]) or (len(i[x])>6 and i[x][0:4]=="node" and '__' in i[x]):
if (i[x] != None and type(i[x]) ==type("@") and "@" in i[x]):
i[x] = i[x].replace("@", "")
retval=loadStackAddress(SCOPE,currElement,i[x])
if (len(retval)>1):
print 'Will handle access links here'
else:
t1 = returnTemp();
i[x]=retval[0];
print "lw $"+t1+", "+i[x];
t[x]= t1;
# print i[x]
if i[3] == '|' :
print "or "+t[0] +","+t[2]+","+t[4];
elif i[3] == '^' :
print "xor "+t[0] +","+t[2]+","+t[4];
elif i[3] == '&' :
print "and "+t[0] +","+t[2]+","+t[4];
elif i[2] == '==':
print "beq "+t[1]+","+t[3]+","+t[4];
elif i[2] == '!=':
print "bne "+t[1]+","+t[3]+","+t[4];
elif i[2] == '>':
t1 = returnTemp()
print "slt $"+t1+","+t[3]+","+t[1]
print "beq $"+t1+",1,"+i[4];
elif i[2] == '<' :
t1 = returnTemp()
print "slt $"+t1 +","+t[3]+","+t[1]
print "beq $"+t1+",$zero,"+i[4];
elif i[2] == '>=':
t1 = returnTemp()
print "slt $"+t1+","+t[3]+","+t[1]
print "beq $"+t1+",1,"+i[4];
print "beq "+t[1]+","+t[3]+","+i[4];
elif i[2] == '<=' :
t1 = returnTemp();
print "slt $"+t1 +","+t[3]+","+t[1]
print "beq $"+t1+",$zero,"+i[4];
print "beq "+t[1]+","+t[3]+","+i[4];
elif i[3] == '<<':
print "sll "+t[0]+","+t[2]+","+t[4]
elif i[3] == '>>':
print "srl "+t[0]+","+t[2]+","+t[4]
elif i[3] == '+' :
print "add "+t[0]+","+t[2]+","+t[4]
elif i[3] == '-' :
print "sub "+t[0]+","+t[2]+","+t[4]
elif i[3] == '*':
print "mult "+t[2]+","+t[4]
print "mflo "+i[0]
elif i[3] == '/':
print "div "+t[2]+","+t[4]
print "mflo "+i[0]
elif i[3] == '%':
print "div "+t[2]+","+t[4]
print "mfhi "+i[0]
elif i[1] == '=' and i[2]!= 'Lcall' :
# print type(i[2])
if type(i[2]) == type(10):
t1 = returnTemp();
print "li $"+t1+", "+str(i[2]);
# else:
# # print i
# # print "lw $"+t1+", "+t[2];
print "sw $"+t1+", "+i[0];
elif i[2] == "== 1":
print "beq "+t[1]+",1,"+i[4];
elif i[3] == "goto":
print "b "+i[4] ;
elif ":" in i[3]:
print i[3]
# SCOPE.code.append(["if",p[3].holdingVariable,"== 1","goto",startLabelChild])
# tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable
def returnTemp():
global globalTempShootDown
globalTempShootDown+=1
return varStart+"_"+str(globalTempShootDown)
def traversetree123(SCOPE):
queue=list()
objects=list()
queue.append(SCOPE)
while len(queue) >0 :
currElement=queue[0]
del queue[0]
for i in range (len(currElement.childs)):
queue.append(currElement.childs[i])
printCode123(SCOPE,currElement)
def generateMips(SCOPE):
traversetree123(SCOPE)
<file_sep>/asgn3/include/tokensDefination.py
tokens = [
'PLUS',
'MINUS',
'TIMES',
'DIVIDE',
'LPAREN',
'RPAREN',
'BLOCK_BEGIN',
'BLOCK_END',
'STATE_END',
'IDENTIFIER',
'FLOAT_CONST',
'INT_CONST',
'STRING_CONST',
'CHARACTER',
'COLON',
'COMM',
'ASSIGN',
'EQUAL',
'NEQUAL',
'GREATER',
'GEQ',
'LESS',
'LEQ',
'DOT',
'LBPAREN',
'RBPAREN',
'CHOOSE',
'SUBTYPE',
'VIEWABLE',
'EXACTEQ',
'TILDA',
'NOT',
'COMMA',
'UNDER',
'AND',
'OR',
'AND_BITWISE',
'OR_BITWISE',
'FUNTYPE',
'LOWER_BOUND',
'UPPER_BOUND',
'VIEW',
'INNER_CLASS',
'AT',
'QUESTION',
'TIMES_ASSIGN',
'DIVIDE_ASSIGN',
'REMAINDER_ASSIGN',
'PLUS_ASSIGN',
'MINUS_ASSIGN',
'LSHIFT_ASSIGN',
'RSHIFT_ASSIGN',
'AND_ASSIGN',
'OR_ASSIGN',
'XOR_ASSIGN',
'XOR',
'LSHIFT',
'RSHIFT',
'REMAINDER',
'newline'
]
reserved = {
'abstract' : 'KWRD_ABST',
'case' : 'KWRD_CASE',
'catch' : 'KWRD_CATCH',
'class' : 'KWRD_CLASS',
'def' : 'KWRD_DEF',
'do' : 'KWRD_DO',
'else' : 'KWRD_ELSE',
'extends' : 'KWRD_EXTNDS',
'false' : 'BOOL_CONSTF',
'final' : 'KWRD_FINAL',
'finally' : 'KWRD_FINALLY',
'for' : 'KWRD_FOR',
'foreach' : 'KWRD_FOREACH',
'forsome' : 'KWRD_FORSOME',
'if' : 'KWRD_IF',
'implicit' : 'KWRD_IMPLICIT',
'import' : 'KWRD_IMPORT',
'lazy' : 'KWRD_LAZY',
'match' : 'KWRD_MATCH',
'new' : 'KWRD_NEW',
'Nil' : 'NIL',
'null' : 'KWRD_NULL',
'object' : 'KWRD_OBJECT',
'override' : 'KWRD_OVERRIDE',
'package' : 'KWRD_PACKAGE',
'private' : 'KWRD_PRIVATE',
'protected' : 'KWRD_PROTECTED',
'public' : 'KWRD_PUBLIC',
'return' : 'KWRD_RETURN',
'sealed' : 'KWRD_SEALED',
'static' : 'KWRD_STATIC',
'super' : 'KWRD_SUPER',
'this' : 'KWRD_THIS',
'throw' : 'KWRD_THROW',
'trait' : 'KWRD_TRAIT',
'try' : 'KWRD_TRY',
'true' : 'BOOL_CONSTT',
'type' : 'KWRD_TYPE',
'until' : 'KWRD_UNTIL',
'val' : 'KWRD_VAL',
'var' : 'KWRD_VAR',
'while' : 'KWRD_WHILE',
'with' : 'KWRD_WITH',
'yield' : 'KWRD_YIELD',
'Int' : 'TYPE_INT',
'Char' : 'TYPE_CHAR',
'String' : 'TYPE_STRING',
'Double' : 'TYPE_FLOAT',
'Boolean' : 'TYPE_BOOLEAN',
'Array' : 'KWRD_ARRAY',
'macro' : 'KWRD_MACRO',
'Unit' : 'TYPE_VOID',
'by' : 'KWRD_BY',
'to' : 'KWRD_TO'
}
tokens = tokens + list(reserved.values())
<file_sep>/asgn3/include/printLexerOutput.py
def printLexerCode(lexer,code_full):
# track the line numbers of the code and the parsed output
newlineno=lexer.lineno
parsed_output=[]
temp_code=code_full
temp_code=temp_code.split("\n")
# loop over the output obtained from lexer
for tok in lexer:
if (tok.lineno!=newlineno) :
print temp_code[newlineno-1],"\t","//",
for item in parsed_output:
print item,
parsed_output=[]
print '\n',
for i in xrange(newlineno,tok.lineno-1):
print temp_code[i]
parsed_output.append(tok.type)
newlineno=tok.lineno
else :
parsed_output.append(tok.type)
print temp_code[newlineno-1],"\t","//",
for item in parsed_output:
print item,
parsed_output=[]
def printLexerTokens(lexer,code_full):
newlineno=lexer.lineno
parsed_output=[]
temp_code=code_full
temp_code=temp_code.split("\n")
for tok in lexer:
if (tok.lineno!=newlineno) :
for item in parsed_output:
print str(item) + " "
parsed_output=[]
parsed_output.append(tok.value)
newlineno=tok.lineno
else :
parsed_output.append(tok.value)
for item in parsed_output:
print str(item) + " "
parsed_output=[]
<file_sep>/asgn4/include/symbolTable_old.py
# #Hashtable Class: it contains the table
# #self.table is dictionary with key=name_of_entry & value=list_of_attributes eg: a=5.. then name='a'(i.e. lexeme) attribute={'value':5} .. note ada is case-insensitive
# #list_of_attributes is a dictionary (list is implemented as dictionary) with many entries with key(attribute_name):value(attribute_value) pairs like - {'type': 'Integer', 'value':'Integer', 'isdatatype':True}
# #Hash table is a dictionary of dictionary based on the name then based on the attributes value
# #Accessed using .table and value is table[name][attribute value]
# class HashTable:
# def __init__(self):
# self.table={} # a dictionary
# def add_entry (self, name, list_attributes):
# if name in self.table:
# print 'Error: Entry already present - [' + name + ']'
# assert(False)
# else:
# self.table[name]= {} # a dictionary
# for i_key in list_attributes:
# self.table[name][i_key]=list_attributes[i_key]
# #update if already present else add it.
# def update_entry(self, name, attribute_name, attribute_value):
# try: #try catch exception
# self.table[name][attribute_name] = attribute_value
# return True
# except:
# return False
# def get_attribute_value (self, name, attribute_name):
# try:
# return self.table[name][attribute_name]
# except:
# return None
# def is_present(self, name):
# if name in self.table:
# return True
# else:
# return False
# def get_table(self):
# return self.table
# def print_table(self):
# print "Table is : Entry name ==> Attribute_list"
# for name in self.table:
# print name,' ==> ', self.table[name]
# class arrayObject:
# def __init__(self,dataType,size):
# self.dataType=dataType # a dictionary
# self.size=size
# # class classObject:
# # def __init__(self):
# # self.table={} # a dictionary
# #Environment Class: Contains current symbolTable and pointer to parent Environment
# from sets import Set
# class Env:
# static_var = 1
# def __init__(self, prev=None):
# self.symbolTable = HashTable() #Creates a new symbol table for a new scope
# self.functionTable = HashTable() #Creates a new hash table for a new scope
# self.objectTable = HashTable() #Creates a new hash table for a new scope
# self.name = "node" + str(Env.static_var)
# self.childs=[]
# self.width = 0 # overall offset/width of this env
# self.paramwidth = 0
# self.prev_env=prev
# self.code=list()
# self.startChildBlock=None
# self.endChildBlock=None
# self.funcName=None
# self.objName = None
# if prev==None:
# self.level=0
# self.parentName=""
# else:
# self.level=prev.level+1
# self.parentName=prev.name
# Env.static_var+=1 # pointer to the previous hash table
# if (prev != None):
# prev.childs.append(self)
# self.tempvar = Set([])
# def gprev(self):
# return self.prev
# def goto(self,data):
# for child in range(0,len(self.childs)):
# # print self.node[child].name
# if(self.childs[child].name==data):
# return self.node[child]
# def subtree(self):
# "Gets the node by name"
# print self.name,":::",self.level,':::',self.parentName
# self.symbolTable.print_table()
# for child in range(0,len(self.childs)):
# # print self.node[child].name
# self.childs[child].subtree()
# # if(self.node[child].name==data):
# # return self.node[child]
# #adds entry in current hashtable
# def add_entry(self,name, list_attributes,updateField="symbol"):
# if updateField=="symbol":
# self.symbolTable.add_entry(name, list_attributes)
# elif updateField=="function":
# self.functionTable.add_entry(name, list_attributes)
# elif updateField == "object":
# self.objectTable.add_entry(name, list_attributes)
# else:
# print "Attribute Missing"
# def ChildObj(self, ObjSearched):
# for child in range(0,len(self.childs)):
# if child.objName == ObjSearched:
# return child
# # print self.node[child].name
# # self.childs[child].subtree()
# # update entry in the most recent hash table in case not found in the most recent goes to the parent and then to next parent and
# # successive goes up till the time entry is found if not found found printf error (Checks if the variable used is previously declared)
# def update_entry(self, name, attribute_name, attribute_value,updateField="symbol"):
# if updateField=="symbol":
# env=self
# while env!=None:
# if env.symbolTable.update_entry(name, attribute_name, attribute_value) == True:
# return
# env=env.prev_env
# print 'Error: Variable not present for updation - [' + name + ']'
# elif updateField=="function":
# env=self
# while env!=None:
# if env.functionTable.update_entry(name, attribute_name, attribute_value) == True:
# return
# env=env.prev_env
# print 'Error: Function not present for updation - [' + name + ']'
# elif updateField=="object":
# env=self
# while env!=None:
# if env.objectTable.update_entry(name, attribute_name, attribute_value) == True:
# return
# env=env.prev_env
# print 'Error: Object not present for updation - [' + name + ']'
# else:
# print "Attribute Missing"
# #Returns list of attributes from most recent hashtable (recent ancestor) corresponding to name. Returns None if entry not found
# def get_attribute_value(self,name, attribute_name,updateField="symbol"):
# if updateField=="symbol":
# env=self
# while env!=None:
# found=env.symbolTable.get_attribute_value(name, attribute_name)
# if found != None:
# return found
# env=env.prev_env
# return None
# elif updateField=="function":
# env=self
# while env!=None:
# found=env.functionTable.get_attribute_value(name, attribute_name)
# if found != None:
# return found
# env=env.prev_env
# return None
# elif updateField=="object":
# env=self
# while env!=None:
# found=env.objectTable.get_attribute_value(name, attribute_name)
# if found != None:
# return found
# env=env.prev_env
# return None
# else:
# print "Attribute not found"
# def get_attribute_append_name(self,name,updateField="symbol"):
# if updateField=="symbol":
# env=self
# while env!=None:
# if env.symbolTable.is_present(name):
# return env.name
# env = env.prev_env
# elif updateField=="function":
# env=self
# while env!=None:
# if env.functionTable.is_present(name):
# return env.name
# env = env.prev_env
# elif updateField=="object":
# env=self
# while env!=None:
# if env.objectTable.is_present(name):
# return env.name
# env = env.prev_env
# else:
# print "Attribute not found"
# #returns table only in current scope, not ancestral ones
# def getCurrentSymbolTable(self):
# return self.symbolTable.get_table()
# #is_present in the current scope only
# # def is_present_current_block(self, name,updateField="sybmol"):
# # if (updateField=="symbol"):
# # return self.symbolTable.is_present(name)
# # elif (updateField=="function"):
# # return self.functionTable.is_present(name)
# # elif (updateField=="object"):
# # return self.objectTable.is_present(name)
# def is_present(self,name,updateField="symbol"):
# if updateField=="symbol":
# env=self
# while env!=None:
# if env.symbolTable.is_present(name):
# return True
# env = env.prev_env
# return False
# elif updateField=="function":
# env=self
# while env!=None:
# if env.functionTable.is_present(name):
# return True
# env = env.prev_env
# return False
# elif updateField=="object":
# env=self
# while env!=None:
# if env.objectTable.is_present(name):
# return True
# env = env.prev_env
# return False
# def print_table(self):
# env=self
# i=0
# while env!=None:
# print "Ancestor - ",i
# env.objectTable.print_table()
# env = env.prev_env
# i=i+1
# # ==========================================Dont know the use of the last four functions
# def get_width(self):
# return self.width
# def increment_width(self, inc): #similar to addwidth() in lecture notes
# self.width += inc
# def get_paramwidth(self):
# return self.paramwidth
# def increment_paramwidth(self, inc):
# self.paramwidth += inc
# # get_entry(self,name) #return full attribute list.
# # get_entryheight(self,name) #how many levles abov it was found
# if __name__ == '__main__':
# OBJ = Env(None)
# # print Env.static_var
# dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
# OBJ.add_entry('Hello',dict)
# print OBJ.get_attribute_value('Hello','Beth')
# dict = {'Alice': '323', 'Beth': '91223', 'Cecil': '3223'}
# OBJ.add_entry('Hel',dict)
# print OBJ.is_present('Hel')
# OBJ1 = Env(OBJ)
# dict = {'Alice': '22', 'Beth': '91', 'Cecil': '32'}
# OBJ1.add_entry('Hello1',dict)
# print OBJ.get_attribute_value('Hello','Beth')
# print OBJ.get_attribute_value('Hello1','Beth')
# dict = {'Alice': '32', 'Beth': '923', 'Cecil': '23'}
# OBJ1.add_entry('Hel',dict)
# print OBJ1.is_present('Hel')
# print OBJ1.get_attribute_value('Hel','Beth')
# OBJ2 = Env(OBJ1)
# dict = {'Alice': '2', 'Beth': '1', 'Cecil': '2'}
# OBJ2.add_entry('Hell1',dict)
# print OBJ2.get_attribute_value('Hell1','Beth')
# OBJ3 = Env(OBJ)
# dict = {'Alice': '2', 'Beth': '1', 'Cecil': '2'}
# OBJ3.add_entry('Hell1',dict)
# # print OBJ3.get_attribute_value('Hell1','Beth')
# OBJ.subtree()
# #SymbolTable Class: Just abstraction layer over the Environment Class
#Hashtable Class: it contains the table
#self.table is dictionary with key=name_of_entry & value=list_of_attributes eg: a=5.. then name='a'(i.e. lexeme) attribute={'value':5} .. note ada is case-insensitive
#list_of_attributes is a dictionary (list is implemented as dictionary) with many entries with key(attribute_name):value(attribute_value) pairs like - {'type': 'Integer', 'value':'Integer', 'isdatatype':True}
#Hash table is a dictionary of dictionary based on the name then based on the attributes value
#Accessed using .table and value is table[name][attribute value]
class HashTable:
def __init__(self):
self.table={} # a dictionary
def add_entry (self, name, list_attributes):
if name in self.table:
print 'Error: Entry already present - [' + name + ']'
assert(False)
else:
#print "Deepak4iii - ",name," - ",list_attributes
self.table[name]= {} # a dictionary
for i_key in list_attributes:
self.table[name][i_key]=list_attributes[i_key]
#update if already present else add it.
def update_entry(self, name, attribute_name, attribute_value):
try: #try catch exception
self.table[name][attribute_name] = attribute_value
return True
except:
return False
def get_attribute_value (self, name, attribute_name):
try:
return self.table[name][attribute_name]
except:
return None
def is_present(self, name):
if name in self.table:
return True
else:
return False
def get_table(self):
return self.table
def print_table(self):
print "Table is : Entry name ==> Attribute_list"
for name in self.table:
print name,' ==> ', self.table[name]
class arrayObject:
def __init__(self,dataType,size):
self.dataType=dataType # a dictionary
self.size=size
# class classObject:
# def __init__(self):
# self.table={} # a dictionary
#Environment Class: Contains current symbolTable and pointer to parent Environment
from sets import Set
class Env:
static_var = 1
def __init__(self, prev=None):
self.symbolTable = HashTable() #Creates a new symbol table for a new scope
self.functionTable = HashTable() #Creates a new hash table for a new scope
self.objectTable = HashTable() #Creates a new hash table for a new scope
self.name = "node" + str(Env.static_var)
self.childs=[]
self.width = 0 # overall offset/width of this env
self.paramwidth = 0
self.prev_env=prev
self.code=list()
self.startChildBlock=None
self.endChildBlock=None
self.funcName=None
self.objName = None
if prev==None:
self.level=0
self.parentName=""
else:
self.level=prev.level+1
self.parentName=prev.name
Env.static_var+=1 # pointer to the previous hash table
if (prev != None):
prev.childs.append(self)
self.tempvar = Set([])
def gprev(self):
return self.prev
def goto(self,data):
for child in range(0,len(self.childs)):
# print self.node[child].name
if(self.childs[child].name==data):
return self.node[child]
def subtree(self):
"Gets the node by name"
print self.name,":::",self.level,':::',self.parentName
self.symbolTable.print_table()
for child in range(0,len(self.childs)):
# print self.node[child].name
self.childs[child].subtree()
# if(self.node[child].name==data):
# return self.node[child]
#adds entry in current hashtable
def add_entry(self,name, list_attributes,updateField="symbol"):
if updateField=="symbol":
self.symbolTable.add_entry(name, list_attributes)
elif updateField=="function":
self.functionTable.add_entry(name, list_attributes)
elif updateField == "object":
self.objectTable.add_entry(name, list_attributes)
else:
print "Attribute Missing"
def ChildObj(self, ObjSearched):
for child in self.childs:
if child.objName == ObjSearched:
return child
# print self.node[child].name
# self.childs[child].subtree()
# update entry in the most recent hash table in case not found in the most recent goes to the parent and then to next parent and
# successive goes up till the time entry is found if not found found printf error (Checks if the variable used is previously declared)
def update_entry(self, name, attribute_name, attribute_value,updateField="symbol"):
if updateField=="symbol":
env=self
while env!=None:
if env.symbolTable.update_entry(name, attribute_name, attribute_value) == True:
return
env=env.prev_env
print 'Error: Variable not present for updation - [' + name + ']'
elif updateField=="function":
env=self
while env!=None:
if env.functionTable.update_entry(name, attribute_name, attribute_value) == True:
return
env=env.prev_env
print 'Error: Function not present for updation - [' + name + ']'
elif updateField=="object":
env=self
while env!=None:
if env.objectTable.update_entry(name, attribute_name, attribute_value) == True:
return
env=env.prev_env
print 'Error: Object not present for updation - [' + name + ']'
else:
print "Attribute Missing"
#Returns list of attributes from most recent hashtable (recent ancestor) corresponding to name. Returns None if entry not found
def get_attribute_value(self,name, attribute_name,updateField="symbol"):
if "@" in name:
split1 = name.split('@')[0]
split2= name.split('@')[1]
env=self
flag = False
while env!=None:
if env.objectTable.is_present(split1):
flag=True
break
env = env.prev_env
if flag == False:
return None
newenv=env.ChildObj(split1)
return newenv.get_attribute_value(split2,attribute_name,updateField)
elif updateField=="symbol":
env=self
while env!=None:
found=env.symbolTable.get_attribute_value(name, attribute_name)
if found != None:
return found
env=env.prev_env
return None
elif updateField=="function":
env=self
while env!=None:
found=env.functionTable.get_attribute_value(name, attribute_name)
if found != None:
return found
env=env.prev_env
return None
elif updateField=="object":
env=self
while env!=None:
found=env.objectTable.get_attribute_value(name, attribute_name)
if found != None:
return found
env=env.prev_env
return None
else:
print "Attribute not found"
def get_attribute_append_name(self,name,updateField="symbol"):
if "@" in name:
split1 = name.split('@')[0]
split2= name.split('@')[1]
env=self
flag = False
while env!=None:
if env.objectTable.is_present(split1):
flag=True
break
env = env.prev_env
if flag == False:
return None
newenv=env.ChildObj(split1)
return newenv.name
if updateField=="symbol":
env=self
while env!=None:
if env.symbolTable.is_present(name):
return env.name
env = env.prev_env
elif updateField=="function":
env=self
while env!=None:
if env.functionTable.is_present(name):
return env.name
env = env.prev_env
elif updateField=="object":
env=self
while env!=None:
if env.objectTable.is_present(name):
return env.name
env = env.prev_env
else:
print "Attribute not found"
#returns table only in current scope, not ancestral ones
def getCurrentSymbolTable(self):
return self.symbolTable.get_table()
#is_present in the current scope only
# def is_present_current_block(self, name,updateField="sybmol"):
# if (updateField=="symbol"):
# return self.symbolTable.is_present(name)
# elif (updateField=="function"):
# return self.functionTable.is_present(name)
# elif (updateField=="object"):
# return self.objectTable.is_present(name)
def is_present(self,name,updateField="symbol"):
if "@" in name:
split1 = name.split('@')[0]
split2= name.split('@')[1]
env=self
flag = False
while env!=None:
if env.objectTable.is_present(split1):
flag=True
break
env = env.prev_env
if flag == False:
return flag
newenv=env.ChildObj(split1)
return newenv.is_present(split2,updateField)
elif updateField=="symbol":
env=self
while env!=None:
if env.symbolTable.is_present(name):
return True
env = env.prev_env
return False
elif updateField=="function":
env=self
while env!=None:
if env.functionTable.is_present(name):
return True
env = env.prev_env
return False
elif updateField=="object":
env=self
while env!=None:
if env.objectTable.is_present(name):
return True
env = env.prev_env
return False
def print_table(self):
env=self
i=0
while env!=None:
print "Ancestor - ",i
env.objectTable.print_table()
env = env.prev_env
i=i+1
# ==========================================Dont know the use of the last four functions
def get_width(self):
return self.width
def increment_width(self, inc): #similar to addwidth() in lecture notes
self.width += inc
def get_paramwidth(self):
return self.paramwidth
def increment_paramwidth(self, inc):
self.paramwidth += inc
# get_entry(self,name) #return full attribute list.
# get_entryheight(self,name) #how many levles abov it was found
if __name__ == '__main__':
OBJ = Env(None)
# print Env.static_var
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
OBJ.add_entry('Hello',dict)
print OBJ.get_attribute_value('Hello','Beth')
dict = {'Alice': '323', 'Beth': '91223', 'Cecil': '3223'}
OBJ.add_entry('Hel',dict)
print OBJ.is_present('Hel')
OBJ1 = Env(OBJ)
dict = {'Alice': '22', 'Beth': '91', 'Cecil': '32'}
OBJ1.add_entry('Hello1',dict)
print OBJ.get_attribute_value('Hello','Beth')
print OBJ.get_attribute_value('Hello1','Beth')
dict = {'Alice': '32', 'Beth': '923', 'Cecil': '23'}
OBJ1.add_entry('Hel',dict)
print OBJ1.is_present('Hel')
print OBJ1.get_attribute_value('Hel','Beth')
OBJ2 = Env(OBJ1)
dict = {'Alice': '2', 'Beth': '1', 'Cecil': '2'}
OBJ2.add_entry('Hell1',dict)
print OBJ2.get_attribute_value('Hell1','Beth')
OBJ3 = Env(OBJ)
dict = {'Alice': '2', 'Beth': '1', 'Cecil': '2'}
OBJ3.add_entry('Hell1',dict)
# print OBJ3.get_attribute_value('Hell1','Beth')
OBJ.subtree()
#SymbolTable Class: Just abstraction layer over the Environment Class
<file_sep>/asgn2/src/parser.py
import sys
import ply.yacc as yacc
import scalalex
import pickle
import sys
import os.path
import re
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)))
from include.grammar import *
def p_error(p):
flag=-1;
print("Syntax error at '%s'" % p.value),
print('\t Error: {}'.format(p))
while 1:
tok = yacc.token() # Get the next token
if not tok:
flag=1
break
if tok.type == 'STATE_END':
flag=0
break
if flag==0:
yacc.errok()
return tok
else:
yacc.restart()
def printnodes(current_node, file):
#sys.stderr.write(str(current_node.name) + "\n")
if (len(current_node.children)==0):
return;
for i in current_node.children:
flag=0
if (isinstance(i.name, basestring)):
matchObj = re.match( r'".*"', i.name , re.M|re.I)
if matchObj:
if (len(matchObj.group())==len(i.name)):
flag=1
print >> file, str(current_node.id)+" [label=\""+str(current_node.name)+"\"];"+str(i.id)+" [label=\""+str((matchObj.group()).replace('"', '\\\"'))+"\"];"+str(current_node.id)+"->"+str(i.id)
if flag==0 :
print >> file, str(current_node.id)+" [label=\""+str(current_node.name)+"\"];"+str(i.id)+" [label=\""+str(i.name)+"\"];"+str(current_node.id)+"->"+str(i.id)
flag=0
for i in current_node.children:
printnodes(i, file)
def printleaves(current_node, file):
if (len(current_node.children) == 0):
print >> file, str(current_node.name) + " "
else:
for i in current_node.children:
printleaves(i)
# Get the token map
tokens = scalalex.tokens
# Build the grammar
parser=yacc.yacc()
#Read from file
f = open(sys.argv[1],"r")
code_full = f.read()
code_full=code_full+'\n'
f.close()
#parse over the input
#Find the dot file for the given parse tree
node = parser.parse(code_full)
if len(sys.argv) == 3:
f = open(sys.argv[2], "w+")
else:
filename=os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))+'/test1.dot'
f = open(filename, "w+")
if node:
print >> f, "digraph G {"
printnodes(node, f)
print >> f, "}"
#Find the left to right order of the leaves
# printleaves(node)<file_sep>/asgn3/include/grammar.py
from symbolTable import *
SCOPE = Env(None) # Current Scope
globalTemp=list()
globalTempShootDown=0
globalLabel=1
globalFunc=1
registerSize=1000
varStart="@t"
labelStart="Label"
functionStart="Function"
for i in range(1,registerSize+1):
globalTemp.append(0)
def returnTemp():
# global globalTemp
global globalTempShootDown
globalTempShootDown+=1
# var='Guys:push in symbol table'
attribute=dict()
attribute['Type']='Temp'
SCOPE.add_entry((varStart+"_"+str(globalTempShootDown))[1:],attribute,"symbol")
return varStart+"_"+str(globalTempShootDown)
# temp=globalTemp[0]
# j=1
# while j<registerSize and temp==1:
# temp=globalTemp[j]
# j=j+1
# if (j==registerSize):
# print "Not enough variables"
# else :
# globalTemp[j-1]=1
# SCOPE.tempvar.add(varStart+"_"+str(j))
# return varStart+"_"+str(j)
def returnLabel():
global globalLabel
globalLabel+=1
return labelStart+str(globalLabel)
def returnFunction():
global globalFunc
globalFunc+=1
return functionStart+str(globalFunc)
def backpatch(listL1,string1):
for i in listL1:
SCOPE.code[i][4]=string1
# [None,None,label+":",None,None]
# append([None,None,label+":",None,None])
def freeVar(a):
pass
# if a!=None:
# if varStart in a:
# if ")" in a:
# a=a[:-1]
# b=int(a.split('_')[1])
# global globalTemp
# globalTemp[b-1]=0
def Updatep1(pnew):
if pnew.isQualifiedName:
# print p[1].value
query=((pnew.value).split('.'))[0]
query1=((pnew.value).split('.'))[1]
# print query
if SCOPE.is_present(query,updateField="symbol"):
val1=SCOPE.get_attribute_value(query,'Type',"symbol")
if "Object" in val1:
pnew.value=val1.split('@')[1]+"@"+query1
# print pnew.value
else:
print "No such object definition found at line,",p.lexer.lineno()
raise Exception("Check your semantics! :P")
else:
print "No such variable found at line,",p.lexer.lineno()
raise Exception("Check your semantics! :P")
return pnew.value
def Updatehold(pnew):
if pnew.isQualifiedName:
# print p[1].value
query=((pnew.holdingVariable).split('.'))[0]
query1=((pnew.holdingVariable).split('.'))[1]
# print query
if SCOPE.is_present(query,updateField="symbol"):
val1=SCOPE.get_attribute_value(query,'Type',"symbol")
if "Object" in val1:
pnew.holdingVariable=val1.split('@')[1]+"@"+query1
# print pnew.value
else:
print "No such object definition found at line,",p.lexer.lineno()
raise Exception("Check your semantics! :P")
else:
print "No such variable found at line,",p.lexer.lineno()
raise Exception("Check your semantics! :P")
return pnew.holdingVariable
class Node(object):
gid = 1
def __init__(self,name,children,dataType="Unit",val=None,size=None,argumentList=None,holdingVariable=None,trueList=None,falseList=None,nextList=None):
self.name = name
self.children = children
self.id=Node.gid
self.value=val
self.size=size
self.argumentList=argumentList
self.dataType=dataType
self.trueList = trueList;
self.falseList = falseList
self.nextList = nextList
self.holdingVariable=holdingVariable
self.isQualifiedName=False
Node.gid+=1
def create_leaf(name1,name2,dataType="Unit"):
leaf1 = Node(name2,[],dataType)
leaf2 = Node(name1,[leaf1],dataType)
return leaf2
def printCode(currElement):
# print len(currElement.tempvar)
for i in currElement.code :
for j in range(5):
if (i[j]!=None):
if type(i[j])==str and "@t" in i[j]:
if (i[j][0]=='*'):
print i[j][0:2]+i[j][3:],
else:
print i[j][1:],
else:
print i[j],
print
print
print
def traversetree():
global SCOPE
queue=list()
objects=list()
queue.append(SCOPE)
while len(queue) >0 :
currElement=queue[0]
del queue[0]
for i in range (len(currElement.childs)):
queue.append(currElement.childs[i])
# if (currElement.childs[i].objName==None):
# queue.append(currElement.childs[i])
# else:
# objects.append(currElement.childs[i])
printCode(currElement)
# def dfsTraversal():
# global SCOPE
# queue=list()
# objects=list()
# queue.append(SCOPE)
# while len(queue) >0 :
# currElement=queue[len(queue)-1]
# del queue[len(queue)-1]
# for i in range (len(currElement.childs)):
# j=len(currElement.childs)-1-i
# queue.append(currElement.childs[j])
# # if (currElement.childs[i].objName==None):
# # queue.append(currElement.childs[i])
# # else:
# # objects.append(currElement.childs[i])
# printCode(currElement)
def replaceCode(currScope,replaceThis):
if (replaceThis!=None):
for i in currScope.code:
for j in range(5):
if (i[j]!=None):
if type(i[j])==str and '__' in i[j] and ':' not in i[j]:
string123=i[j].split('__')[0]
if (string123==replaceThis):
abc=i[j].split('__')
abc[0]="this."+replaceThis
abc123="__".join(abc)
i[j]=abc123
def obtainTableSize(currScope):
value=0
# print type (currScope.symbolTable.table)
for key,val in (currScope.symbolTable.table).iteritems():
# print key,val
if 'Array' in val['Type'] or 'Object' in val['Type']:
pass
else:
if (currScope.objName==None):
value=value+1
else:
if (val['Type']=='Temp'):
value=value+1
# print 'Val:',key,value
# print
# print
return value
def backpatch_address(currScope):
for i in range (len(currScope.childs)):
currScope.totalSize=currScope.totalSize+backpatch_address(currScope.childs[i])
currScope.totalSize=currScope.totalSize+obtainTableSize(currScope)
if (currScope.objName==None and currScope.funcName==None):
return currScope.totalSize
elif (currScope.objName!=None or currScope.funcName!=None):
currScope.code[1][4]=str(currScope.totalSize*4)
return 0
def dfsTraversal(currScope,replaceThis):
if currScope.objName!=None:
replaceThis=currScope.name
replaceCode(currScope,replaceThis)
for i in range (len(currScope.childs)):
dfsTraversal(currScope.childs[i],replaceThis)
if currScope.objName!=None:
replaceThis=None
def p_start_here(p):
'''start_here : ProgramStructure end_here'''
p[0] = Node("startOfProgram", [p[1], p[2]])
def p_end_here(p):
'''end_here : empty '''
p[0] = Node("endhere", [p[1]])
dfsTraversal(SCOPE,None)
backpatch_address(SCOPE)
traversetree()
# SCOPE.subtree()
def p_program_structure(p):
'''ProgramStructure : ProgramStructure class_and_objects
| class_and_objects '''
if len(p) == 3:
if not (p[1].dataType=="Unit" and p[2].dataType=="Unit"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("ProgramStructure", [p[1], p[2]])
else:
if not (p[1].dataType=="Unit"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("ProgramStructure", [p[1]])
def p_class_and_objects(p):
'''class_and_objects : SingletonObject
| class_declaration'''
if not (p[1].dataType=="Unit"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("class_and_objects", [p[1]])
def p_SingletonObject(p):
'SingletonObject : ObjectDeclare block'
if not (p[1].dataType=="Unit" and p[2].dataType=="Unit" ):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("SingletonObject", [p[1], p[2]])
# object declaration
def p_object_declare(p):
'''ObjectDeclare : KWRD_OBJECT IDENTIFIER
| KWRD_OBJECT IDENTIFIER KWRD_EXTNDS IDENTIFIER'''
if len(p) == 3:
child1 = create_leaf("KWRD_OBJECT", p[1])
child2 = create_leaf("IDENTIFIER", p[2])
if not (child1.dataType=="Unit" and child2.dataType=="Unit"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("ObjectDeclare", [child1, child2])
else:
child1 = create_leaf("KWRD_OBJECT", p[1])
child2 = create_leaf("IDENTIFIER", p[2])
child3 = create_leaf("KWRD_EXTNDS", p[3])
child4 = create_leaf("IDENTIFIER", p[4])
if not (child1.dataType=="Unit" and child2.dataType=="Unit" and child3.dataType=="Unit" and child4.dataType=="Unit"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("ObjectDeclare", [child1, child2, child3, child4])
# expression
def p_expression(p):
'''expression : assignment_expression'''
p[0] = Node("expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
def p_expression_optional(p):
'''expression_optional : expression
| empty'''
p[0] = Node("expression_optional", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
def p_assignment_expression(p):
'''assignment_expression : assignment
| conditional_or_expression'''
returnHold=p[1].holdingVariable
if p[1].trueList!=None and p[1].falseList!=None and (len(p[1].trueList) >0 or len(p[1].falseList) >0):
truelabel=returnLabel()
falselabel=returnLabel()
jumplabel=returnLabel()
retVar=returnTemp()
SCOPE.code.append([None,None,truelabel+":",None,None])
SCOPE.code.append([retVar,"=","1",None,None])
SCOPE.code.append([None,None,None,"goto",jumplabel])
SCOPE.code.append([None,None,falselabel+":",None,None])
SCOPE.code.append([retVar,"=","0",None,None])
SCOPE.code.append([None,None,jumplabel+":",None,None])
backpatch(p[1].trueList,truelabel)
backpatch(p[1].falseList,falselabel)
returnHold=retVar
elif p[1].trueList!=None and len(p[1].trueList) >0 :
truelabel=returnLabel()
retVar=returnTemp()
SCOPE.code.append([None,None,truelabel+":",None,None])
SCOPE.code.append([retVar,"=","1",None,None])
backpatch(p[1].trueList,truelabel)
returnHold=retVar
elif p[1].falseList!=None and len(p[1].falseList) >0 :
falselabel=returnLabel()
retVar=returnTemp()
SCOPE.code.append([None,None,falselabel+":",None,None])
SCOPE.code.append([retVar,"=","0",None,None])
backpatch(p[1].falseList,falselabel)
returnHold=retVar
else:
pass
p[0] = Node("assignment_expression", [p[1]],p[1].dataType,None,None,None,returnHold)
# assignment
def p_assignment(p):
'''assignment : valid_variable assignment_operator assignment_expression'''
if (p[1].dataType == p[3].dataType):
pass
# elif ((p[1].dataType=="Double" and p[3].dataType=="Int") or (p[3].dataType=="Double" and p[1].dataType=="Int")):
# print "Do type cast here "
# pass
else:
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
if (p[2].value=="="):
SCOPE.code.append([p[1].holdingVariable,"=",p[3].holdingVariable,None,None])
freeVar(p[3].holdingVariable)
else:
val=p[2].value[0]
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1].holdingVariable,None,None])
SCOPE.code.append([p[1].holdingVariable,"=",tempVar,val,p[3].holdingVariable])
freeVar(p[3].holdingVariable)
freeVar(tempVar)
# print p[1].holdingVariable," ",p[2].value," ",p[3].holdingVariable
p[0] = Node("assignment", [p[1], p[2], p[3]],p[1].dataType)
def p_assignment_operator(p):
'''assignment_operator : ASSIGN
| TIMES_ASSIGN
| DIVIDE_ASSIGN
| REMAINDER_ASSIGN
| PLUS_ASSIGN
| MINUS_ASSIGN
| LSHIFT_ASSIGN
| RSHIFT_ASSIGN
| AND_ASSIGN
| OR_ASSIGN
| XOR_ASSIGN'''
# print p.lineno
child1 = create_leaf("ASSIGN_OP", p[1])
p[0] = Node("assignment_operator", [child1],"Unit",p[1])
def p_Marker(p):
'''Marker : empty '''
label=returnLabel()
p[0] = Node("Marker", [p[1]],"Unit",label)
SCOPE.code.append([None,None,label+":",None,None])
# OR(||) has least precedence, and OR is left assosiative
# a||b||c => first evalutae a||b then (a||b)||c
def p_conditional_or_expression(p):
'''conditional_or_expression : conditional_and_expression
| conditional_or_expression OR Marker conditional_and_expression'''
if len(p) == 2:
p[0] = Node("conditional_or_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
# handle using jump statements
child1 = create_leaf("OR", p[2])
if not (p[1].dataType=="Boolean" and p[4].dataType=="Boolean"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("conditional_or_expression", [p[1], child1, p[4]],p[1].dataType)
backpatch(p[1].falseList,p[3].value)
p[0].trueList = p[1].trueList+p[4].trueList;
p[0].falseList = p[4].falseList;
# AND(&&) has next least precedence, and AND is left assosiative
# a&&b&&c => first evalutae a&&b then (a&&b)&&c
def p_conditional_and_expression(p):
'''conditional_and_expression : inclusive_or_expression
| conditional_and_expression AND Marker inclusive_or_expression'''
if len(p) == 2:
p[0] = Node("conditional_and_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
# handle later
child1 = create_leaf("AND", p[2])
if not (p[1].dataType=="Boolean" and p[4].dataType=="Boolean"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("conditional_and_expression", [p[1], child1, p[4]],p[1].dataType)
backpatch(p[1].trueList, p[3].value)
p[0].trueList = p[4].trueList
p[0].falseList = p[1].falseList+p[4].falseList
def p_inclusive_or_expression(p):
'''inclusive_or_expression : exclusive_or_expression
| inclusive_or_expression OR_BITWISE exclusive_or_expression'''
if len(p) == 2:
p[0] = Node("inclusive_or_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("OR_BITWISE", p[2])
if not (p[1].dataType == "Int" and p[3].dataType == "Int"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable])
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
# print tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable
p[0] = Node("inclusive_or_expression", [p[1], child1, p[3]],p[1].dataType,None,None,None,tempVar)
def p_exclusive_or_expression(p):
'''exclusive_or_expression : and_expression
| exclusive_or_expression XOR and_expression'''
if len(p) == 2:
p[0] = Node("exclusive_or_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("XOR", p[2])
if not (p[1].dataType == "Int" and p[3].dataType == "Int"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable])
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
# print tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable
p[0] = Node("exclusive_or_expression", [p[1], child1, p[3]],p[1].dataType,None,None,None,tempVar)
def p_and_expression(p):
'''and_expression : equality_expression
| and_expression AND_BITWISE equality_expression'''
if len(p) == 2:
p[0] = Node("and_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("AND_BITWISE", p[2])
if not (p[1].dataType == "Int" and p[3].dataType == "Int"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable])
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
p[0] = Node("and_expression", [p[1], child1, p[3]],p[1].dataType,None,None,None,tempVar)
def p_equality_expression(p):
'''equality_expression : relational_expression
| equality_expression EQUAL relational_expression
| equality_expression NEQUAL relational_expression''' #Marker Marker
if len(p) == 2:
p[0] = Node("relational_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("EqualityOp", p[2])
if not (p[1].dataType == p[3].dataType):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("relational_expression", [p[1], child1, p[3]],"Boolean",None,None,None,None)
SCOPE.code.append(["if",p[1].holdingVariable,p[2],p[3].holdingVariable+" goto",None])
p[0].trueList=list()
(p[0].trueList).append(len(SCOPE.code)-1)
SCOPE.code.append([None,None,None,"goto",None])
p[0].falseList=list()
(p[0].falseList).append(len(SCOPE.code)-1)
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
def p_relational_expression(p):
'''relational_expression : shift_expression
| relational_expression GREATER shift_expression
| relational_expression LESS shift_expression
| relational_expression GEQ shift_expression
| relational_expression LEQ shift_expression'''
if len(p) == 2:
p[0] = Node("relational_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("RelationalOp", p[2])
if not (p[1].dataType == p[3].dataType):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("relational_expression", [p[1], child1, p[3]],"Boolean",None,None,None,None)
SCOPE.code.append(["if",p[1].holdingVariable,p[2],p[3].holdingVariable+" goto",None])
p[0].trueList=list()
(p[0].trueList).append(len(SCOPE.code)-1)
SCOPE.code.append([None,None,None,"goto",None])
p[0].falseList=list()
(p[0].falseList).append(len(SCOPE.code)-1)
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
def p_shift_expression(p):
'''shift_expression : additive_expression
| shift_expression LSHIFT additive_expression
| shift_expression RSHIFT additive_expression'''
if len(p) == 2:
p[0] = Node("shift_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("ShiftOp", p[2])
if not (p[1].dataType == p[3].dataType and p[1].dataType=="Int"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable])
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
p[0] = Node("shift_expression", [p[1], child1, p[3]],p[1].dataType,None,None,None,tempVar)
# p[0].trueList=p[1].trueList
# p[0].falseList=p[1].falseList
def p_additive_expression(p):
'''additive_expression : multiplicative_expression
| additive_expression PLUS multiplicative_expression
| additive_expression MINUS multiplicative_expression'''
if len(p) == 2:
p[0] = Node("additive_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("AddOp", p[2])
currType="Int"
if (p[1].dataType=="Int" and p[3].dataType=="Int"):
currType="Int"
elif (p[1].dataType=="Int" and p[3].dataType=="Double"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Double"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Int"):
currType="Double"
elif (p[1].dataType=="String" and p[3].dataType=="String" and p[2]=="+"):
currType="String"
else:
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable])
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
p[0] = Node("additive_expression", [p[1], child1, p[3]],currType,None,None,None,tempVar)
# p[0].trueList=p[1].trueList
# p[0].falseList=p[1].falseList
def p_multiplicative_expression(p):
'''multiplicative_expression : unary_expression
| multiplicative_expression TIMES unary_expression
| multiplicative_expression DIVIDE unary_expression
| multiplicative_expression REMAINDER unary_expression'''
if len(p) == 2:
p[0] = Node("multiplicative_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("MultOp", p[2])
currType="Int"
if (p[1].dataType=="Int" and p[3].dataType=="Int"):
currType="Int"
elif (p[1].dataType=="Int" and p[3].dataType=="Double" and p[2] != "%"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Double" and p[2] != "%"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Int" and p[2] != "%"):
currType="Double"
else:
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1].holdingVariable,p[2],p[3].holdingVariable])
freeVar(p[1].holdingVariable)
freeVar(p[3].holdingVariable)
p[0] = Node("multiplicative_expression", [p[1], child1, p[3]],currType,None,None,None,tempVar)
# p[0].trueList=p[1].trueList
# p[0].falseList=p[1].falseList
def p_unary_expression(p):
'''unary_expression : PLUS unary_expression
| MINUS unary_expression
| unary_expression_not_plus_minus'''
if len(p) == 3:
if not (p[2].dataType == "Int" or p[2].dataType=="Double"):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar1=returnTemp()
# print tempVar1,"= 0"
tempVar=returnTemp()
# print tempVar,"=",tempVar1,p[1],p[2].holdingVariable
SCOPE.code.append([tempVar1,"=","0",None,None])
SCOPE.code.append([tempVar,"=",tempVar1,p[1],p[2].holdingVariable])
freeVar(p[2].holdingVariable)
freeVar(tempVar1)
child1 = create_leaf("UnaryOp", p[1])
p[0] = Node("unary_expression", [child1, p[2]],p[2].dataType,None,None,None,tempVar)
p[0].trueList=p[2].trueList
p[0].falseList=p[2].falseList
else:
p[0] = Node("unary_expression", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
def p_unary_expression_not_plus_minus(p):
'''unary_expression_not_plus_minus : base_variable_set
| NOT unary_expression
| cast_expression'''
if len(p) == 2:
p[0] = Node("unary_expression_not_plus_minus", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
if (p[2].dataType=="Boolean"):
pass
else:
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
child1 = create_leaf("Unary_1Op", p[1])
p[0] = Node("unary_expression_not_plus_minus", [child1, p[2]],p[2].dataType,None,None,None,None)
p[0].trueList=p[2].falseList
p[0].falseList=p[2].trueList
def p_unary_expression_not_plus_minus_1(p):
'''unary_expression_not_plus_minus : TILDA unary_expression '''
if (p[2].dataType=="Int"):
pass
else:
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
child1 = create_leaf("Unary_1Op", p[1])
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",None,p[1],p[2].holdingVariable])
freeVar(p[2].holdingVariable)
p[0] = Node("unary_expression_not_plus_minus", [child1, p[2]],p[2].dataType,None,None,None,tempVar)
p[0].trueList=p[2].trueList
p[0].falseList=p[2].falseList
def p_base_variable_set(p):
'''base_variable_set : variable_literal
| LPAREN expression RPAREN'''
if len(p) == 2:
p[0] = Node("base_variable_set", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
else:
child1 = create_leaf("LPAREN", p[1])
child2 = create_leaf("RPAREN", p[3])
p[0] = Node("base_variable_set", [child1, p[2], child2],p[2].dataType,None,None,None,p[2].holdingVariable)
p[0].trueList=p[2].trueList
p[0].falseList=p[2].falseList
def p_cast_expression(p):
'''cast_expression : LPAREN primitive_type RPAREN unary_expression'''
flag=0
currType="Int"
if (p[2].dataType=="Unit" and (p[4].dataType=="Double" or p[4].dataType=="Int")):
if (p[2].value=="Int" or p[2].value=="Double"):
flag=1
if (p[2].value=="Int"):
currType="Int"
elif (p[2].value=="Double"):
currType="Double"
else:
flag=2
if (flag==0):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
elif (flag==2):
print "Cast Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",None,"("+p[2].value+")",p[4].holdingVariable])
freeVar(p[4].holdingVariable)
# print tempVar,"=","cast to",p[2].value,p[4].holdingVariable
child1 = create_leaf("LPAREN", p[1])
child2 = create_leaf("RPAREN", p[3])
p[0] = Node("cast_expression", [child1, p[2], child2, p[4]],currType,None,None,None,tempVar)
p[0].trueList=p[4].trueList
p[0].falseList=p[4].falseList
def p_primary(p):
'''primary : literal
| method_invocation'''
p[0] = Node("primary", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
def p_literal_1(p):
'''literal : int_float'''
p[0] = Node("literal", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].trueList=p[1].trueList
p[0].falseList=p[1].falseList
def p_literal_2(p):
'''literal : CHARACTER'''
child1 = create_leaf("LiteralConst", p[1],"Char")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1],None,None])
p[0] = Node("literal", [child1],"Char",None,None,None,tempVar)
# p[0].trueList=p[1].trueList
# p[0].falseList=p[1].falseList
def p_literal_3(p):
'''literal : STRING_CONST'''
child1 = create_leaf("LiteralConst", p[1],"String")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1],None,None])
p[0] = Node("literal", [child1],"String",None,None,None,tempVar)
# p[0].trueList=p[1].trueList
# p[0].falseList=p[1].falseList
def p_literal_4(p):
'''literal : BOOL_CONSTT'''
child1 = create_leaf("LiteralConst", p[1],"Boolean")
# tempVar=returnTemp()
# SCOPE.code.append([tempVar,"=",p[1],None,None])
p[0] = Node("literal", [child1],"Boolean",None,None,None,None)
SCOPE.code.append([None,None,None,"goto",None])
p[0].trueList=list()
(p[0].trueList).append(len(SCOPE.code)-1)
def p_literal_7(p):
'''literal : BOOL_CONSTF'''
child1 = create_leaf("LiteralConst", p[1],"Boolean")
p[0] = Node("literal", [child1],"Boolean",None,None,None,None)
SCOPE.code.append([None,None,None,"goto",None])
p[0].falseList=list()
(p[0].falseList).append(len(SCOPE.code)-1)
def p_literal_5(p):
'''literal : KWRD_NULL'''
child1 = create_leaf("LiteralConst", p[1],"Unit")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1],None,None])
p[0] = Node("literal", [child1],"Unit",None,None,None,tempVar)
def p_int_float_1(p):
'''int_float : FLOAT_CONST'''
child1 = create_leaf("FloatConst", p[1],"Double")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1],None,None])
p[0] = Node("int_float", [child1],"Double",None,None,None,tempVar)
def p_int_float_2(p):
'''int_float : INT_CONST'''
child1 = create_leaf("IntConst", p[1],"Int")
tempVar=returnTemp()
SCOPE.code.append([tempVar,"=",p[1],None,None])
p[0] = Node("int_float", [child1],"Int",None,None,None,tempVar)
def p_method_invocation(p):
'''method_invocation : name LPAREN argument_list_opt RPAREN '''
child1 = create_leaf("LPAREN", p[2])
child2 = create_leaf("RPAREN", p[4])
val=""
retType=""
# print "QualifiedName:",p[1].isQualifiedName
oldVal=p[1].value
oldVal1=""
if p[1].isQualifiedName:
oldVal1=oldVal.split('.')[0]
oldVal=oldVal.split('.')[1]
p[1].value=Updatep1(p[1])
if SCOPE.is_present(p[1].value,updateField="function"):
val=SCOPE.get_attribute_value(p[1].value,'Type',"function")
retType=SCOPE.get_attribute_value(p[1].value,'returnType',"function")
if (val==p[3].dataType):
pass
else:
print "Mismatch in arguement types to invoke the function at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
else:
print "Function is not defined at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("method_invocation", [p[1], child1, p[3], child2],retType)
d=0;
if p[1].isQualifiedName:
d+=1;
SCOPE.code.append([None,None,None,"PushParam","this("+oldVal1+")"])
if p[3].holdingVariable!=None:
for i in p[3].holdingVariable:
j=i
d+=1
# print oldVal
if varStart in i:
if (i[0]=='*'):
i=i[0:2]+i[3:]
else:
i=i[1:]
# print 'Function',i
SCOPE.code.append([None,None,None,"PushParam",i])
freeVar(j)
holding=None
if (retType!="Unit"):
holding=returnTemp()
SCOPE.code.append([holding,"=","Lcall",SCOPE.get_attribute_append_name(p[1].value,updateField="function").name+"__"+oldVal,None])
else:
SCOPE.code.append([None,None,"Lcall",SCOPE.get_attribute_append_name(p[1].value,updateField="function").name+"__"+oldVal,None])
SCOPE.code.append([None,None,None,"PopParam",d*4])
if p[1].isQualifiedName:
SCOPE.code.append([None,None,None,"#Considered ^this^ as 4 byte pointer",None])
# SCOPE.code.append([None,None,None,"PopParam",len(p[3].holdingVariable)*4])
p[0].holdingVariable=holding
def p_array_access(p):
'''array_access : name LBPAREN expression RBPAREN '''
child1 = create_leaf("LBPAREN", p[2])
child2 = create_leaf("RBPAREN", p[4])
val1=list()
oldVal=p[1].value
p[1].value=Updatep1(p[1])
if SCOPE.is_present(p[1].value,updateField="symbol"):
val=SCOPE.get_attribute_value(p[1].value,'Type',"symbol")
val1=val.split(",")
if (val1[0]!="Array"):
print "Array Undefined at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
if (p[3].dataType=="Int"):
pass
else:
print "Only Integer Indices Allowed at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
else:
print "Array Undefined at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("array_access", [p[1], child1, p[3], child2],",".join(val1[1:]))
temp= returnTemp()
SCOPE.code.append([temp,"=","4",None,None])
temp1= returnTemp()
SCOPE.code.append([temp1,"=",temp,"*",p[3].holdingVariable])
nodename=""
if p[1].isQualifiedName:
nodename=SCOPE.get_attribute_append_name(oldVal[:oldVal.find('.')],updateField="symbol").name+"__"+oldVal.split('.')[0]
nodename_later=SCOPE.get_attribute_append_name(p[1].value,updateField="symbol").name+"__"+oldVal.split('.')[1]
nodename=nodename+'.'+nodename_later
else:
node=SCOPE.get_attribute_append_name(p[1].value,updateField="symbol")
nodename=node.name+"__"+oldVal
SCOPE.code.append([temp,"=",nodename,"+",temp1])
# SCOPE.code.append([temp1,"=*","(",temp,")"])
freeVar(temp1)
p[0].holdingVariable="*("+temp+")"
# print p[0].holdingVariable
def p_argument_list_opt(p):
'''argument_list_opt : argument_list'''
p[0] = Node("argument_list_opt", [p[1]],p[1].dataType)
p[0].holdingVariable=p[1].holdingVariable
def p_argument_list_opt2(p):
'''argument_list_opt : empty'''
p[0] = Node("argument_list_opt", [p[1]],p[1].dataType)
p[0].holdingVariable=p[1].holdingVariable
def p_argument_list(p):
'''argument_list : expression
| argument_list COMMA expression'''
if len(p) == 2:
newType_1 = list()
newType_1.append(p[1].dataType)
newHolding = list()
newHolding.append(p[1].holdingVariable)
p[0] = Node("argument_list", [p[1]],newType_1)
p[0].holdingVariable=newHolding
else:
newType_1 = list(p[1].dataType)
newType_2 = list()
newType_2.append(p[3].dataType)
newHold_1 = list(p[1].holdingVariable)
newHold_2 = list()
newHold_2.append(p[3].holdingVariable)
child1 = create_leaf("COMMA", p[2])
p[0] = Node("argument_list", [p[1], child1, p[3]],newType_1+newType_2)
p[0].holdingVariable=newHold_1+newHold_2
# object identifier and identifier names for left hand assignment
def p_name(p):
'''name : simple_name
| qualified_name'''
p[0] = Node("name", [p[1]],"Unit",p[1].value,None,None,p[1].holdingVariable)
p[0].isQualifiedName=p[1].isQualifiedName
def p_simple_name(p):
'''simple_name : IDENTIFIER'''
child1 = create_leaf("IDENTIFIER", p[1])
p[0] = Node("simple_name", [child1],"Unit",p[1],None,None,p[1])
def p_qualified_name(p):
'''qualified_name : name DOT simple_name'''
child1 = create_leaf("DOT", p[2])
p[0] = Node("qualified_name", [p[1], child1, p[3]])
p[0].isQualifiedName=True
p[0].value=p[1].value+"."+p[3].value
p[0].holdingVariable=p[0].value
def p_valid_variable(p):
'''valid_variable : name'''
val=""
# print p[1].value
oldVal=p[1].value
p[1].value=Updatep1(p[1])
# p[1].holdingVariable=Updatehold(p[1])
if SCOPE.is_present(p[1].value,updateField="symbol"):
val=SCOPE.get_attribute_value(p[1].value,'Type',"symbol")
else:
print "Variable undefined at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
# if p[1].isQualifiedName:
# print
# SCOPE.get_attribute_append_name(,updateField="symbol")
nodename=""
if p[1].isQualifiedName:
nodename=SCOPE.get_attribute_append_name(oldVal[:oldVal.find('.')],updateField="symbol").name+"__"+oldVal.split('.')[0]
nodename_later=SCOPE.get_attribute_append_name(p[1].value,updateField="symbol").name+"__"+oldVal.split('.')[1]
nodename=nodename+'.'+nodename_later
else:
node=SCOPE.get_attribute_append_name(p[1].value,updateField="symbol")
nodename=node.name+"__"+oldVal
# print 'Hello',nodename
# if (node.objName!=None and p[1].isQualifiedName==False):
# offset=SCOPE.get_attribute_value(p[1].value,'Offset',"symbol")
# # print 'Hello',p[1].value
# # currScope=SCOPE
# # while(currScope!=None and currScope!=node):
# # # print
# # if (currScope.funcName!=None):
# # nodename="this."+p[1].value
# # break
# # currScope=currScope.prev_env
# print nodename
# SCOPE.CheckValidParentObject(nodeName,oldVal.split)
p[0] = Node("valid_variable", [p[1]],val,None,None,None,nodename)
def p_valid_variable_1(p):
'''valid_variable : array_access'''
p[0] = Node("valid_variable", [p[1]],p[1].dataType)
p[0].holdingVariable=p[1].holdingVariable
def p_variableliteral(p):
'''variable_literal : valid_variable
| primary'''
p[0] = Node("variable_literal", [p[1]],p[1].dataType,None,None,None,p[1].holdingVariable)
p[0].falseList=p[1].falseList
p[0].trueList=p[1].trueList
# BLOCK STATEMENTS
# def p_block(p):
# '''block : BLOCK_BEGIN block_statements_opt BLOCK_END '''
# child1 = create_leaf("BLOCK_BEGIN", p[1])
# child2 = create_leaf("BLOCK_END", p[3])
# p[0] = Node("block", [child1, p[2], child2])
def p_block(p):
'''block : start_scope block_statements_opt end_scope'''
p[0] = Node("block", [p[1], p[2], p[3]])
def p_start_scope(p):
'''start_scope : BLOCK_BEGIN'''
global SCOPE
NEW_SCOPE = Env(SCOPE)
PREV_SCOPE=SCOPE
SCOPE=NEW_SCOPE
if (PREV_SCOPE.startChildBlock!=None):
SCOPE.code.append([None,None,PREV_SCOPE.startChildBlock+":",None,None])
PREV_SCOPE.startChildBlock=None
child1 = create_leaf("BLOCK_BEGIN", p[1])
p[0] = Node("start_scope", [child1])
def p_end_scope(p):
'''end_scope : BLOCK_END'''
global SCOPE
PREV_SCOPE=SCOPE.prev_env
if (PREV_SCOPE.endChildBlock!=None):
SCOPE.code.append([None,None,None,"goto",PREV_SCOPE.endChildBlock])
PREV_SCOPE.endChildBlock=None
SCOPE=PREV_SCOPE
# SCOPE.subtree()
child1 = create_leaf("BLOCK_END", p[1])
p[0] = Node("end_scope", [child1])
def p_block_statements_opt(p):
'''block_statements_opt : block_statements'''
p[0] = Node("block_statements_opt", [p[1]],p[1].dataType)
def p_block_statements_opt2(p):
'''block_statements_opt : empty'''
p[0] = Node("block_statements_opt", [p[1]],p[1].dataType)
def p_block_statements(p):
'''block_statements : block_statement
| block_statements block_statement'''
if len(p) == 2:
p[0] = Node("block_statement", [p[1]])
else:
p[0] = Node("block_statement", [p[1], p[2]])
def p_block_statement(p):
'''block_statement : local_variable_declaration_statement
| statement
| class_declaration
| SingletonObject
| method_declaration'''
p[0] = Node("block_statement", [p[1]],p[1].dataType)
# var (a:Int)=(h);
# var (a:Int,b:Int,c:Int)=(1,2,3);
# var (a:Int)=(h)
# var (a:Int,b:Int,c:Int)=(1,2,3)
# supported
def p_modifier_opts(p):
'''modifier_opts : modifier
| empty '''
p[0] = Node("modifier_opts", [p[1]],p[1].dataType)
def p_declaration_keyword(p):
'''declaration_keyword : KWRD_VAR
| KWRD_VAL '''
child1 = create_leaf("KWRD VAR/VAL", p[1])
p[0] = Node("declaration_keyword", [child1])
def p_local_variable_declaration_statement(p):
'''local_variable_declaration_statement : local_variable_declaration STATE_END '''
child1 = create_leaf("STATE_END", p[2])
p[0] = Node("local_variable_declaration_statement", [p[1], child1])
#
def p_local_variable_declaration(p):
'''local_variable_declaration : modifier_opts declaration_keyword variable_declaration_body'''
p[0] = Node("local_variable_declaration", [p[1], p[2], p[3]])
def p_variable_declaration_initializer(p):
'''variable_declaration_initializer : expression
| array_initializer
| class_initializer'''
p[0] = Node("variable_declaration_initializer", [p[1]],p[1].dataType,p[1].value,p[1].size,p[1].argumentList,p[1].holdingVariable)
def p_variable_arguement_list(p):
''' variable_arguement_list : variable_declaration_initializer
| variable_arguement_list COMMA variable_declaration_initializer'''
if len(p) == 2:
newType_1 = list()
newType_1.append(p[1].dataType)
newSize_1 = list()
newSize_1.append(p[1].size)
newArg_1 = list()
newArg_1.append(p[1].argumentList)
newHold_1 = list()
newHold_1.append(p[1].holdingVariable)
# print p[1].dataType
# print newType_1
p[0] = Node("variable_arguement_list", [p[1]],newType_1,None,newSize_1,newArg_1,newHold_1)
else:
child1 = create_leaf("COMMA", p[2])
newType_1 = list(p[1].dataType)
newType_2 = list()
newType_2.append(p[3].dataType)
newSize_1 = list(p[1].size)
newSize_2 = list()
newSize_2.append(p[3].size)
newArg_1 = list(p[1].argumentList)
newArg_2 = list()
newArg_2.append(p[3].argumentList)
newHold_1 = list(p[1].holdingVariable)
newHold_2 = list()
newHold_2.append(p[3].holdingVariable)
# print newType_1
# print newType_2
p[0] = Node("variable_arguement_list", [p[1], child1, p[3]],newType_1+newType_2,None,newSize_1+newSize_2,newArg_1+newArg_2,newHold_1+newHold_2)
def p_variable_declaration_body_1(p):
'''variable_declaration_body : variable_declarator ASSIGN variable_declaration_initializer '''
# print p[1].dataType
# print p[3].dataType
if (p[1].dataType!=p[3].dataType):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
else:
# print type(p[3].size)
# print p[3].size
if (p[3].size!=None):
SCOPE.update_entry(p[1].value,'Size',int((p[3].size)),updateField="symbol")
#SCOPE.print_table()
# print p[3].holdingVariable
if p[1].dataType!=None:
if ("Array" in p[1].dataType):
j=0
if p[3].holdingVariable!=None:
for i in p[3].holdingVariable:
temp= returnTemp()
SCOPE.code.append([temp,"=","4",None,None])
temp2=returnTemp()
SCOPE.code.append([temp2,"=",j,None,None])
temp1= returnTemp()
SCOPE.code.append([temp1,"=",temp,"*",temp2])
SCOPE.code.append([temp,"=",SCOPE.get_attribute_append_name(p[1].value,updateField="symbol").name+"__"+p[1].value,"+",temp1])
# SCOPE.code.append([temp1,"=*","(",temp,")"])
SCOPE.code.append(["*("+temp+")","=",i,None,None])
freeVar(temp1)
freeVar(temp)
freeVar(temp2)
freeVar(i)
j=j+1
elif ("Object" in p[1].dataType):
d=0;
if p[3].holdingVariable!=None:
for i in p[3].holdingVariable:
if (i[0]=='*'):
i=i[0:2]+i[3:]
else:
i=i[1:]
d=d+1
SCOPE.code.append([None,None,None,"PushParam",i])
SCOPE.code.append([None,None,None,"PushParam",'this.'+p[1].value])
# print 'Apart',
SCOPE.code.append([None,None,"Lcall",SCOPE.get_attribute_append_name(p[1].dataType.split('@')[1],updateField="object").name+'__'+p[1].dataType.split('@')[1],None])
SCOPE.code.append([None,None,None,"PopParam",(d+1)*4])
else:
SCOPE.code.append([SCOPE.get_attribute_append_name(p[1].value,updateField="symbol").name+"__"+p[1].value,"=",p[3].holdingVariable,None,None])
# SCOPE.tempvar.add(SCOPE.get_attribute_append_name(p[1].value,updateField="symbol").name+"__"+p[1].value)
freeVar(p[3].holdingVariable)
# print p[1].dataType
# for i123 in range (len(p[1].holdingVariable)):
child1 = create_leaf("ASSIGN", p[2])
p[0] = Node("variable_declaration_body", [p[1], child1, p[3]])
def p_variable_declaration_body_2(p):
'''variable_declaration_body : LPAREN variable_declarators RPAREN ASSIGN LPAREN variable_arguement_list RPAREN'''
child1 = create_leaf("LPAREN", p[1])
child2 = create_leaf("RPAREN", p[3])
child3 = create_leaf("ASSIGN", p[4])
child4 = create_leaf("LPAREN", p[5])
child5 = create_leaf("RPAREN", p[7])
# print p[2].dataType
# print p[6].dataType
if (p[2].dataType!=p[6].dataType):
print "Type Error at line ",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
else :
for i123 in range(len(p[2].value)):
if ("Array" in (p[2].dataType)[i123]):
j=0
for i in (p[6].holdingVariable)[i123]:
temp= returnTemp()
SCOPE.code.append([temp,"=","4",None,None])
temp1= returnTemp()
temp2=returnTemp()
SCOPE.code.append([temp2,"=",j,None,None])
SCOPE.code.append([temp1,"=",temp,"*",temp2])
SCOPE.code.append([temp,"=",SCOPE.get_attribute_append_name((p[2].value)[i123],updateField="symbol").name+"__"+(p[2].value)[i123],"+",temp1])
SCOPE.code.append([temp1,"=*","(",temp,")"])
SCOPE.code.append([temp1,"=",i,None,None])
freeVar(temp1)
freeVar(temp)
freeVar(temp2)
freeVar(i)
j=j+1
elif ("Object" in (p[2].dataType)[i123]):
d=0
for i in (p[6].holdingVariable)[i123]:
if (i[0]=='*'):
i=i[0:2]+i[3:]
else:
i=i[1:]
d=d+1
SCOPE.code.append([None,None,None,"PushParam",i])
SCOPE.code.append([None,None,None,"PushParam",'this.'+(p[2].value)[i123]])
# print (p[2].value)[i123]
SCOPE.code.append([None,None,"Lcall",SCOPE.get_attribute_append_name((p[2].dataType)[i123].split('@')[1],updateField="object").name+'__'+(p[2].dataType)[i123].split('@')[1],None])
SCOPE.code.append([None,None,None,"PopParam",(d+1)*4])
pass
else:
newName=SCOPE.get_attribute_append_name((p[2].value)[i123],updateField="symbol").name+"__"+(p[2].value)[i123]
SCOPE.code.append([newName,"=",(p[6].holdingVariable)[i123],None,None])
# SCOPE.tempvar.add(newName)
freeVar((p[6].holdingVariable)[i123])
for i1 in range(len(p[2].value)):
if (p[6].size)[i1] != None:
SCOPE.update_entry((p[2].value)[i1],'Size',int((p[6].size)[i1]),updateField="symbol")
#SCOPE.print_table()
p[0] = Node("variable_declaration_body", [child1, p[2], child2, child3, child4, p[6], child5])
#left
def p_variable_declaration_body_3(p):
''' variable_declaration_body : IDENTIFIER ASSIGN LPAREN func_arguement_list_opt RPAREN FUNTYPE expression'''
child1 = create_leaf("IDENTIFIER", p[1])
child2 = create_leaf("ASSIGN", p[2])
child3 = create_leaf("LPAREN", p[3])
child4 = create_leaf("RPAREN", p[5])
child5 = create_leaf("FUNTYPE", p[6])
p[0] = Node("variable_declaration_body", [child1, child2, child3, p[4], child4, child5,p[7]])
def p_variable_declarators(p):
'''variable_declarators : variable_declarator
| variable_declarators COMMA variable_declarator'''
if len(p) == 2:
newType_1 = list()
newType_1.append(p[1].dataType)
newValue_1 = list()
newValue_1.append(p[1].value)
p[0] = Node("variable_declarators", [p[1]],newType_1,newValue_1)
else:
newType_1 = list(p[1].dataType)
newType_2 = list()
newType_2.append(p[3].dataType)
newValue_1 = list(p[1].value)
newValue_2 = list()
newValue_2.append(p[3].value)
child1 = create_leaf("COMMA", p[2])
p[0] = Node("variable_declarators", [p[1], child1, p[3]],newType_1+newType_2,newValue_1+newValue_2)
def p_variable_declarator(p):
'''variable_declarator : variable_declarator_id'''
p[0] = Node("variable_declarator", [p[1]],p[1].dataType,p[1].value)
def p_variable_declarator_id(p):
'''variable_declarator_id : IDENTIFIER COLON type'''
#Insert in symbol table
attribute=dict()
attribute['Type']=p[3].value
# print 'Hello'+p[3].value
SCOPE.add_entry(p[1],attribute,"symbol")
child1 = create_leaf("IDENTIFIER", p[1])
child2 = create_leaf("COLON", p[2])
p[0] = Node("variable_declarator_id", [child1, child2, p[3]],p[3].value,p[1])
# p[0] = Variable(p[1], dimensions=p[2])
def p_statement(p):
'''statement : normal_statement
| if_else_statement
| while_statement
| do_while_statement
| for_statement'''
p[0] = Node("statement", [p[1]],p[1].dataType)
def p_normal_statement(p):
'''normal_statement : block
| expression_statement
| empty_statement
| return_statement
| switch_statement'''
p[0] = Node("normal_statement", [p[1]],p[1].dataType)
def p_expression_statement(p):
'''expression_statement : statement_expression STATE_END'''
child1 = create_leaf("STATE_END", p[2])
p[0] = Node("expression_statement", [p[1], child1])
def p_statement_expression(p):
'''statement_expression : assignment
| method_invocation'''
p[0] = Node("statement_expression", [p[1]],p[1].dataType)
# def p_if_then_statement(p):
# '''if_then_statement : KWRD_IF LPAREN expression RPAREN block'''
# child1 = create_leaf("IF", p[1])
# child2 = create_leaf("LPAREN", p[2])
# child3 = create_leaf("RPAREN", p[4])
# if (p[3].dataType!="Boolean"):
# print "Conditional If only accepts boolean expression at line",p.lexer.lineno
# raise Exception("Correct the above Semantics! :P")
# p[0] = Node("if_then_statement", [child1, child2, p[3], child3, p[5]])
# def p_if_then_else_statement(p):
# '''if_then_else_statement : KWRD_IF LPAREN expression RPAREN if_then_else_intermediate KWRD_ELSE block'''
# child1 = create_leaf("IF", p[1])
# child2 = create_leaf("LPAREN", p[2])
# child3 = create_leaf("RPAREN", p[4])
# child4 = create_leaf("ELSE", p[6])
# if (p[3].dataType!="Boolean"):
# print "Conditional If only accepts boolean expression at line",p.lexer.lineno
# raise Exception("Correct the above Semantics! :P")
# p[0] = Node("if_then_else_statement", [child1, child2, p[3], child3, p[5], child4, p[7]])
# def p_if_then_else_statement_precedence(p):
# '''if_then_else_statement_precedence : KWRD_IF LPAREN expression RPAREN if_then_else_intermediate KWRD_ELSE if_then_else_intermediate'''
# child1 = create_leaf("IF", p[1])
# child2 = create_leaf("LPAREN", p[2])
# child3 = create_leaf("RPAREN", p[4])
# child4 = create_leaf("ELSE", p[6])
# if (p[3].dataType!="Boolean"):
# print "Conditional If only accepts boolean expression at line",p.lexer.lineno
# raise Exception("Correct the above Semantics! :P")
# p[0] = Node("if_then_else_statement_precedence", [child1, child2, p[3], child3, p[5], child4, p[7]])
# def p_if_then_else_intermediate(p):
# '''if_then_else_intermediate : block
# | if_then_else_statement_precedence'''
# p[0] = Node("if_then_else_intermediate", [p[1]])
def p_start_scope_if(p):
'''start_scope_if : BLOCK_BEGIN'''
global SCOPE
NEW_SCOPE = Env(SCOPE)
PREV_SCOPE=SCOPE
SCOPE=NEW_SCOPE
if (PREV_SCOPE.startChildBlock!=None):
SCOPE.code.append([None,None,None,PREV_SCOPE.startChildBlock+":",None])
PREV_SCOPE.startChildBlock=None
child1 = create_leaf("BLOCK_BEGIN", p[1])
p[0] = Node("start_scope_if", [child1])
def p_end_scope_if(p):
'''end_scope_if : BLOCK_END'''
global SCOPE
PREV_SCOPE=SCOPE.prev_env
if (PREV_SCOPE.endChildBlock!=None):
SCOPE.code.append([None,None,None,"goto",PREV_SCOPE.endChildBlock])
SCOPE=PREV_SCOPE
# SCOPE.subtree()
child1 = create_leaf("BLOCK_END", p[1])
p[0] = Node("end_scope_if", [child1])
def p_MarkIfStart(p):
'''MarkIfStart : empty'''
endLabel=returnLabel()
SCOPE.endChildBlock=endLabel
p[0] = Node("MarkIfStart", [p[1]])
def p_MarkIfEnd(p):
'''MarkIfEnd : empty'''
# global SCOPE
SCOPE.code.append([None,None,None,SCOPE.endChildBlock+":",None])
SCOPE.endChildBlock=None
p[0] = Node("MarkIfEnd", [p[1]])
def p_if_else_block(p):
'''if_else_block : start_scope_if block_statements_opt end_scope_if'''
p[0] = Node("block", [p[1], p[2], p[3]])
def p_if_else_statement(p):
'''if_else_statement : MarkIfStart if_else_begin if_else_intermediate MarkIfEnd'''
p[0] = Node("if_else_statement", [p[1],p[2]])
def p_if_else_begin(p):
'''if_else_begin : if_else_starting if_else_ending'''
p[0]=Node("if_else_begin",[p[1],p[2]])
def p_if_else_starting(p):
'''if_else_starting : KWRD_IF LPAREN expression RPAREN'''
child1 = create_leaf("IF", p[1])
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
if (p[3].dataType!="Boolean"):
print "Conditional If only accepts boolean expression at line",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0]=Node("if_else_begin",[child1,child2,p[3],child3])
startLabelChild=returnLabel()
SCOPE.code.append(["if",p[3].holdingVariable,"== 1","goto",startLabelChild])
SCOPE.startChildBlock=startLabelChild
freeVar(p[3].holdingVariable)
# // BNEQZ
# // set label for child block
def p_if_else_ending(p):
'''if_else_ending : if_else_block'''
p[0]=Node("if_else_ending",[p[1]])
def p_if_else_intermediate(p):
'''if_else_intermediate : KWRD_ELSE if_else_end
| empty'''
if (len(p)==2):
p[0]=Node("if_else_intermediate",[p[1]])
else:
child1= create_leaf("ELSE", p[1])
p[0]=Node("if_else_intermediate",[child1, p[2]])
def p_MarkBeforeElse(p):
'''MarkBeforeElse : empty'''
p[0]=Node("MarkBeforeElse",[p[1]])
startLabelChild=returnLabel()
SCOPE.code.append([None,None,None,"goto",startLabelChild])
SCOPE.startChildBlock=startLabelChild
def p_if_else_end(p):
''' if_else_end : MarkBeforeElse if_else_block
| if_else_begin if_else_intermediate'''
p[0]=Node("if_else_end",[p[1],p[2]])
def p_while_statement(p):
'''while_statement : while_header while_body'''
p[0] = Node("while_statement", [p[1],p[2]])
def p_while_header(p):
'''while_header : while_begin LPAREN expression RPAREN'''
newLabel=returnLabel()
SCOPE.code.append(["if",p[3].holdingVariable,"== 1","goto",newLabel])
freeVar(p[3].holdingVariable)
SCOPE.startChildBlock=newLabel
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
if (p[3].dataType!="Boolean"):
print "Loop While only accepts boolean expression at line",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
p[0] = Node("while_header", [p[1], child2, p[3], child3])
def p_while_body(p):
'''while_body : block'''
p[0] = Node("while_statement_body", [p[1]])
def p_while_begin(p):
'''while_begin : KWRD_WHILE'''
child1 = create_leaf("WHILE", p[1])
label=returnLabel()
SCOPE.code.append([None,None,label+":",None,None])
SCOPE.endChildBlock=label
p[0] = Node("while_begin", [child1])
def p_do_while_statement(p):
'''do_while_statement : do_while_statement_begin block KWRD_WHILE LPAREN expression RPAREN STATE_END '''
child2 = create_leaf("WHILE", p[3])
child3 = create_leaf("LPAREN", p[4])
child4 = create_leaf("RPAREN", p[6])
child5 = create_leaf("STATE_END", p[7])
if (p[5].dataType!="Boolean"):
print "Conditional Do While only accepts boolean expression at line",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
SCOPE.code.append(["if",p[5].holdingVariable,"== 1","goto",p[1].value])
freeVar(p[5].holdingVariable)
p[0] = Node("do_while_statement", [p[1], p[2], child2, child3, p[5], child4, child5])
def p_do_while_statement_begin(p):
''' do_while_statement_begin : KWRD_DO '''
child1 = create_leaf("DO", p[1])
label1=returnLabel()
label2=returnLabel()
SCOPE.startChildBlock=label1
SCOPE.endChildBlock=label2
SCOPE.code.append([None,None,None,"goto",label1])
SCOPE.code.append([None,None,label2+":",None,None])
p[0]=Node("do_while_statement_begin",[child1],"Unit",label1)
def p_for_statement(p):
'''for_statement : KWRD_FOR LPAREN for_loop RPAREN block'''
child1 = create_leaf ("FOR",p[1])
child2 = create_leaf ("LPAREN",p[2])
child3 = create_leaf ("RPAREN",p[4])
p[0] = Node("for_statement",[child1,child2,p[3],child3,p[5]])
if p[3].holdingVariable!=None:
for i in p[3].holdingVariable:
freeVar(i)
# def p_for_logic(p):
# ''' for_logic : for_update '''
# if len(p)==2:
# p[0]=Node("for_logic",[p[1]])
# # else:
# # child1 = create_leaf("STATE_END",p[2])
# # p[0] = Node("for_logic",[p[1],child1,p[3]])
# def p_for_update(p):
# ''' for_update : for_loop'''
# p[0]=Node("for_update",[p[1]])
def p_for_loop(p):
''' for_loop : IDENTIFIER CHOOSE expression KWRD_UNTIL expression for_step_opts'''
if SCOPE.is_present(p[1],updateField="symbol"):
pass
else:
print "Undeclared Variable at line",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
if (p[3].dataType==p[5].dataType and p[3].dataType=="Int" and SCOPE.get_attribute_value(p[1],"Type","symbol")=="Int"):
pass
else:
print "Only Integer expressions allowed in For statement at line",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
child1 = create_leaf("IDENTIFIER",p[1])
child2 = create_leaf("CHOOSE",p[2])
child3 = create_leaf("UNTIL_TO",p[4])
p[0] = Node("for_loop_st",[child1,child2,p[3],child3,p[5],p[6]])
if (p[6].holdingVariable!=None):
if p[6].dataType=="Int":
pass
else:
print "Only Integer step allowed at line",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
SCOPE.code.append([SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"=",p[3].holdingVariable,None,None])
freeVar(p[3].holdingVariable)
for_start_label=returnLabel()
for_end_label=returnLabel()
block_start_label=returnLabel()
block_end_label=returnLabel()
SCOPE.code.append([None,None,None,for_start_label+":",None])
SCOPE.code.append(["if",SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"<",p[5].holdingVariable+" goto",block_start_label])
SCOPE.code.append([None,None,None,"goto",for_end_label])
SCOPE.code.append([None,None,None,block_end_label+":",None])
SCOPE.code.append([SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"=",SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"+",p[6].holdingVariable])
SCOPE.code.append([None,None,None,"goto",for_start_label])
SCOPE.code.append([None,None,None,for_end_label+":",None])
SCOPE.startChildBlock=block_start_label
SCOPE.endChildBlock=block_end_label
p[0].holdingVariable=[p[5].holdingVariable,p[6].holdingVariable]
else:
SCOPE.code.append([SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"=",p[3].holdingVariable,None,None])
freeVar(p[3].holdingVariable)
for_start_label=returnLabel()
for_end_label=returnLabel()
block_start_label=returnLabel()
block_end_label=returnLabel()
SCOPE.code.append([None,None,None,for_start_label+":",None])
SCOPE.code.append(["if",SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"< ",p[5].holdingVariable+" goto",block_start_label])
SCOPE.code.append([None,None,None,"goto",for_end_label])
SCOPE.code.append([None,None,None,block_end_label+":",None])
temp=returnTemp()
SCOPE.code.append([temp,"=","1",None,None])
SCOPE.code.append([SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"=",SCOPE.get_attribute_append_name(p[1]).name+"__"+p[1],"+",temp])
freeVar(temp)
SCOPE.code.append([None,None,None,"goto",for_start_label])
SCOPE.code.append([None,None,None,for_end_label+":",None])
SCOPE.startChildBlock=block_start_label
SCOPE.endChildBlock=block_end_label
p[0].holdingVariable=[p[5].holdingVariable]
# def p_for_untilTo(p):
# '''for_untilTo : KWRD_UNTIL
# | KWRD_TO'''
# child1 = create_leaf("UNTIL_TO",p[1])
# p[0]=Node("for_untilTo",[child1])
def p_for_step_opts(p):
''' for_step_opts : KWRD_BY expression
| empty'''
if len(p)==2:
p[0]=Node("for_step_opts",[p[1]])
else :
if (p[2].dataType=="Int"):
pass
else:
print "Only Integer step allowed in For statement at line",p.lexer.lineno
raise Exception("Correct the above Semantics! :P")
child1 = create_leaf("BY",p[1])
p[0]=Node("for_step_opts",[child1,p[2]])
p[0].holdingVariable=p[2].holdingVariable
p[0].dataType=p[2].dataType
def p_switch_statement(p):
'''switch_statement : expression KWRD_MATCH switch_block '''
child1 = create_leaf("MATCH", p[2])
p[0] = Node("switch_statement", [p[1], child1, p[3]])
def p_switch_block(p):
'''switch_block : BLOCK_BEGIN BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[2])
p[0] = Node("switch_block", [child1, child2])
def p_switch_block2(p):
'''switch_block : BLOCK_BEGIN switch_block_statements BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[3])
p[0] = Node("switch_block", [child1, p[2], child2])
def p_switch_block3(p):
'''switch_block : BLOCK_BEGIN switch_labels BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[3])
p[0] = Node("switch_block", [child1, p[2], child2])
def p_switch_block4(p):
'''switch_block : BLOCK_BEGIN switch_block_statements switch_labels BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[4])
p[0] = Node("switch_block", [child1, p[2], p[3], child2])
def p_switch_block_statements(p):
'''switch_block_statements : switch_block_statement
| switch_block_statements switch_block_statement'''
if len(p) == 2:
p[0] = Node("switch_block_statements", [p[1]])
else:
p[0] = Node("switch_block_statements", [p[1], p[2]])
def p_switch_block_statement(p):
'''switch_block_statement : switch_labels block_statements'''
p[0] = Node("switch_block_statement", [p[1], p[2]])
def p_switch_labels(p):
'''switch_labels : switch_label
| switch_labels switch_label'''
if len(p) == 2:
p[0] = Node("switch_labels", [p[1]])
else:
p[0] = Node("switch_labels", [p[1], p[2]])
def p_switch_label(p):
'''switch_label : KWRD_CASE expression FUNTYPE '''
child1 = create_leaf("CASE", p[1])
child2 = create_leaf("FUNTYPE", p[3])
p[0] = Node("switch_label", [child1, p[2], child2])
def p_empty_statement(p):
'''empty_statement : STATE_END '''
child1 = create_leaf("STATE_END", p[1])
p[0] = Node("empty_statement", [child1])
def p_return_statement(p):
'''return_statement : KWRD_RETURN expression_optional STATE_END '''
child1 = create_leaf("RETURN", p[1])
child2 = create_leaf("STATE_END", p[3])
p[0] = Node("return_statement", [child1, p[2], child2])
if (p[2].dataType==SCOPE.funcType):
pass
else:
print ("Return Types not consistent at line",p.lexer.lineno)
raise Exception("Check the semantics! :P")
SCOPE.code.append([None,None,None,"Return",p[2].holdingVariable])
def p_constructor_arguement_list_opt(p):
'''constructor_arguement_list_opt : constructor_arguement_list
| empty '''
p[0] = Node("constructor_arguement_list_opt", [p[1]],p[1].dataType)
def p_constructor_arguement_list(p):
'''constructor_arguement_list : constructor_arguement_list_declarator
| constructor_arguement_list COMMA constructor_arguement_list_declarator'''
if len(p) == 2:
newConst_2=list()
newConst_2.append(p[1].dataType)
p[0] = Node("constructor_arguement_list", [p[1]],newConst_2)
else:
child1 = create_leaf("COMMA", p[2])
newConst_1=list(p[1].dataType)
newConst_2=list()
newConst_2.append(p[3].dataType)
# print newConst_1
# print newConst_2
p[0] = Node("constructor_arguement_list", [p[1], child1, p[3]],newConst_1+newConst_2)
def p_constructor_arguement_list_declarator(p):
'''constructor_arguement_list_declarator : declaration_keyword IDENTIFIER COLON type'''
child1 = create_leaf("IDENTIFIER", p[2])
child2 = create_leaf("COLON", p[3])
attribute=dict()
attribute['Type']=p[4].value
SCOPE.offset+=4
attribute['Offset']=SCOPE.offset
SCOPE.add_entry(p[2],attribute,"symbol")
p[0] = Node("constructor_arguement_list_declarator", [p[1], child1, child2, p[4]],p[4].value)
def p_func_arguement_list_opt(p):
'''func_arguement_list_opt : variable_declarators
| empty '''
p[0] = Node("func_arguement_list_opt", [p[1]],p[1].dataType)
def p_class_declaration(p):
'''class_declaration : class_header class_body'''
p[0] = Node("class_declaration", [p[1], p[2]])
def p_class_header(p):
'''class_header : class_header_name class_header_extends_opt'''
p[0] = Node("class_header", [p[1], p[2]])
def p_class_header_name(p):
'''class_header_name : class_header_name1 func_args_start constructor_arguement_list_opt RPAREN''' # class_header_name1 type_parameters
# | class_header_name1
# child1 = create_leaf("LPAREN", p[2])
child2 = create_leaf("RPAREN", p[4])
#Arguement List : p[3].dataType
#Name : p[1].value
attribute=dict()
attribute['ConstructorList']=p[3].dataType
# print p[3].value
# attribute['ClassVariables']=
SCOPE.prev_env.add_entry(p[1].value,attribute,"object")
# print p[1].value
# print
# SCOPE.print_table()
p[0] = Node("class_header_name", [p[1], p[2], p[3], child2])
SCOPE.objName=p[1].value
def p_class_header_name1(p):
'''class_header_name1 : modifier_opts KWRD_CLASS name'''
child1 = create_leaf("CLASS", p[2])
p[0] = Node("class_header_name1", [p[1], child1, p[3]],"Unit",p[3].value)
def p_class_header_extends_opt(p):
'''class_header_extends_opt : class_header_extends
| empty'''
p[0] = Node("class_header_extends_opt", [p[1]])
def p_class_header_extends(p):
'''class_header_extends : KWRD_EXTNDS name LPAREN func_arguement_list_opt RPAREN'''
child1 = create_leaf("EXTENDS", p[1])
child2 = create_leaf("LPAREN", p[3])
child3 = create_leaf("RPAREN", p[5])
p[0] = Node("class_header_extends", [child1, p[2], child2, p[4], child3])
def p_class_body(p):
'''class_body : class_body_start block_statements_opt class_body_end '''
p[0] = Node("class_body", [p[1], p[2], p[3]])
# p[0] = Node("class_body", [p[1]])
def p_class_body_start(p):
'''class_body_start : BLOCK_BEGIN'''
child1 = create_leaf("BLOCK_BEGIN", p[1])
p[0] = Node("class_body_start", [child1])
SCOPE.code.append([None,None,None,SCOPE.prev_env.name+'__'+SCOPE.objName+":",None])
SCOPE.code.append([None,None,None,"BeginClass",None])
def p_class_body_end(p):
'''class_body_end : BLOCK_END'''
global SCOPE
SCOPE.code.append([None,None,None,"EndClass",None])
# SCOPE.code[1][4]=str(len(SCOPE.tempvar)*4)
#'Guys: Backpatch Later'
PREV_SCOPE=SCOPE.prev_env
SCOPE=PREV_SCOPE
child1 = create_leaf("BLOCK_END", p[1])
p[0] = Node("end_scope", [child1])
def p_method_declaration(p):
'''method_declaration : method_header method_body'''
p[0] = Node("method_declaration", [p[1], p[2]])
def p_method_header(p):
'''method_header : method_header_name func_args_start func_arguement_list_opt RPAREN COLON method_return_type ASSIGN'''
# child1 = create_leaf("LPAREN", p[2])
child2 = create_leaf("RPAREN", p[4])
child3 = create_leaf("COLON", p[5])
child4 = create_leaf("ASSIGN", p[7])
attribute=dict()
attribute['Type']=p[3].dataType
attribute['returnType']=p[6].dataType
SCOPE.prev_env.add_entry(p[1].value,attribute,"function")
SCOPE.funcName=p[1].value
SCOPE.funcType=p[6].dataType
p[0] = Node("method_header", [p[1], p[2], p[3], child2, child3, p[6], child4])
def p_func_args_start(p):
'''func_args_start : LPAREN'''
global SCOPE
NEW_SCOPE = Env(SCOPE)
SCOPE=NEW_SCOPE
child1 = create_leaf("LPAREN", p[1])
p[0] = Node("func_args_start", [child1])
def p_method_return_type(p):
'''method_return_type : type'''
p[0] = Node("method_return_type", [p[1]],p[1].value)
def p_method_return_type1(p):
'''method_return_type : TYPE_VOID'''
child1 = create_leaf("VOID", p[1])
p[0] = Node("method_return_type", [child1],"Unit")
def p_method_header_name(p):
'''method_header_name : modifier_opts KWRD_DEF IDENTIFIER''' # class_header_name1 type_parameters
# | class_header_name1
child1 = create_leaf("DEF", p[2])
child2 = create_leaf("IDENTIFIER", p[3])
p[0] = Node("method_header_name", [p[1], child1, child2],"Unit",p[3])
def p_method_body(p):
'''method_body : method_start_scope block_statements_opt method_end_scope '''
p[0] = Node("method_body", [p[1], p[2], p[3]])
def p_method_start_scope(p):
'''method_start_scope : BLOCK_BEGIN'''
child1 = create_leaf("BLOCK_BEGIN", p[1])
p[0] = Node("end_scope", [child1])
SCOPE.code.append([None,None,None,SCOPE.prev_env.name+"__"+SCOPE.funcName+":",None])
SCOPE.code.append([None,None,None,"BeginFunc",None])
def p_method_end_scope(p):
'''method_end_scope : BLOCK_END'''
global SCOPE
SCOPE.code.append([None,None,None,"EndFunc",None])
# SCOPE.code[1][4]=str(len(SCOPE.tempvar)*4)
PREV_SCOPE=SCOPE.prev_env
SCOPE=PREV_SCOPE
child1 = create_leaf("BLOCK_END", p[1])
p[0] = Node("end_scope", [child1])
def p_modifier(p):
'''modifier : KWRD_PROTECTED
| KWRD_PRIVATE'''
child1 = create_leaf("ModifierKeyword", p[1])
p[0] = Node("modifier", [child1])
def p_type(p):
'''type : primitive_type
| reference_type '''
p[0] = Node("type", [p[1]],p[1].dataType,p[1].value)
# p[0] = p[1]
def p_primitive_type(p):
'''primitive_type : TYPE_INT
| TYPE_FLOAT
| TYPE_CHAR
| TYPE_STRING
| TYPE_BOOLEAN'''
child1 = create_leaf("TYPE", p[1])
p[0] = Node("primitive_type", [child1],"Unit",p[1])
def p_reference_type(p):
'''reference_type : class_data_type
| array_data_type'''
p[0] = Node("reference_type", [p[1]],p[1].dataType,p[1].value)
def p_class_data_type(p):
'''class_data_type : name'''
p[0] = Node("class_data_type", [p[1]],"Unit","Object@"+p[1].value)
def p_array_data_type(p):
'''array_data_type : KWRD_ARRAY LBPAREN type RBPAREN'''
child1 = create_leaf("ARRAY", p[1])
child2 = create_leaf("LBPAREN", p[2])
child3 = create_leaf("RBPAREN", p[4])
p[0] = Node("array_data_type", [child1, child2, p[3], child3],"Unit","Array,"+p[3].value)
def p_array_initializer(p):
''' array_initializer : KWRD_NEW KWRD_ARRAY LBPAREN type RBPAREN LPAREN INT_CONST RPAREN
| KWRD_ARRAY LPAREN argument_list_opt RPAREN '''
if len(p) == 9:
child1 = create_leaf("NEW", p[1])
child2 = create_leaf("ARRAY", p[2])
child3 = create_leaf("LBPAREN", p[3])
child4 = create_leaf("RBPAREN", p[5])
child5 = create_leaf("LPAREN", p[6])
child6 = create_leaf("INT_CONST", p[7])
child7 = create_leaf("RPAREN", p[8])
p[0] = Node("array_initializer", [child1, child2, child3, p[4], child4, child5, child6, child7],"Array,"+p[4].value,None,str(int(p[7])))
else:
child1 = create_leaf("ARRAY", p[1])
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
currType=p[3].dataType[0]
# print p[3].dataType
for i in range(1,len(p[3].dataType)):
if p[3].dataType[i] != currType:
print ("Type error: array can only be of same type at line ",p.lexer.lineno)
raise Exception("Correct the above Semantics! :P")
p[0] = Node("array_initializer", [child1, child2, p[3], child3],"Array,"+currType,None,str(int(len(p[3].dataType))))
p[0].holdingVariable=p[3].holdingVariable
def p_class_initializer(p):
''' class_initializer : KWRD_NEW name LPAREN argument_list_opt RPAREN '''
child1 = create_leaf("NEW", p[1])
child2 = create_leaf("LPAREN", p[3])
child3 = create_leaf("RPAREN", p[5])
if SCOPE.is_present(p[2].value,updateField="object"):
val=SCOPE.get_attribute_value(p[2].value,'ConstructorList',"object")
# print '*************'
# print p[4].holdingVariable
# print p[4].dataType
# print '*************'
if val==p[4].dataType:
pass
else:
print ("Check Constructor Definition , line ",p.lexer.lineno)
raise Exception("Correct the above Semantics! :P")
else:
print ("Undefined Class Definition , line ",p.lexer.lineno)
raise Exception("Correct the above Semantics! :P")
p[0] = Node("class_initializer", [child1, p[2], child2, p[4], child3],"Object@"+p[2].value,None,None,p[4].dataType)
p[0].holdingVariable=p[4].holdingVariable
def p_empty(p):
'empty :'
child1 = create_leaf("Empty", "NOP")
p[0] = Node("empty", [child1])
pass
<file_sep>/asgn3/bin/lexer.py
# lexer for a Scala language
import sys
import os.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)))
from include import lex
from include.tokensDefination import *
from include.regexDefination import *
import include.printLexerOutput as printLexerOutput
# build the lexer
lexer = lex.lex()
# read the file contents
f = open(sys.argv[1],"r")
code_full = f.read()
code_full=code_full+'\n'
f.close()
#use the lexer
lexer.input(code_full)
# print the output
# printLexerOutput.printLexerCode(lexer,code_full)
#print the tokens
printLexerOutput.printLexerTokens(lexer,code_full)
<file_sep>/asgn3/Makefile
all:
cp src/lexerP1.py bin/lexer.py
cp src/parser.py bin/irgen.py
cp src/scalalex.py bin/scalalex.py
python -m py_compile bin/lexer.py
python -m py_compile bin/irgen.py
mv bin/lexer.pyc bin/lexer
mv bin/irgen.pyc bin/irgen
chmod -R 777 bin/
clean:
rm -rf bin/*
rm test1.dot
<file_sep>/asgn2/README.md
This is the repository for
Scala Compiler, the Scala to MIPS compiler hosted at [IITK](https://git.cse.iitk.ac.in/smanocha/compilersproject) and [Github](https://github.com/sid17/CompilersProject)
## Contributors
* [<NAME>](http://home.iitk.ac.in/~smanocha)
* [<NAME>](http://home.iitk.ac.in/~satvikg)
* [<NAME>](http://home.iitk.ac.in/~sshekh)
## Credits
This project is done as a part of CS335 course at IIT Kanpur under the guidance of
[Dr.Subhajit Roy](http://web.cse.iitk.ac.in/users/subhajit/).
## Description
### LEXER
The src folder consists of the file named lexer.py which consists of the lexer code. It includes the files : tokensDefination.py , regexDefination.py , printLexerOutput.py defined under include folder.
* tokensDefination.py : Contains the defination of various tokens used in scala
* regexDefination.py : Defines the regex for various tokens and literals
* printLexerOutput.py : parses the output from the lexer and prints them to the standard output
## Compilation Instructions
### LEXER
The test folder consists of various files namely HelloWorld.scala, etc. The given files can be run for output as
python src/lexer.py test/HelloWorld.scala
To print the output to a file in output folder, run
python src/lexer.py test/HelloWorld.scala > output/parsed.scala
This sends the output to the file parsed.scala under the output folder
Alternately, the given file can also be run via the following commands.
* cd asgn1
* make
* bin/lexer test/HelloWorld.scala
### PARSER
For part 2 of the assignment, we adopt the following procedure for compilation
* cd asgn2
* make
* bin/parser test/HelloWorld.scala
* dotty test1.dot
* dot -Tpdf test1.dot -o HelloWorld.pdf
* gnome-open HelloWorld.pdf
<!-- To run the dot file in graphviz,
dot -Tps a.dot -o outfile.ps -->
<file_sep>/asgn4/include/reference.py
#!/usr/bin/env python2
import ply.lex as lex
import ply.yacc as yacc
from .model import *
class ExpressionParser(object):
def p_expression(self, p):
'''expression : assignment_expression'''
p[0] = p[1]
def p_assignment_expression(self, p):
'''assignment_expression : assignment'''
p[0] = p[1]
def p_assignment(self, p):
'''assignment : postfix_expression assignment_operator assignment_expression'''
p[0] = Assignment(p[2], p[1], p[3])
def p_assignment_operator(self, p):
'''assignment_operator : '='
| TIMES_ASSIGN
| DIVIDE_ASSIGN
| REMAINDER_ASSIGN
| PLUS_ASSIGN
| MINUS_ASSIGN'''
p[0] = p[1]
def p_postfix_expression(self, p):
'''postfix_expression : name
| post_increment_expression
| post_decrement_expression'''
p[0] = p[1]
def p_post_increment_expression(self, p):
'''post_increment_expression : postfix_expression PLUSPLUS'''
p[0] = Unary('x++', p[1])
def p_post_decrement_expression(self, p):
'''post_decrement_expression : postfix_expression MINUSMINUS'''
p[0] = Unary('x--', p[1])
def p_dims_opt(self, p):
'''dims_opt : dims'''
p[0] = p[1]
def p_dims_opt2(self, p):
'''dims_opt : empty'''
p[0] = 0
class StatementParser(object):
def p_block(self, p):
'''block : '{' block_statements_opt '}' '''
p[0] = Block(p[2])
def p_block_statements_opt(self, p):
'''block_statements_opt : block_statements'''
p[0] = p[1]
def p_block_statements_opt2(self, p):
'''block_statements_opt : empty'''
p[0] = []
def p_block_statements(self, p):
'''block_statements : block_statement
| block_statements block_statement'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]]
def p_block_statement(self, p):
'''block_statement : local_variable_declaration_statement
| statement
| class_declaration'''
p[0] = p[1]
def p_local_variable_declaration_statement(self, p):
'''local_variable_declaration_statement : local_variable_declaration ';' '''
p[0] = p[1]
def p_local_variable_declaration(self, p):
'''local_variable_declaration : type variable_declarators'''
p[0] = VariableDeclaration(p[1], p[2])
def p_variable_declarators(self, p):
'''variable_declarators : variable_declarator
| variable_declarators ',' variable_declarator'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]]
def p_variable_declarator(self, p):
'''variable_declarator : variable_declarator_id
| variable_declarator_id '=' variable_initializer'''
if len(p) == 2:
p[0] = VariableDeclarator(p[1])
else:
p[0] = VariableDeclarator(p[1], initializer=p[3])
def p_variable_declarator_id(self, p):
'''variable_declarator_id : NAME dims_opt'''
p[0] = Variable(p[1], dimensions=p[2])
def p_variable_initializer(self, p):
'''variable_initializer : expression
| array_initializer'''
p[0] = p[1]
def p_statement(self, p):
'''statement : statement_without_trailing_substatement
| if_then_statement
| if_then_else_statement
| while_statement
| for_statement'''
p[0] = p[1]
def p_statement_without_trailing_substatement(self, p):
'''statement_without_trailing_substatement : block
| expression_statement
| empty_statement
| switch_statement
| do_statement
| return_statement'''
p[0] = p[1]
def p_expression_statement(self, p):
'''expression_statement : statement_expression ';' '''
p[0] = p[1]
def p_statement_expression(self, p):
'''statement_expression : assignment
| pre_increment_expression
| pre_decrement_expression
| post_increment_expression
| post_decrement_expression
| method_invocation
| class_instance_creation_expression'''
p[0] = p[1]
def p_if_then_statement(self, p):
'''if_then_statement : IF '(' expression ')' statement'''
p[0] = IfThenElse(p[3], p[5])
def p_if_then_else_statement(self, p):
'''if_then_else_statement : IF '(' expression ')' statement_no_short_if ELSE statement'''
p[0] = IfThenElse(p[3], p[5], p[7])
def p_if_then_else_statement_no_short_if(self, p):
'''if_then_else_statement_no_short_if : IF '(' expression ')' statement_no_short_if ELSE statement_no_short_if'''
p[0] = IfThenElse(p[3], p[5], p[7])
def p_while_statement(self, p):
'''while_statement : WHILE '(' expression ')' statement'''
p[0] = While(p[3], p[5])
def p_while_statement_no_short_if(self, p):
'''while_statement_no_short_if : WHILE '(' expression ')' statement_no_short_if'''
p[0] = While(p[3], p[5])
def p_for_statement(self, p):
'''for_statement : FOR '(' for_init_opt ';' expression_opt ';' for_update_opt ')' statement'''
p[0] = For(p[3], p[5], p[7], p[9])
def p_for_statement_no_short_if(self, p):
'''for_statement_no_short_if : FOR '(' for_init_opt ';' expression_opt ';' for_update_opt ')' statement_no_short_if'''
p[0] = For(p[3], p[5], p[7], p[9])
def p_method_invocation(self, p):
'''method_invocation : NAME '(' argument_list_opt ')' '''
p[0] = MethodInvocation(p[1], arguments=p[3])
def p_empty_statement(self, p):
'''empty_statement : ';' '''
p[0] = Empty()
def p_switch_statement(self, p):
'''switch_statement : SWITCH '(' expression ')' switch_block'''
p[0] = Switch(p[3], p[5])
def p_do_statement(self, p):
'''do_statement : DO statement WHILE '(' expression ')' ';' '''
p[0] = DoWhile(p[5], body=p[2])
def p_return_statement(self, p):
'''return_statement : RETURN expression_opt ';' '''
p[0] = Return(p[2])
def p_statement_no_short_if(self, p):
'''statement_no_short_if : statement_without_trailing_substatement
| labeled_statement_no_short_if
| if_then_else_statement_no_short_if
| while_statement_no_short_if
| for_statement_no_short_if'''
p[0] = p[1]
def p_for_init_opt(self, p):
'''for_init_opt : for_init
| empty'''
p[0] = p[1]
def p_for_init(self, p):
'''for_init : statement_expression_list
| local_variable_declaration'''
p[0] = p[1]
def p_statement_expression_list(self, p):
'''statement_expression_list : statement_expression
| statement_expression_list ',' statement_expression'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]]
def p_expression_opt(self, p):
'''expression_opt : expression
| empty'''
p[0] = p[1]
def p_for_update_opt(self, p):
'''for_update_opt : for_update
| empty'''
p[0] = p[1]
def p_for_update(self, p):
'''for_update : statement_expression_list'''
p[0] = p[1]
def p_comma_opt(self, p):
'''comma_opt : ','
| empty'''
# ignore
def p_array_initializer(self, p):
'''array_initializer : '{' comma_opt '}' '''
p[0] = ArrayInitializer()
def p_array_initializer2(self, p):
'''array_initializer : '{' variable_initializers '}'
| '{' variable_initializers ',' '}' '''
p[0] = ArrayInitializer(p[2])
def p_variable_initializers(self, p):
'''variable_initializers : variable_initializer
| variable_initializers ',' variable_initializer'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]]
def p_switch_block3(self, p):
'''switch_block : '{' switch_label '}' '''
p[0] = [SwitchCase(p[2])]
def p_switch_label(self, p):
'''switch_label : CASE constant_expression ':'
| DEFAULT ':' '''
if len(p) == 3:
p[0] = 'default'
else:
p[0] = p[2]
def p_constant_expression(self, p):
'''constant_expression : expression'''
p[0] = p[1]
class NameParser(object):
def p_name(self, p):
'''name : simple_name'''
p[0] = p[1]
def p_simple_name(self, p):
'''simple_name : NAME'''
p[0] = Name(p[1])
class LiteralParser(object):
def p_literal(self, p):
'''literal : NUM
| CHAR_LITERAL
| STRING_LITERAL
| TRUE
| FALSE
| NULL'''
p[0] = Literal(p[1])
class TypeParser(object):
def p_type(self, p):
'''type : primitive_type
| reference_type'''
p[0] = p[1]
def p_primitive_type(self, p):
'''primitive_type : BOOLEAN
| VOID
| BYTE
| SHORT
| INT
| LONG
| CHAR
| FLOAT
| DOUBLE'''
p[0] = p[1]
def p_reference_type(self, p):
'''reference_type : array_type'''
p[0] = p[1]
def p_array_type(self, p):
'''array_type : primitive_type dims'''
p[0] = Type(p[1], dimensions=p[2])<file_sep>/asgn4/src/scalalex.py
# lexer for a Scala language
import sys
import os.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)))
import ply.lex as lex
from include.tokensDefination import *
from include.regexDefination import *
import include.printLexerOutput as printLexerOutput
# build the lexer
lexer = lex.lex()
# read the file contents
#f = open(sys.argv[1],"r")
#code_full = f.read()
#code_full=code_full+'\n'
#f.close()
#use the lexer
#lexer.input(code_full)
# print the output
#printLexerOutput.printLexer(lexer,code_full)
<file_sep>/asgn3/src/testparser.py
import sys
sys.path.insert(0,"../..")
if sys.version_info[0] >= 3:
raw_input = input
tokens = (
'NAME','NUMBER',
)
literals = ['=','+','-','*','/', '(',')']
# Tokens
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
t_ignore = " \t"
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
import ply.lex as lex
lex.lex()
class Node(object):
gid = 1
def __init__(self,name,children):
self.name = name
self.children = children
self.id=Node.gid
Node.gid+=1
# Parsing rules
precedence = (
('left','+','-'),
('left','*','/'),
('right','UMINUS'),
)
# dictionary of names
names = { }
def create_child_nodes(name1,name2):
leaf1 = Node(name2,[])
leaf2 = Node(name1,[leaf1])
return leaf2
def p_statement_assign(p):
'statement : NAME "=" expression'
names[p[1]] = p[3]
child1=create_child_nodes("NAME",p[1]);
child2=create_child_nodes("EQUAL",p[2]);
p[0] = Node("statement -> NAME = expression",[child1,child2,p[3]])
def p_statement_expr(p):
'statement : expression'
p[0] = Node("statement -> expression",[p[1]])
# print(p[1])
def p_expression_binop(p):
'''expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression'''
#p[0] = Node("binop",[p[1],p[3]], p[2])
child1=create_child_nodes("binop",p[2])
p[0] = Node("expression -> expression binop expression",[p[1],child1,p[3]])
# if p[2] == '+' : #p[0] = p[1] + p[3]
# elif p[2] == '-': #p[0] = p[1] - p[3]
# elif p[2] == '*': #p[0] = p[1] * p[3]
# elif p[2] == '/': #p[0] = p[1] / p[3]
def p_expression_uminus(p):
"expression : '-' expression %prec UMINUS"
#p[0] = -p[2]
def p_expression_group(p):
"expression : '(' expression ')'"
child1=create_child_nodes("LEFT_PAREN",p[1])
child3=create_child_nodes("RIGHT_PAREN",p[3])
p[0] = Node("expression -> ( expression )",[child1,p[2],child3])
#p[0] = Node("group", [p[2]], ['(',')'])
# #p[0] = p[2]
def p_expression_number(p):
"expression : NUMBER"
child1=create_child_nodes("NUMBER",p[1])
p[0] = Node("expression -> NUMBER",[child1])
# #p[0] = p[1]
#p[0] = Node("number", [], [p[1]])
def p_expression_name(p):
"expression : NAME"
try:
child1=create_child_nodes("NAME",p[1])
p[0] = Node("expression -> NAME",[child1])
# p[0] = names[p[1]]
except LookupError:
print("Undefined name '%s'" % p[1])
assert(False);
p[0] = 0
def p_error(p):
if p:
print("Syntax error at '%s'" % p.value)
else:
print("Syntax error at EOF")
import ply.yacc as yacc
yacc.yacc()
def printnodes(current_node):
# current_node.id = gid
# print current_node.name
if (len(current_node.children)==0):
return;
# val2 = val
for i in current_node.children:
# printnodes(i)
# val2 += 1
print str(current_node.id)+" [label=\""+str(current_node.name)+"\"];"+str(i.id)+" [label=\""+str(i.name)+"\"];"+str(current_node.id)+"->"+str(i.id)
for i in current_node.children:
# val=val+1
printnodes(i)
# print current_node.count,'->',i
# # print ,
# for i in current_node.children:
# print current_node.count,'->',i.count
# # print i.type,
# # print
# for i in current_node.children:
# # print 'hello'
# printnodes(i)
while 1:
try:
s = raw_input('calc > ')
except EOFError:
break
if not s: continue
# print yacc.parse(s).children[0].children[0].type
node=yacc.parse(s)
printnodes(node)
# for node in yacc.parse(s):
# print node.type
# yacc.parse(s)
<file_sep>/asgn2/include/grammar.py
from symbolTable import *
SCOPE = Env(None) # Current Scope
class Node(object):
gid = 1
def __init__(self,name,children,dataType="Unit",val=None,size=0,argumentList=None):
self.name = name
self.children = children
self.id=Node.gid
self.value=val
self.size=size
self.argumentList=argumentList
self.dataType=dataType
Node.gid+=1
def create_leaf(name1,name2,dataType="Unit"):
leaf1 = Node(name2,[],dataType)
leaf2 = Node(name1,[leaf1],dataType)
return leaf2
def p_program_structure(p):
'''ProgramStructure : ProgramStructure class_and_objects
| class_and_objects '''
if len(p) == 3:
if not (p[1].dataType=="Unit" and p[2].dataType=="Unit"):
print "Type Error"
assert(False)
p[0] = Node("ProgramStructure", [p[1], p[2]])
else:
if not (p[1].dataType=="Unit"):
print "Type Error"
assert(False)
p[0] = Node("ProgramStructure", [p[1]])
def p_class_and_objects(p):
'''class_and_objects : SingletonObject
| class_declaration'''
if not (p[1].dataType=="Unit"):
print "Type Error"
assert(False)
p[0] = Node("class_and_objects", [p[1]])
def p_SingletonObject(p):
'SingletonObject : ObjectDeclare block'
if not (p[1].dataType=="Unit" and p[2].dataType=="Unit" ):
print "Type Error"
assert(False)
p[0] = Node("SingletonObject", [p[1], p[2]])
# object declaration
def p_object_declare(p):
'''ObjectDeclare : KWRD_OBJECT IDENTIFIER
| KWRD_OBJECT IDENTIFIER KWRD_EXTNDS IDENTIFIER'''
if len(p) == 3:
child1 = create_leaf("KWRD_OBJECT", p[1])
child2 = create_leaf("IDENTIFIER", p[2])
if not (child1.dataType=="Unit" and child2.dataType=="Unit"):
print "Type Error"
assert(False)
p[0] = Node("ObjectDeclare", [child1, child2])
else:
child1 = create_leaf("KWRD_OBJECT", p[1])
child2 = create_leaf("IDENTIFIER", p[2])
child3 = create_leaf("KWRD_EXTNDS", p[3])
child4 = create_leaf("IDENTIFIER", p[4])
if not (child1.dataType=="Unit" and child2.dataType=="Unit" and child3.dataType=="Unit" and child4.dataType=="Unit"):
print "Type Error"
assert(False)
p[0] = Node("ObjectDeclare", [child1, child2, child3, child4])
# expression
def p_expression(p):
'''expression : assignment_expression'''
p[0] = Node("expression", [p[1]],p[1].dataType)
def p_expression_optional(p):
'''expression_optional : expression
| empty'''
p[0] = Node("expression_optional", [p[1]],p[1].dataType)
def p_assignment_expression(p):
'''assignment_expression : assignment
| conditional_or_expression'''
p[0] = Node("assignment_expression", [p[1]],p[1].dataType)
# assignment
def p_assignment(p):
'''assignment : valid_variable assignment_operator assignment_expression'''
if not (p[1].dataType == p[3].dataType):
print "Type Error"
assert(False)
p[0] = Node("assignment", [p[1], p[2], p[3]],p[3].dataType)
def p_assignment_operator(p):
'''assignment_operator : ASSIGN
| TIMES_ASSIGN
| DIVIDE_ASSIGN
| REMAINDER_ASSIGN
| PLUS_ASSIGN
| MINUS_ASSIGN
| LSHIFT_ASSIGN
| RSHIFT_ASSIGN
| AND_ASSIGN
| OR_ASSIGN
| XOR_ASSIGN'''
child1 = create_leaf("ASSIGN_OP", p[1])
p[0] = Node("assignment_operator", [child1])
# OR(||) has least precedence, and OR is left assosiative
# a||b||c => first evalutae a||b then (a||b)||c
def p_conditional_or_expression(p):
'''conditional_or_expression : conditional_and_expression
| conditional_or_expression OR conditional_and_expression'''
if len(p) == 2:
p[0] = Node("conditional_or_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("OR", p[2])
if not (p[1].dataType=="Boolean" and p[3].dataType=="Boolean"):
print "type error"
assert(False)
p[0] = Node("conditional_or_expression", [p[1], child1, p[3]],p[1].dataType)
# AND(&&) has next least precedence, and AND is left assosiative
# a&&b&&c => first evalutae a&&b then (a&&b)&&c
def p_conditional_and_expression(p):
'''conditional_and_expression : inclusive_or_expression
| conditional_and_expression AND inclusive_or_expression'''
if len(p) == 2:
p[0] = Node("conditional_and_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("AND", p[2])
if not (p[1].dataType=="Boolean" and p[3].dataType=="Boolean"):
print "type error"
assert(False)
p[0] = Node("conditional_and_expression", [p[1], child1, p[3]],p[1].dataType)
def p_inclusive_or_expression(p):
'''inclusive_or_expression : exclusive_or_expression
| inclusive_or_expression OR_BITWISE exclusive_or_expression'''
if len(p) == 2:
p[0] = Node("inclusive_or_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("OR_BITWISE", p[2])
if not (p[1].dataType == "Int" and p[3].dataType == "Int"):
print "Type Error"
assert(False)
p[0] = Node("inclusive_or_expression", [p[1], child1, p[3]],p[1].dataType)
def p_exclusive_or_expression(p):
'''exclusive_or_expression : and_expression
| exclusive_or_expression XOR and_expression'''
if len(p) == 2:
p[0] = Node("exclusive_or_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("XOR", p[2])
if not (p[1].dataType == "Int" and p[3].dataType == "Int"):
print "Type Error"
assert(False)
p[0] = Node("exclusive_or_expression", [p[1], child1, p[3]],p[1].dataType)
def p_and_expression(p):
'''and_expression : equality_expression
| and_expression AND_BITWISE equality_expression'''
if len(p) == 2:
p[0] = Node("and_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("AND_BITWISE", p[2])
if not (p[1].dataType == "Int" and p[3].dataType == "Int"):
print "Type Error"
assert(False)
p[0] = Node("and_expression", [p[1], child1, p[3]],p[1].dataType)
def p_equality_expression(p):
'''equality_expression : relational_expression
| equality_expression EQUAL relational_expression
| equality_expression NEQUAL relational_expression'''
if len(p) == 2:
p[0] = Node("relational_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("EqualityOp", p[2])
if not (p[1].dataType == p[3].dataType):
print "Type Error"
assert(False)
p[0] = Node("relational_expression", [p[1], child1, p[3]],"Boolean")
def p_relational_expression(p):
'''relational_expression : shift_expression
| relational_expression GREATER shift_expression
| relational_expression LESS shift_expression
| relational_expression GEQ shift_expression
| relational_expression LEQ shift_expression'''
if len(p) == 2:
p[0] = Node("relational_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("RelationalOp", p[2])
if not (p[1].dataType == p[3].dataType):
print "Type Error"
assert(False)
p[0] = Node("relational_expression", [p[1], child1, p[3]],"Boolean")
def p_shift_expression(p):
'''shift_expression : additive_expression
| shift_expression LSHIFT additive_expression
| shift_expression RSHIFT additive_expression'''
if len(p) == 2:
p[0] = Node("shift_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("ShiftOp", p[2])
if not (p[1].dataType == p[3].dataType and p[1].dataType=="Int"):
print "Type Error"
assert(False)
p[0] = Node("shift_expression", [p[1], child1, p[3]],p[1].dataType)
def p_additive_expression(p):
'''additive_expression : multiplicative_expression
| additive_expression PLUS multiplicative_expression
| additive_expression MINUS multiplicative_expression'''
if len(p) == 2:
p[0] = Node("additive_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("AddOp", p[2])
currType="Int"
if (p[1].dataType=="Int" and p[3].dataType=="Int"):
currType="Int"
elif (p[1].dataType=="Int" and p[3].dataType=="Double"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Double"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Int"):
currType="Double"
elif (p[1].dataType=="String" and p[3].dataType=="String" and p[2]=="PLUS"):
currType="String"
else:
print "Type Error"
assert(False)
p[0] = Node("additive_expression", [p[1], child1, p[3]],currType)
def p_multiplicative_expression(p):
'''multiplicative_expression : unary_expression
| multiplicative_expression TIMES unary_expression
| multiplicative_expression DIVIDE unary_expression
| multiplicative_expression REMAINDER unary_expression'''
if len(p) == 2:
p[0] = Node("multiplicative_expression", [p[1]],p[1].dataType)
else:
child1 = create_leaf("MultOp", p[2])
currType="Int"
if (p[1].dataType=="Int" and p[3].dataType=="Int"):
currType="Int"
elif (p[1].dataType=="Int" and p[3].dataType=="Double" and p[2] != "REMAINDER"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Double" and p[2] != "REMAINDER"):
currType="Double"
elif (p[1].dataType=="Double" and p[3].dataType=="Int" and p[2] != "REMAINDER"):
currType="Double"
else:
print "Type Error"
assert(False)
p[0] = Node("multiplicative_expression", [p[1], child1, p[3]],currType)
def p_unary_expression(p):
'''unary_expression : PLUS unary_expression
| MINUS unary_expression
| unary_expression_not_plus_minus'''
if len(p) == 3:
if not (p[2].dataType == "Int" or p[2].dataType=="Double"):
print "Type Error"
assert(False)
child1 = create_leaf("UnaryOp", p[1])
p[0] = Node("unary_expression", [child1, p[2]],p[2].dataType)
else:
p[0] = Node("unary_expression", [p[1]],p[1].dataType)
def p_unary_expression_not_plus_minus(p):
'''unary_expression_not_plus_minus : base_variable_set
| TILDA unary_expression
| NOT unary_expression
| cast_expression'''
if len(p) == 2:
p[0] = Node("unary_expression_not_plus_minus", [p[1]],p[1].dataType)
else:
if (p[1]=="TILDA" and p[2].dataType=="Int"):
pass
elif (p[1]=="NOT" and p[2].dataType=="Boolean"):
pass
else:
print "Type Error"
assert(False)
child1 = create_leaf("Unary_1Op", p[1])
p[0] = Node("unary_expression_not_plus_minus", [child1, p[2]],p[2].dataType)
def p_base_variable_set(p):
'''base_variable_set : variable_literal
| LPAREN expression RPAREN'''
if len(p) == 2:
p[0] = Node("base_variable_set", [p[1]],p[1].dataType)
else:
child1 = create_leaf("LPAREN", p[1])
child2 = create_leaf("RPAREN", p[3])
p[0] = Node("base_variable_set", [child1, p[2], child2],p[2].dataType)
def p_cast_expression(p):
'''cast_expression : LPAREN primitive_type RPAREN unary_expression'''
flag=0
currType="Int"
if (p[2].dataType=="Unit" and (p[4].dataType=="Double" or p[4].dataType=="Int")):
if (p[2].value=="Int" or p[2].value=="Double"):
flag=1
if (p[2].value=="Int"):
currType="Int"
elif (p[2].value=="Double"):
currType="Double"
else:
flag=2
if (flag==0):
print "Type Error"
assert(False)
elif (flag==2):
print "Cast Error"
assert(False)
child1 = create_leaf("LPAREN", p[1])
child2 = create_leaf("RPAREN", p[3])
p[0] = Node("cast_expression", [child1, p[2], child2, p[4]],currType)
def p_primary(p):
'''primary : literal
| method_invocation'''
p[0] = Node("primary", [p[1]],p[1].dataType)
def p_literal_1(p):
'''literal : int_float'''
p[0] = Node("literal", [p[1]],p[1].dataType)
def p_literal_2(p):
'''literal : CHARACTER'''
child1 = create_leaf("LiteralConst", p[1],"Char")
p[0] = Node("literal", [child1],"Char")
def p_literal_3(p):
'''literal : STRING_CONST'''
child1 = create_leaf("LiteralConst", p[1],"String")
p[0] = Node("literal", [child1],"String")
def p_literal_4(p):
'''literal : BOOL_CONSTT
| BOOL_CONSTF'''
child1 = create_leaf("LiteralConst", p[1],"Boolean")
p[0] = Node("literal", [child1],"Boolean")
def p_literal_5(p):
'''literal : KWRD_NULL'''
child1 = create_leaf("LiteralConst", p[1],"Unit")
p[0] = Node("literal", [child1],"Unit")
# def p_literal(p):
# '''literal : int_float
# | CHARACTER
# | STRING_CONST
# | BOOL_CONSTT
# | BOOL_CONSTF
# | KWRD_NULL'''
# if type(p[1]) == type("sample-string"): # here
# currType="Unit"
# # if (p[1]=="True" or p[1]=="False")
# child1 = create_leaf("LiteralConst", p[1])
# p[0] = Node("literal", [child1])
# else:
# p[0] = Node("literal", [p[1]],p[1].dataType)
def p_int_float_1(p):
'''int_float : FLOAT_CONST'''
child1 = create_leaf("FloatConst", p[1],"Double")
p[0] = Node("int_float", [child1],"Double")
def p_int_float_2(p):
'''int_float : INT_CONST'''
child1 = create_leaf("IntConst", p[1],"Int")
p[0] = Node("int_float", [child1],"Int")
def p_method_invocation(p):
'''method_invocation : name LPAREN argument_list_opt RPAREN '''
child1 = create_leaf("LPAREN", p[2])
child2 = create_leaf("RPAREN", p[4])
p[0] = Node("method_invocation", [p[1], child1, p[3], child2])
def p_array_access(p):
'''array_access : name LBPAREN expression RBPAREN '''
child1 = create_leaf("LBPAREN", p[2])
child2 = create_leaf("RBPAREN", p[4])
p[0] = Node("array_access", [p[1], child1, p[3], child2])
def p_argument_list_opt(p):
'''argument_list_opt : argument_list'''
p[0] = Node("argument_list_opt", [p[1]],p[1].dataType)
def p_argument_list_opt2(p):
'''argument_list_opt : empty'''
p[0] = Node("argument_list_opt", [p[1]],p[1].dataType)
def p_argument_list(p):
'''argument_list : expression
| argument_list COMMA expression'''
if len(p) == 2:
newType_1 = list()
newType_1.append(p[1].dataType)
p[0] = Node("argument_list", [p[1]],newType_1)
else:
newType_1 = list(p[1].dataType)
newType_2 = list()
newType_2.append(p[3].dataType)
child1 = create_leaf("COMMA", p[2])
p[0] = Node("argument_list", [p[1], child1, p[3]],newType_1+newType_2)
# object identifier and identifier names for left hand assignment
def p_name(p):
'''name : simple_name
| qualified_name'''
p[0] = Node("name", [p[1]],p[1].dataType,p[1].value)
def p_simple_name(p):
'''simple_name : IDENTIFIER'''
val=SCOPE.get_attribute_value(p[1],'Type',"symbol")
child1 = create_leaf("IDENTIFIER", p[1])
p[0] = Node("simple_name", [child1],val,p[1])
def p_qualified_name(p):
'''qualified_name : name DOT simple_name'''
child1 = create_leaf("DOT", p[2])
p[0] = Node("qualified_name", [p[1], child1, p[3]])
def p_valid_variable(p):
'''valid_variable : name
| array_access'''
p[0] = Node("valid_variable", [p[1]],p[1].dataType)
def p_variableliteral(p):
'''variable_literal : valid_variable
| primary'''
p[0] = Node("variable_literal", [p[1]],p[1].dataType)
# BLOCK STATEMENTS
def p_block(p):
'''block : BLOCK_BEGIN block_statements_opt BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[3])
p[0] = Node("block", [child1, p[2], child2])
def p_block_statements_opt(p):
'''block_statements_opt : block_statements'''
p[0] = Node("block_statements_opt", [p[1]],p[1].dataType)
def p_block_statements_opt2(p):
'''block_statements_opt : empty'''
p[0] = Node("block_statements_opt", [p[1]],p[1].dataType)
def p_block_statements(p):
'''block_statements : block_statement
| block_statements block_statement'''
if len(p) == 2:
p[0] = Node("block_statement", [p[1]])
else:
p[0] = Node("block_statement", [p[1], p[2]])
def p_block_statement(p):
'''block_statement : local_variable_declaration_statement
| statement
| class_declaration
| SingletonObject
| method_declaration'''
p[0] = Node("block_statement", [p[1]],p[1].dataType)
# var (a:Int)=(h);
# var (a:Int,b:Int,c:Int)=(1,2,3);
# var (a:Int)=(h)
# var (a:Int,b:Int,c:Int)=(1,2,3)
# supported
def p_modifier_opts(p):
'''modifier_opts : modifier
| empty '''
p[0] = Node("modifier_opts", [p[1]],p[1].dataType)
def p_declaration_keyword(p):
'''declaration_keyword : KWRD_VAR
| KWRD_VAL '''
child1 = create_leaf("KWRD VAR/VAL", p[1])
p[0] = Node("declaration_keyword", [child1])
def p_local_variable_declaration_statement(p):
'''local_variable_declaration_statement : local_variable_declaration STATE_END '''
child1 = create_leaf("STATE_END", p[2])
p[0] = Node("local_variable_declaration_statement", [p[1], child1])
#
def p_local_variable_declaration(p):
'''local_variable_declaration : modifier_opts declaration_keyword variable_declaration_body'''
p[0] = Node("local_variable_declaration", [p[1], p[2], p[3]])
def p_variable_declaration_initializer(p):
'''variable_declaration_initializer : expression
| array_initializer
| class_initializer'''
p[0] = Node("variable_declaration_initializer", [p[1]],p[1].dataType)
def p_variable_arguement_list(p):
''' variable_arguement_list : variable_declaration_initializer
| variable_arguement_list COMMA variable_declaration_initializer'''
if len(p) == 2:
newType_1 = list()
newType_1.append(p[1].dataType)
print p[1].dataType
print newType_1
p[0] = Node("variable_arguement_list", [p[1]],newType_1)
else:
child1 = create_leaf("COMMA", p[2])
newType_1 = list(p[1].dataType)
newType_2 = list()
newType_2.append(p[3].dataType)
print newType_1
print newType_2
p[0] = Node("variable_arguement_list", [p[1], child1, p[3]],newType_1+newType_2)
def p_variable_declaration_body_1(p):
'''variable_declaration_body : variable_declarator ASSIGN variable_declaration_initializer '''
if (p[1].dataType!=p[3].dataType):
print("Type Error")
assert(False)
child1 = create_leaf("ASSIGN", p[2])
p[0] = Node("variable_declaration_body", [p[1], child1, p[3]])
def p_variable_declaration_body_2(p):
'''variable_declaration_body : LPAREN variable_declarators RPAREN ASSIGN LPAREN variable_arguement_list RPAREN'''
child1 = create_leaf("LPAREN", p[1])
child2 = create_leaf("RPAREN", p[3])
child3 = create_leaf("ASSIGN", p[4])
child4 = create_leaf("LPAREN", p[5])
child5 = create_leaf("RPAREN", p[7])
print p[2].dataType
print p[6].dataType
if (p[2].dataType!=p[6].dataType):
print("Type Error")
assert(False)
p[0] = Node("variable_declaration_body", [child1, p[2], child2, child3, child4, p[6], child5])
#left
def p_variable_declaration_body_3(p):
''' variable_declaration_body : IDENTIFIER ASSIGN LPAREN func_arguement_list_opt RPAREN FUNTYPE expression'''
child1 = create_leaf("IDENTIFIER", p[1])
child2 = create_leaf("ASSIGN", p[2])
child3 = create_leaf("LPAREN", p[3])
child4 = create_leaf("RPAREN", p[5])
child5 = create_leaf("FUNTYPE", p[6])
p[0] = Node("variable_declaration_body", [child1, child2, child3, p[4], child4, child5,p[7]])
def p_variable_declarators(p):
'''variable_declarators : variable_declarator
| variable_declarators COMMA variable_declarator'''
if len(p) == 2:
newType_1 = list()
newType_1.append(p[1].dataType)
p[0] = Node("variable_declarators", [p[1]],newType_1)
else:
newType_1 = list(p[1].dataType)
newType_2 = list()
newType_2.append(p[3].dataType)
child1 = create_leaf("COMMA", p[2])
p[0] = Node("variable_declarators", [p[1], child1, p[3]],newType_1+newType_2)
def p_variable_declarator(p):
'''variable_declarator : variable_declarator_id'''
p[0] = Node("variable_declarator", [p[1]],p[1].dataType)
def p_variable_declarator_id(p):
'''variable_declarator_id : IDENTIFIER COLON type'''
#Insert in symbol table
attribute=dict()
attribute['Type']=p[3].value
print 'Hello'+p[3].value
SCOPE.add_entry(p[1],attribute,"symbol")
child1 = create_leaf("IDENTIFIER", p[1])
child2 = create_leaf("COLON", p[2])
p[0] = Node("variable_declarator_id", [child1, child2, p[3]],p[3].value)
# p[0] = Variable(p[1], dimensions=p[2])
def p_statement(p):
'''statement : normal_statement
| if_then_statement
| if_then_else_statement
| while_statement
| do_while_statement
| for_statement'''
p[0] = Node("statement", [p[1]],p[1].dataType)
def p_normal_statement(p):
'''normal_statement : block
| expression_statement
| empty_statement
| return_statement
| switch_statement'''
p[0] = Node("normal_statement", [p[1]],p[1].dataType)
def p_expression_statement(p):
'''expression_statement : statement_expression STATE_END'''
child1 = create_leaf("STATE_END", p[2])
p[0] = Node("expression_statement", [p[1], child1])
def p_statement_expression(p):
'''statement_expression : assignment
| method_invocation'''
p[0] = Node("statement_expression", [p[1]],p[1].dataType)
def p_if_then_statement(p):
'''if_then_statement : KWRD_IF LPAREN expression RPAREN statement'''
child1 = create_leaf("IF", p[1])
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
p[0] = Node("if_then_statement", [child1, child2, p[3], child3, p[5]])
def p_if_then_else_statement(p):
'''if_then_else_statement : KWRD_IF LPAREN expression RPAREN if_then_else_intermediate KWRD_ELSE statement'''
child1 = create_leaf("IF", p[1])
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
child4 = create_leaf("ELSE", p[6])
p[0] = Node("if_then_else_statement", [child1, child2, p[3], child3, p[5], child4, p[7]])
def p_if_then_else_statement_precedence(p):
'''if_then_else_statement_precedence : KWRD_IF LPAREN expression RPAREN if_then_else_intermediate KWRD_ELSE if_then_else_intermediate'''
child1 = create_leaf("IF", p[1])
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
child4 = create_leaf("ELSE", p[6])
p[0] = Node("if_then_else_statement_precedence", [child1, child2, p[3], child3, p[5], child4, p[7]])
def p_if_then_else_intermediate(p):
'''if_then_else_intermediate : normal_statement
| if_then_else_statement_precedence'''
p[0] = Node("if_then_else_intermediate", [p[1]])
def p_while_statement(p):
'''while_statement : KWRD_WHILE LPAREN expression RPAREN statement'''
child1 = create_leaf("WHILE", p[1])
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
p[0] = Node("while_statement", [child1, child2, p[3], child3, p[5]])
def p_do_while_statement(p):
'''do_while_statement : KWRD_DO statement KWRD_WHILE LPAREN expression RPAREN STATE_END '''
child1 = create_leaf("DO", p[1])
child2 = create_leaf("WHILE", p[3])
child3 = create_leaf("LPAREN", p[4])
child4 = create_leaf("RPAREN", p[6])
child5 = create_leaf("STATE_END", p[7])
p[0] = Node("do_while_statement", [child1, p[2], child2, child3, p[5], child4, child5])
def p_for_statement(p):
'''for_statement : KWRD_FOR LPAREN for_logic RPAREN statement'''
child1 = create_leaf ("FOR",p[1])
child2 = create_leaf ("LPAREN",p[2])
child3 = create_leaf ("RPAREN",p[4])
p[0] = Node("for_statement",[child1,child2,p[3],child3,p[5]])
def p_for_logic(p):
''' for_logic : for_update
| for_update STATE_END for_logic '''
if len(p)==2:
p[0]=Node("for_logic",[p[1]])
else:
child1 = create_leaf("STATE_END",p[2])
p[0] = Node("for_logic",[p[1],child1,p[3]])
def p_for_update(p):
''' for_update : for_loop for_step_opts '''
p[0]=Node("for_update",[p[1],p[2]])
def p_for_loop(p):
''' for_loop : IDENTIFIER CHOOSE expression for_untilTo expression '''
child1 = create_leaf("IDENTIFIER",p[1])
child2 = create_leaf("CHOOSE",p[2])
p[0] = Node("for_loop_st",[child1,child2,p[3],p[4],p[5]])
def p_for_untilTo(p):
'''for_untilTo : KWRD_UNTIL
| KWRD_TO'''
child1 = create_leaf("UNTIL_TO",p[1])
p[0]=Node("for_untilTo",[child1])
def p_for_step_opts(p):
''' for_step_opts : KWRD_BY expression
| empty'''
if len(p)==2:
p[0]=Node("for_step_opts",[p[1]])
else :
child1 = create_leaf("BY",p[1])
p[0]=Node("for_step_opts",[child1,p[2]])
def p_switch_statement( p):
'''switch_statement : expression KWRD_MATCH switch_block '''
child1 = create_leaf("MATCH", p[2])
p[0] = Node("switch_statement", [p[1], child1, p[3]])
def p_switch_block(p):
'''switch_block : BLOCK_BEGIN BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[2])
p[0] = Node("switch_block", [child1, child2])
def p_switch_block2(p):
'''switch_block : BLOCK_BEGIN switch_block_statements BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[3])
p[0] = Node("switch_block", [child1, p[2], child2])
def p_switch_block3(p):
'''switch_block : BLOCK_BEGIN switch_labels BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[3])
p[0] = Node("switch_block", [child1, p[2], child2])
def p_switch_block4(p):
'''switch_block : BLOCK_BEGIN switch_block_statements switch_labels BLOCK_END '''
child1 = create_leaf("BLOCK_BEGIN", p[1])
child2 = create_leaf("BLOCK_END", p[4])
p[0] = Node("switch_block", [child1, p[2], p[3], child2])
def p_switch_block_statements(p):
'''switch_block_statements : switch_block_statement
| switch_block_statements switch_block_statement'''
if len(p) == 2:
p[0] = Node("switch_block_statements", [p[1]])
else:
p[0] = Node("switch_block_statements", [p[1], p[2]])
def p_switch_block_statement(p):
'''switch_block_statement : switch_labels block_statements'''
p[0] = Node("switch_block_statement", [p[1], p[2]])
def p_switch_labels(p):
'''switch_labels : switch_label
| switch_labels switch_label'''
if len(p) == 2:
p[0] = Node("switch_labels", [p[1]])
else:
p[0] = Node("switch_labels", [p[1], p[2]])
def p_switch_label(p):
'''switch_label : KWRD_CASE expression FUNTYPE '''
child1 = create_leaf("CASE", p[1])
child2 = create_leaf("FUNTYPE", p[3])
p[0] = Node("switch_label", [child1, p[2], child2])
def p_empty_statement(p):
'''empty_statement : STATE_END '''
child1 = create_leaf("STATE_END", p[1])
p[0] = Node("empty_statement", [child1])
def p_return_statement(p):
'''return_statement : KWRD_RETURN expression_optional STATE_END '''
child1 = create_leaf("RETURN", p[1])
child2 = create_leaf("STATE_END", p[3])
p[0] = Node("return_statement", [child1, p[2], child2])
def p_constructor_arguement_list_opt(p):
'''constructor_arguement_list_opt : constructor_arguement_list
| empty '''
p[0] = Node("constructor_arguement_list_opt", [p[1]])
def p_constructor_arguement_list(p):
'''constructor_arguement_list : constructor_arguement_list_declarator
| constructor_arguement_list COMMA constructor_arguement_list_declarator'''
if len(p) == 2:
p[0] = Node("constructor_arguement_list", [p[1]])
else:
child1 = create_leaf("COMMA", p[2])
p[0] = Node("constructor_arguement_list", [p[1], child1, p[3]])
def p_constructor_arguement_list_declarator(p):
'''constructor_arguement_list_declarator : declaration_keyword IDENTIFIER COLON type'''
child1 = create_leaf("IDENTIFIER", p[2])
child2 = create_leaf("COLON", p[3])
p[0] = Node("constructor_arguement_list_declarator", [p[1], child1, child2, p[4]])
def p_func_arguement_list_opt(p):
'''func_arguement_list_opt : variable_declarators
| empty '''
p[0] = Node("func_arguement_list_opt", [p[1]])
def p_class_declaration(p):
'''class_declaration : class_header class_body'''
p[0] = Node("class_declaration", [p[1], p[2]])
def p_class_header(p):
'''class_header : class_header_name class_header_extends_opt'''
p[0] = Node("class_header", [p[1], p[2]])
def p_class_header_name(p):
'''class_header_name : class_header_name1 LPAREN constructor_arguement_list_opt RPAREN''' # class_header_name1 type_parameters
# | class_header_name1
child1 = create_leaf("LPAREN", p[2])
child2 = create_leaf("RPAREN", p[4])
p[0] = Node("class_header_name", [p[1], child1, p[3], child2])
def p_class_header_name1(p):
'''class_header_name1 : modifier_opts KWRD_CLASS name'''
child1 = create_leaf("CLASS", p[2])
p[0] = Node("class_header_name1", [p[1], child1, p[3]])
def p_class_header_extends_opt(p):
'''class_header_extends_opt : class_header_extends
| empty'''
p[0] = Node("class_header_extends_opt", [p[1]])
def p_class_header_extends(p):
'''class_header_extends : KWRD_EXTNDS name LPAREN func_arguement_list_opt RPAREN'''
child1 = create_leaf("EXTENDS", p[1])
child2 = create_leaf("LPAREN", p[3])
child3 = create_leaf("RPAREN", p[5])
p[0] = Node("class_header_extends", [child1, p[2], child2, p[4], child3])
def p_class_body(p):
'''class_body : block '''
p[0] = Node("class_body", [p[1]])
def p_method_declaration(p):
'''method_declaration : method_header method_body'''
p[0] = Node("method_declaration", [p[1], p[2]])
def p_method_header(p):
'''method_header : method_header_name LPAREN func_arguement_list_opt RPAREN COLON method_return_type ASSIGN'''
child1 = create_leaf("LPAREN", p[2])
child2 = create_leaf("RPAREN", p[4])
child3 = create_leaf("COLON", p[5])
child4 = create_leaf("ASSIGN", p[7])
p[0] = Node("method_header", [p[1], child1, p[3], child2, child3, p[6], child4])
def p_method_return_type(p):
'''method_return_type : type'''
p[0] = Node("method_return_type", [p[1]])
def p_method_return_type1(p):
'''method_return_type : TYPE_VOID'''
child1 = create_leaf("VOID", p[1])
p[0] = Node("method_return_type", [child1])
def p_method_header_name(p):
'''method_header_name : modifier_opts KWRD_DEF IDENTIFIER''' # class_header_name1 type_parameters
# | class_header_name1
child1 = create_leaf("DEF", p[2])
child2 = create_leaf("IDENTIFIER", p[3])
p[0] = Node("method_header_name", [p[1], child1, child2])
def p_method_body(p):
'''method_body : block '''
p[0] = Node("method_body", [p[1]])
def p_modifier(p):
'''modifier : KWRD_PROTECTED
| KWRD_PRIVATE'''
child1 = create_leaf("ModifierKeyword", p[1])
p[0] = Node("modifier", [child1])
def p_type(p):
'''type : primitive_type
| reference_type '''
p[0] = Node("type", [p[1]],p[1].dataType,p[1].value)
# p[0] = p[1]
def p_primitive_type(p):
'''primitive_type : TYPE_INT
| TYPE_FLOAT
| TYPE_CHAR
| TYPE_STRING
| TYPE_BOOLEAN'''
child1 = create_leaf("TYPE", p[1])
p[0] = Node("primitive_type", [child1],"Unit",p[1])
def p_reference_type(p):
'''reference_type : class_data_type
| array_data_type'''
p[0] = Node("reference_type", [p[1]],p[1].dataType,p[1].value)
def p_class_data_type(p):
'''class_data_type : name'''
p[0] = Node("class_data_type", [p[1]],"Unit","Object@"+p[1].value)
def p_array_data_type(p):
'''array_data_type : KWRD_ARRAY LBPAREN type RBPAREN'''
child1 = create_leaf("ARRAY", p[1])
child2 = create_leaf("LBPAREN", p[2])
child3 = create_leaf("RBPAREN", p[4])
p[0] = Node("array_data_type", [child1, child2, p[3], child3],"Unit","Array,"+p[3].value)
def p_array_initializer(p):
''' array_initializer : KWRD_NEW KWRD_ARRAY LBPAREN type RBPAREN LPAREN INT_CONST RPAREN
| KWRD_ARRAY LPAREN argument_list_opt RPAREN '''
if len(p) == 9:
child1 = create_leaf("NEW", p[1])
child2 = create_leaf("ARRAY", p[2])
child3 = create_leaf("LBPAREN", p[3])
child4 = create_leaf("RBPAREN", p[5])
child5 = create_leaf("LPAREN", p[6])
child6 = create_leaf("INT_CONST", p[7])
child7 = create_leaf("RPAREN", p[8])
p[0] = Node("array_initializer", [child1, child2, child3, p[4], child4, child5, child6, child7],"Array,"+p[4].value,None,int(p[7]))
else:
child1 = create_leaf("ARRAY", p[1])
child2 = create_leaf("LPAREN", p[2])
child3 = create_leaf("RPAREN", p[4])
currType=p[3].dataType[0]
print p[3].dataType
for i in range(1,len(p[3].dataType)):
if p[3].dataType[i] != currType:
print ("Type error: array can only be of same type")
assert(False)
p[0] = Node("array_initializer", [child1, child2, p[3], child3],"Array,"+currType,None,int(len(p[3].dataType)))
def p_class_initializer(p):
''' class_initializer : KWRD_NEW name LPAREN argument_list_opt RPAREN '''
child1 = create_leaf("NEW", p[1])
child2 = create_leaf("LPAREN", p[3])
child3 = create_leaf("RPAREN", p[5])
p[0] = Node("class_initializer", [child1, p[2], child2, p[4], child3],"Object@"+p[2].value)
# print statement
# def p_printstatement_1(p):
# "print_st : IDENTIFIER LPAREN IDENTIFIER RPAREN "
# try:
# print(names[p[3]])
# except LookupError:
# print("Undefined name '%s'" % p[3])
def p_empty(p):
'empty :'
child1 = create_leaf("Empty", "NOP")
p[0] = Node("empty", [child1])
pass
<file_sep>/asgn2/Makefile
all:
cp src/lexerP1.py bin/lexer.py
cp src/parser.py bin/parser.py
cp src/scalalex.py bin/scalalex.py
python -m py_compile bin/lexer.py
python -m py_compile bin/parser.py
mv bin/lexer.pyc bin/lexer
mv bin/parser.pyc bin/parser
chmod -R 777 bin/
clean:
rm -rf bin/*
rm test1.dot
| 80f2e5db2bad8710432e40b7634808a1185f8e7f | [
"Markdown",
"Python",
"Makefile"
]
| 16 | Python | sid17/CompilersProject | 2c8ad090a008c72042ff536804e2b48c9d51f50b | dd324a111bc0d916fb8b99dab87eea390b5da508 |
refs/heads/master | <file_sep>
import moe.reinwd.taxi.model.Region;
import moe.reinwd.taxi.model.Taxi;
import java.io.*;
import java.text.ParseException;
import java.util.*;
public class LocalTest {
public static void main(String[] args) throws IOException, ParseException {
File file = new File("./data/taxi_gps.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String s ;
List<Taxi> list = new ArrayList<>();
Set<Taxi> set = new HashSet<>();
while ((s = reader.readLine())!=null) {
Taxi fromStr = Taxi.createFromStr(s);
list.add(fromStr);
set.add(fromStr);
}
HashMap<Integer, Integer> countMap = new HashMap<>();
list.stream().forEach(taxi -> {
Integer integer = countMap.get(taxi.getIndex());
if (integer !=null){
countMap.put(taxi.getIndex(),integer+1);
}else countMap.put(taxi.getIndex(),1);
});
System.out.println();
}
static class RegionTest{
public static void main(String[] args) throws IOException, ParseException {
File file = new File("./data/taxi_gps.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String s ;
List<Taxi> list = new ArrayList<>();
Set<Taxi> set = new LinkedHashSet<>();
while ((s = reader.readLine())!=null) {
Taxi fromStr = Taxi.createFromStr(s);
list.add(fromStr);
set.add(fromStr);
}
File regionFile = new File("./data/district.txt");
reader = new BufferedReader(new FileReader(regionFile));
List<Region> regions = new ArrayList<>();
while ((s = reader.readLine())!=null) {
regions.add(Region.createFromStr(s));
}
regions.forEach(region -> {
int i = 0;
Set<Integer> quchong = new HashSet<>();
for (Taxi t :
list) {
if (!quchong.contains(t.getIndex())){
if (region.isInRegion(t.getPositon())){
i++;
}}
quchong.add(t.getIndex());
}
System.out.println(region.getName()+" "+i);
});
System.out.println();
set.forEach(taxi -> {
// System.out.println(taxi.getTime());
});
}
}
}
<file_sep>package moe.reinwd.taxi.util;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* @author ReinWD 张巍 2016214874
* @e-mail <EMAIL>
*/
public class ConcurrentUtil {
private static List<ExecutorService> registeredExecutorList = new LinkedList<>();
private static List<StopListener> stopListenerList = new LinkedList<>();
public static ExecutorService getExecutor(String name, ExecutorType type){
return getExecutor(name,type,null);
}
public static ExecutorService getExecutor(String name, ExecutorType type, StopListener stoplistener){
ExecutorService executorService = null;
if(type == null) return null;
switch (type){
case SINGLE_THREAD:
executorService = Executors.newSingleThreadExecutor(r -> new Thread(r, name));
break;
case CACHED:
executorService = Executors.newCachedThreadPool(r -> new Thread(r, name));
break;
case SCHEDULED:
executorService = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, name));
break;
}
if (executorService!= null)
registeredExecutorList.add(executorService);
if (stoplistener!=null)stopListenerList.add(stoplistener);
return executorService;
}
public static void registerExecutor(ExecutorService executor){
if (executor != null) registeredExecutorList.add(executor);
}
public static void stop(){
if (!registeredExecutorList.isEmpty()) registeredExecutorList.forEach(ExecutorService::shutdown);
if (!stopListenerList.isEmpty()) stopListenerList.forEach(StopListener::onStop);
}
public static void unRegister(ScheduledExecutorService executor) {
registeredExecutorList.remove(executor);
}
public enum ExecutorType {
SINGLE_THREAD, CACHED, SCHEDULED
}
private interface StopListener {
void onStop();
}
}
<file_sep>package moe.reinwd.taxi.model;
import java.io.Serializable;
/**
* @author ReinWD 张巍 2016214874
* @e-mail <EMAIL>
*/
public class LatLng implements Serializable {
private double lat;
private double lng;
LatLng (double lat, double lng){
this.lat = lat;
this.lng = lng;
}
public double getLat() {
return lat;
}
public double getLng() {
return lng;
}
}
<file_sep>package moe.reinwd.taxi.log;
import moe.reinwd.taxi.util.ConcurrentUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
/**
* @author ReinWD 张巍 2016214874
* @e-mail <EMAIL>
*/
public class Log {
public static final int DEBUG = 0;
public static final int INFO = 1;
public static final int WARN = 2;
public static final int ERROR = 3;
private static int logLevel;
private static BufferedWriter writer;
private static File logFile;
private static ExecutorService writerThread = ConcurrentUtil.getExecutor("LoggerThread", ConcurrentUtil.ExecutorType.SINGLE_THREAD);
static {
logFile = new File("./log");
if (!logFile.exists()) {
logFile.mkdir();
}
Date date = new Date();
String format = DateFormat.getDateInstance().format(date);
logFile = new File(logFile, format + ".log");
try {
writer = new BufferedWriter(new FileWriter(logFile,true));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setLogLevel(LogLevel logLevel) {
Log.logLevel = logLevel.level;
}
public static void d(String s) {
if (Log.logLevel <= 0) {
log(LogLevel.DEBUG, s);
}
}
private static void log(LogLevel level, String message) {
writerThread.submit(()->{
try {
synchronized (writer) {
writer.newLine();
Date date = new Date();
String format = DateFormat.getTimeInstance().format(date);
writer.write("[");
writer.write(format);
writer.write("] [");
writer.write(level.name());
writer.write("] ");
writer.write(message);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
public static void i(String s) {
if (Log.logLevel <= 1) {
log(LogLevel.INFO,s);
}
}
public static void w(String s) {
if (Log.logLevel <= 2) {
log(LogLevel.WARN,s);
}
}
public static void e(String s) {
if (Log.logLevel <= 3) {
log(LogLevel.ERROR,s);
}
}
enum LogLevel {
DEBUG(0), INFO(1), WARN(2), ERROR(3);
int level;
LogLevel(int i) {
this. level = i;
}
}
}
<file_sep># taxiAnalysis
2018-Cloud computing and big data course
## 描述
使用Spark & Hadoop 分析GPS数据的小程序
包括统计车辆数目与统计区域内车辆总数两块内容。
<file_sep>package moe.reinwd.taxi.model;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author ReinWD 张巍 2016214874
* @e-mail <EMAIL>
*/
public class Taxi implements Serializable {
private static SimpleDateFormat dateFormat;
private int index;
private TaxiEvent event;
private TaxiWorkingState workingState;
private Date time;
private LatLng latLng;
private int speed, towards;
private byte gpsState;
static {
dateFormat = (SimpleDateFormat) SimpleDateFormat.getInstance();
dateFormat.applyPattern("yyyyMMddhhmmss");
}
public static Taxi createFromStr(String str) throws ParseException {
return new Taxi(str);
}
private Taxi(String str) throws ParseException {
String[] split = str.split(",");
int i = 0;
index = Integer.parseInt(split[i++]);
event = TaxiEvent.get(split[i++]);
workingState = TaxiWorkingState.get(split[i++]);
time = dateFormat.parse(split[i++]);
double lng = Double.parseDouble(split[i++]);
double lat = Double.parseDouble(split[i++]);
latLng = new LatLng(lat, lng);
speed = Integer.parseInt(split[i++]);
towards = Integer.parseInt(split[i++]);
gpsState = Byte.parseByte(split[i]);
}
@Override
public boolean equals(Object obj) {
if (obj == null)return false;
if (obj instanceof Taxi){
return this.index == ((Taxi) obj).index;
}return false;
}
public int getIndex() {
return index;
}
@Override
public int hashCode() {
return index*13;
}
public LatLng getPositon() {
return this.latLng;
}
enum TaxiEvent{
TO_EMPTY(0), TO_WORKING(1), TO_PROTECTED(2),
OUT_PROTECTED(3), OTHERS(4);
private int event;
TaxiEvent(int i){
this.event = i;
}
public static TaxiEvent get(String s) {
int i = Integer.parseInt(s);
for (TaxiEvent e :
values()) {
if (e.event == i)return e;
}
throw new RuntimeException("event not exists.");
}
}
enum TaxiWorkingState{
EMPTY(0), WORKING(1), HALTING(2), STOPPED(3), OTHERS(4);
private int state;
TaxiWorkingState(int state){
this.state = state;
}
public static TaxiWorkingState get(String s) {
int i = Integer.parseInt(s);
for (TaxiWorkingState e :
values()) {
if (e.state == i)return e;
}
throw new RuntimeException("event not exists.");
}
}
}
<file_sep>package moe.reinwd.taxi.util;
import moe.reinwd.taxi.model.LatLng;
/**
* copied from https://blog.csdn.net/sanyuesan0000/article/details/51683464
* Created by yuliang on 2015/3/20.
* modified by ReinWD on 2018/11/19
*/
public class LocationUtils {
private static double EARTH_RADIUS = 6378.137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* 通过经纬度获取距离(单位:千米)
* @return
*/
public static double getDistance(LatLng latLng2, LatLng latLng1) {
double radLat1 = rad(latLng1.getLat());
double radLat2 = rad(latLng2.getLat());
double a = radLat1 - radLat2;
double b = rad(latLng1.getLng()) - rad(latLng2.getLng());
double s = 2 * Math.asin(
Math.sqrt(
Math.pow(Math.sin(a / 2), 2)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(b / 2), 2)
)
);
s = s * EARTH_RADIUS;
s = Math.round(s * 10000d) / 10000d;
// s = s*1000;
return s;
}
} | 5dbe986386694152e13bf61317d0c3f09b0940a5 | [
"Markdown",
"Java"
]
| 7 | Java | ReinWD/taxiAnalysis | 7911b1608595d3c5780a858b330485dc9afa9477 | 6edd56b531e72855c3c69a31cec5b007f28eab63 |
refs/heads/main | <file_sep>import CloseLegend from "../../pages/elements/closeLegend";
describe("Close legend on map", () => {
const closeLegend = new CloseLegend();
beforeEach(() => {
closeLegend.visit();
cy.wait(5000);
});
it("The legend icon is visible after the user closes legend on map", () => {
closeLegend
.getCloseButton()
.should("be.visible")
.eq(1)
.click({ force: true });
closeLegend.getLegendIcon().should("be.visible");
});
});
<file_sep>import ServiceTerritory from "../../pages/elements/serviceTerritory";
describe("GPC Service Territory in map legend", () => {
const serviceTerritory = new ServiceTerritory();
beforeEach(() => {
serviceTerritory.visit();
cy.wait(5000);
});
it("User can check and uncheck GPC Service Territory on map legend", () => {
if (serviceTerritory.getTerritoryCheckbox().should("be.checked")) {
serviceTerritory.getTerritoryCheckbox().click({ force: true });
} else {
}
});
});
<file_sep>class Search {
searchIcon = ".search";
addressInput = "#address-search";
addressList = ".listnav-component__listnavitem__text";
pinpoint =
'div[style*="32px; height: 32px; overflow: hidden; position: absolute; cursor: pointer; touch-action: none;"]*';
addressDetails = ".location-details";
constructor() {}
visit() {
return cy.visit("");
}
getSearchIcon() {
return cy.get(this.searchIcon);
}
getAddressInput() {
return cy.get(this.addressInput);
}
getAddressList() {
return cy.get(this.addressList);
}
getPinpoint() {
return cy.get(this.pinpoint);
}
getAddressDetails() {
return cy.get(this.addressDetails);
}
}
export default Search;
<file_sep>class County {
viewByLocation = ".main-button";
selectionMenu = ".menu-item";
county = "#map";
countyInfo = ".infobox-card--header";
constructor() {}
visit() {
return cy.visit("");
}
getViewByLocation() {
return cy.get(this.viewByLocation);
}
getSelectionMenu() {
return cy.get(this.selectionMenu);
}
getCounty() {
return cy.get(this.county).eq(0);
}
getCountyInfo() {
return cy.get(this.countyInfo);
}
}
export default County;
<file_sep>**How to run test specs in Cypress runner and view mochawesome report:**
1. Run command `npm install` in the terminal (this only needs to be run one time to install the node_module files).
2. After install completes, run command `cd cypresse2e` in the terminal to change the folder directory to the cypresse2e folder.
3. Run command `node_modules/.bin/cypress open` in the terminal to open the Cypress test runner.
4. In the Cypress test runner, click on a test spec to run it or click run all test specs to run all sequentially.
5. To generate the mochaawesome report you can run `npm run report` after the test completes. You can chain the two commands together in your CI job.
**How to run test specs in terminal/headless:**
1. Run command `npm run test` in terminal and all specs will execute.
---
## Heres some ref doc for cypress:
Example: config can be passed in through command line, or you can setup multiple cypress.json config files
`https://docs.cypress.io/guides/references/configuration.html#Command-Line`
`https://docs.cypress.io/guides/guides/launching-browsers.html#Chrome-Browsers`
---
Example: yaml run setup for CI pipeline
`https://docs.cypress.io/guides/guides/cross-browser-testing.html#Parallelize-per-browser`
You will need to have firefox and edge installed on your computer to run tests in these browsers.
<file_sep>import MenuSummary from "../../pages/elements/menuSummary";
import inputValues from "../../fixtures/inputValues.json";
describe("View summary report in menu", () => {
const menuSummary = new MenuSummary();
beforeEach(() => {
menuSummary.visit();
cy.wait(5000);
});
it("User can view summary report after typing in a location", () => {
button(menuSummary.getMenuIcon(), 0);
button(menuSummary.getSummaryButton(), 0);
button(menuSummary.getViewZipcode(), 1);
cy.wait(2000);
menuSummary
.getRefineInput()
.click({ force: true })
.type(inputValues.zipcode)
.focus()
.blur();
reportData(0, inputValues.zipAndCity);
reportData(1, inputValues.customersAffected);
reportData(2, inputValues.customersServed);
menuSummary.getPanelFooter().contains("updated every 10 min");
});
function button(getMethod, index) {
getMethod.eq(index).should("be.visible").click({ force: true });
}
function reportData(index, data) {
menuSummary.getDataPanel().eq(index).contains(data);
}
});
<file_sep>class Outages {
cluster =
'div[style*="width: 40px; height: 40px; overflow: hidden; position: absolute; cursor: pointer; touch-action: none;"]*';
outages = ".infobox-card--point-icon";
constructor() {}
visit() {
return cy.visit("");
}
getCluster() {
return cy.get(this.cluster);
}
getOutages() {
return cy.get(this.outages);
}
}
export default Outages;
<file_sep>import Search from "../../pages/elements/searchAddress";
import inputValues from "../../fixtures/inputValues.json";
describe("Search an address on the map", () => {
const search = new Search();
beforeEach(() => {
search.visit();
cy.wait(5000);
});
it("User can type and search for address on map", () => {
icon(search.getSearchIcon());
search
.getAddressInput()
.click({ force: true })
.type(inputValues.searchAddress);
search
.getAddressList()
.contains(inputValues.addressResult)
.click({ force: true });
cy.wait(3000);
icon(search.getPinpoint());
search.getAddressDetails().should("contain", inputValues.addressDetails);
});
function icon(getMethod) {
getMethod.should("be.visible").click({ force: true });
}
});
<file_sep>class MenuSummary {
menuIcon = ".tabs div";
summaryButton = ".tools-card .menu-tool .head";
viewZipcode = ".content .summary-tools div a";
refineInput = ".filter-group .filter-search-input input";
dataPanel = ".report-content .ReactVirtualized__Table__rowColumn";
panelFooter = ".report-summary .last-updated";
constructor() {}
visit() {
return cy.visit("");
}
getMenuIcon() {
return cy.get(this.menuIcon);
}
getSummaryButton() {
return cy.get(this.summaryButton);
}
getViewZipcode() {
return cy.get(this.viewZipcode);
}
getRefineInput() {
return cy.get(this.refineInput);
}
getDataPanel() {
return cy.get(this.dataPanel);
}
getPanelFooter() {
return cy.get(this.panelFooter);
}
}
export default MenuSummary;
| 37455ea74ab263509ddf2a4c6184338644dab085 | [
"JavaScript",
"Markdown"
]
| 9 | JavaScript | jessica-lau/outage-map | cbc2f2ae30759a8295681851f993f107c8770e8e | 8347771f4be4db55fb514e69ea891e72e481d910 |
refs/heads/master | <repo_name>DamianLew23/AkademiaSpring-KSB2-PracaDomowa3<file_sep>/src/test/java/pl/akademiaspring/ksb2pracadomowa3/KursSpringBoot2PracaDomowa3ApplicationTests.java
package pl.akademiaspring.ksb2pracadomowa3;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class KursSpringBoot2PracaDomowa3ApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>/src/main/java/pl/akademiaspring/ksb2pracadomowa3/service/CarService.java
package pl.akademiaspring.ksb2pracadomowa3.service;
import org.springframework.stereotype.Service;
import pl.akademiaspring.ksb2pracadomowa3.model.Car;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
@Service
public class CarService {
private List<Car> carList = new ArrayList<>();
CarService() {
carList.add(new Car(1L,"Volvo", "S60", "Black"));
carList.add(new Car(2L,"Peugeot", "406", "White"));
carList.add(new Car(3L,"Audi", "Q7", "Blue"));
}
public List<Car> getCars() {
return this.carList;
}
public Car getCarById(long id) {
return carList
.stream()
.filter(x -> (x.getId() == id))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Nie znaleziono samochodu o ID: " + id));
}
public List<Car> getCarsByColor(String color) {
return carList
.stream()
.filter(car -> car.getColor().equals(color))
.collect(Collectors.toList());
}
public boolean addCar(Car car) {
return carList.add(car);
}
public boolean modCar(Car car) {
Car carFromList = carList
.stream()
.filter(x -> (x.getId() == car.getId()))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Nie znaleziono samochodu o ID: " + car.getId()));
carList.remove(carFromList);
return carList.add(car);
}
public boolean patchCar(Car car) {
Car carFromList = carList
.stream()
.filter(x -> (x.getId() == car.getId()))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Nie znaleziono samochodu o ID: " + car.getId()));
if(car.getMark() != null)
carFromList.setMark(car.getMark());
if(car.getModel() != null)
carFromList.setModel(car.getModel());
if(car.getColor() != null)
carFromList.setColor(car.getColor());
return true;
}
public boolean removeCar(long id) {
Car carFromList = carList
.stream()
.filter(car -> (car.getId() == id))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Nie znaleziono samochodu o ID: " + id));
return carList.remove(carFromList);
}
}
<file_sep>/src/main/java/pl/akademiaspring/ksb2pracadomowa3/KursSpringBoot2PracaDomowa3Application.java
package pl.akademiaspring.ksb2pracadomowa3;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KursSpringBoot2PracaDomowa3Application {
public static void main(String[] args) {
SpringApplication.run(KursSpringBoot2PracaDomowa3Application.class, args);
}
}
| b32fa9910c82287da31ef2b446062aa32ad3cee5 | [
"Java"
]
| 3 | Java | DamianLew23/AkademiaSpring-KSB2-PracaDomowa3 | 127082c2f587bd31661f3ebfb93449305900da12 | 2f2dd2c878c681c6b49b01e70ac11201170f4f82 |
refs/heads/master | <repo_name>matthewkling/vortex<file_sep>/code/hurricane.r
# This script downloads raw hurricane data and converts it into tidy county format,
# first performing some spatial interpolation and deriving an exposure index.
# Input: raw NOAA hurricane data, hurdat2-1851-2015-021716.txt, automatically downloaded when script is run
# Output: tidy county-wise hurricane exposure, hurricane.csv
# Author: <NAME>
library(data.table)
library(dplyr)
library(tidyr)
library(stringr)
library(raster)
library(rgeos)
library(rgdal)
library(broom)
library(maptools)
library(ggplot2)
library(viridis)
download.file("http://www.nhc.noaa.gov/data/hurdat/hurdat2-1851-2015-021716.txt",
"raw_data/hurricane/hurdat2-1851-2015-021716.txt")
# read text file line-wise
d <- readLines("raw_data/hurricane/hurdat2-1851-2015-021716.txt")
# transform raw hurricane data into an R-readable csv format
commas <- c()
for(i in 1:length(d)){
if(length(gregexpr(",", d[i])[[1]]) == 3){ # lines with only 3 commas are storm headers
id <- paste0(substr(d[i], 1,8), ", ") # get the sorm id tag
commas <- c(commas, i)
next()
}
d[i] <- paste0(id, d[i]) # add the tag to every entry for that storm
}
d <- d[setdiff(1:length(d), commas)] # remove the storm header lines
writeLines(d, "raw_data/hurricane/hurricanes_tabular.csv") # save intermediate file
# clean up tabular data
d <- fread("raw_data/hurricane/hurricanes_tabular.csv", header=F) %>%
mutate(id=V1,
date=V2,
time=str_pad(V3, 4, "left", 0),
lat=as.numeric(substr(V6,1,4)), lat_dir=substr(V6, 5,5),
lon=as.numeric(substr(V7,1,4)) * -1, lon_dir=substr(V7, 5,5),
windspeed=as.numeric(V8)) %>%
filter(lat_dir=="N", lon_dir=="W") %>%
dplyr::select(id:windspeed)%>%
filter(windspeed > 0) %>%
mutate(datetime = as.POSIXct(paste(date, time), format="%Y%m%d %H")) %>%
arrange(datetime)
# load counties shapefile
counties <- readOGR("raw_data/census/us_counties_shapefile", "cb_2014_us_county_500k")
bbox <- extent(-126, -59, 22, 53)
counties <- crop(counties, bbox) # crop to US48
counties$area <- gArea(counties, byid=T) # calculate area per county
# crop to buffer around US extent, to avoid unnecessary computation
e <- extent(counties) * 1.1
coordinates(d) <- c("lon", "lat")
d <- crop(d, e)
d <- as.data.frame(d)
# interpolation -- linear interpolation of coordinates and windspeeds at hourly timesteps
ds <- split(d, d$id)
ds <- lapply(ds, function(x){
writeLines(as.character(x$id[1]))
dd <- data.frame()
if(nrow(x)<2) return(x)
for(i in 2:nrow(x)){
di <- x[(i-1):i,]
if(di$id[1]!=di$id[2]) next()
tdiff <- as.integer(difftime(x$datetime[2], x$datetime[1], units="hours"))
dd <- rbind(dd, di[1,])
for(h in 1:(tdiff-1)){
new <- di[1,]
weights <- c(tdiff-h, h)
weights <- weights / sum(weights)
new$datetime <- new$datetime + 3600 * h
new$lat <- weighted.mean(di$lat, weights)
new$lon <- weighted.mean(di$lon, weights)
new$windspeed <- weighted.mean(di$windspeed, weights)
dd <- rbind(dd, new)
}
}
return(dd)
})
d <- do.call("rbind", ds)
# crop to us extent
coordinates(d) <- c("lon", "lat")
crs(d) <- crs(counties)
d <- crop(d, extent(counties))
# tabulate weather events per county and join to shapefile data
s <- d %>%
over(counties) %>%
cbind(d@data) %>%
group_by(GEOID) %>%
summarize(n_storms=n(),
total_intensity=sum(windspeed^3),
intensity_per_area=total_intensity/sum(area)) %>%
left_join(counties@data, .) %>%
mutate(state_fips=STATEFP, county_fips=COUNTYFP) %>%
dplyr::select(n_storms:county_fips)
# fill NA values with minimum valid value
na2min <- function(x){
x[is.na(x) | x<0] <- min(na.omit(x[x>=0]))
return(x)
}
s$total_intensity <- na2min(s$total_intensity)
s$intensity_per_area <- na2min(s$intensity_per_area)
# export final tidy data
write.csv(s, "output/tidy_county_data/hurricane.csv", row.names=F)
<file_sep>/exploratory/raster_to_counties_demo.R
# this script demonstrates how to summarize raster data by county
# set working directory to your local vortex folder
setwd("~/documents/vortex")
library(raster)
library(rgdal)
library(rgeos)
library(stringr)
library(dplyr)
# load US counties shapefile
counties <- readOGR("raw_data/census/us_counties_shapefile", "cb_2014_us_county_500k")
counties <- crop(counties, extent(-126, -59, 22, 53)) # crop to US48
counties$area <- gArea(counties, byid=T) # calculate area per county
# load some raster data... using mean temp as an example
d <- getData('worldclim', var='bio', res=5)
d <- d[[1]]
# sync projections
counties <- spTransform(counties, crs(d))
d <- crop(d, counties)
# convert raster to points
d <- as.data.frame(rasterToPoints(d))
coordinates(d) <- c("x", "y")
crs(d) <- crs(counties)
# spatial join
o <- over(d, counties)
d <- o %>%
mutate(value = d$bio1) %>%
group_by(GEOID) %>%
summarize(value=mean(value))
counties@data <- left_join(counties@data, d)
# plot a map
variable <- "value" # the variable you want to map
values <- counties@data[,variable]
colors <- colorRampPalette(c("darkblue", "darkmagenta", "red", "yellow"))(100)[cut(values, breaks=100)]
colors[is.na(colors)] <- "darkblue" # what color to use for counties with no data -- set this to NA if you want them to be white
plot(counties, col=colors, axes=F, border=F)
<file_sep>/exploratory/organizing data Census API.R
#problem with this is that it's only 2008-2012
library(acs)
library(sqldf)
library(ggplot2)
library(maps)
library(tigris)
library(stringr) # to pad fips codes
#Request your own key easily through census.gov
#api.key.install(key="yourkeyhere")
#states = geo.make(state="*")
# load the boundary data for all counties
county.df=map_data("county")
# rename fields for later merge
names(county.df)[5:6]=c("state","county")
state.df=map_data("state")
# wow! a single geo.set to hold all the counties...?
us.county=geo.make(state="*", county="*")
income<-acs.fetch(endyear = 2012, span = 5, geography = us.county,
table.number = "B19001", col.names = "pretty")
acs.lookup(keyword="race")
#
# 17 C02003_002 C02003 Detailed Race
# 18 C02003_003 C02003 Detailed Race
# 19 C02003_004 C02003 Detailed Race
# 20 C02003_005 C02003 Detailed Race
# 21 C02003_006 C02003 Detailed Race
race<- acs.fetch(endyear = 2012, span = 5, geography = us.county,
table.number = "C02003", col.names = "pretty")
income_df <- data.frame(paste0(str_pad(income@geography$state, 2, "left", pad="0"),
str_pad(income@geography$county, 3, "left", pad="0")),
income@estimate[,c("Household Income: Total:",
"Household Income: $200,000 or more")],
stringsAsFactors = FALSE)
rownames(income_df)<-1:nrow(income_df)
names(income_df)<-c("GEOID", "total", "over_200")
income_df$percent <- 100*(income_df$over_200/income_df$total)
#tigris
counties <- c(5, 47, 61, 81, 85)
income_merged<- geo_join(county.df, income_df, "GEOID", "GEOID")
# there are some tracts with no land that we should exclude
income_merged <- income_merged[income_merged$ALAND>0,]
race_df <- data.frame(paste0(str_pad(race@geography$state, 2, "left", pad="0"),
str_pad(race@geography$county, 3, "left", pad="0")),
race@estimate[,c("Detailed Race: Total:",
"Detailed Race: Population of one race: White", "Detailed Race: Population of one race: Black or African American")], stringsAsFactors = FALSE)
<file_sep>/shiny/app1/ui.R
shinyUI(navbarPage(strong("DEMOGRAPHICS of DISASTER"),
windowTitle="Demographics of Disaster",
tabPanel("about",
imageOutput("katrina"),
hr(),
includeMarkdown("text/intro.md"),
hr(),
fluidRow(
column(2, tags$a(class="btn btn-default",
href="https://github.com/matthewkling/vortex",
"View GitHub repository")),
column(2, downloadButton('report', 'Download the report'))
),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
br(),
imageOutput("workflow")
),
tabPanel("explore correlations",
fluidRow(
column(4,
h2(htmlOutput("title1"), align="left")
),
column(2,
selectInput("xv", "X & Y variables", choices=vars$display,
selected=vars$display[grepl("black", vars$display)][1]),
selectInput("yv", NULL, choices=vars$display,
selected=vars$display[grepl("hurricane", vars$display)][1])
),
column(2,
selectInput("xscale", "X & Y scale transformations", choices=c("linear", "log10", "percentile"), selected="percentile"),
selectInput("yscale", NULL, choices=c("linear", "log10", "percentile"), selected="percentile")
),
column(2,
selectInput("smoother", "Smoother & color palette", choices=c("none", "lm", "loess", "gam"), selected="lm"),
selectInput("palette", NULL, choices=c("inferno", "dayglo", "alfalfa", "proton"))#,
#checkboxInput("transpose_palette", label="transpose", value=F)
#checkboxInput("se", label="show confidence interval", value=F)
),
column(2,
selectInput("region", "Region", choices=c("USA", na.omit(unique(as.character(e$STNAME))))),
downloadButton("download_correlation_plot", label="Download plot")
)
),
hr(),
fluidRow(
column(5,plotOutput("scatterplot", height="600px")),
column(7,plotOutput("map"), height="600px")
),
br(),
hr(),
includeMarkdown("text/explore_correlations.md")
),
tabPanel("compare groups",
fluidRow(
column(4,
h2(htmlOutput("title2"), align="left")
),
column(2,
selectInput("histogram_region", "Region", choices=c("USA", na.omit(unique(as.character(e$STNAME))))),
downloadButton("download_histogram", label="Download plot")
),
column(2,
selectInput("groups", "Select social groups", choices=na.omit(vars$group[vars$group!=""]),
selected=na.omit(vars$group[vars$group!=""])[c(3,4)], multiple=T, selectize=T)
),
column(2,
selectInput("envvar", "Select environmental variable", choices=vars$display[vars$category=="risk"],
selected=vars$display[vars$category=="risk"][1], multiple=F, selectize=T)
),
column(2,
selectInput("scale", "Scale transformation", choices=c("linear", "log10"), selected="log10")
)
),
hr(),
fluidRow(
plotOutput("histogram", height="650px")
),
br(),
hr(),
includeMarkdown("text/compare_groups.md")
)
))<file_sep>/Makefile
PHONY.: download_clean_data masterdatafile cleanedtables
all: output/master_county_data/master_county_data.csv output/master_county_data/cleanedsocial.csv output/master_county_data/cleanedrisk.csv
download_clean_data:
Rscript code/natamen.R
Rscript code/TrimmingCensusRaceData.R
Rscript code/hurricane.r
Rscript code/tornado_wind_hail.R
Rscript code/unemployment_clean.R
Rscript code/income_clean.R
Rscript code/poverty_clean.R
masterdatafile: code/join_tidy_county_data.R
Rscript code/join_tidy_county_data.R
cleanedtables: code/CleanMasterForAnalysis.R
Rscript code/CleanMasterForAnalysis.R
<file_sep>/raw_data/fire/README.txt
This data was downloaded from http://www.fs.usda.gov/rds/archive/Product/RDS-2015-0046. Within "data products" (RDS-2015-0046.zip),
the folder of interest is in Data/whp_2014_classified
Methods for generating the data can be found here: http://www.firelab.org/sites/default/files/images/downloads/wfp_methods_041813.pdf
Fire risk codes represent the following risk categories:
1. Very Low
2. Low
3. Moderate
4. High
5. Very High
6. Non-burnable land
7. Water
In the analysis, the variable of interest is % of county that's either in Risk Category 4 or 5
<file_sep>/code/natamen.R
#data obtained from http://www.ers.usda.gov/datafiles/Natural_Amenities_Scale/natamenf_1_.xls
#setwd("vortex") #code will not run appropriately from another directory
library(data.table)
library(rio)
library(xlsx)
download.file("http://www.ers.usda.gov/datafiles/Natural_Amenities_Scale/natamenf_1_.xls","raw_data/natural_amenities/natamenf.xls",method="curl")
nat.raw <- read.xlsx("raw_data/natural_amenities/natamenf.xls",1)
write.csv(nat.raw,"raw_data/natural_amenities/natamenf.csv", row.names = F)
natamen <- read.csv("raw_data/natural_amenities/natamenf.csv", skip=83) #removes comments and descriptions from the beginning of the data
names(natamen)[1] <- "state_county_fips" #changes column name
write.csv(natamen,"raw_data/natural_amenities/natamenf_fips.csv")
natamen_raw <- read.csv(("raw_data/natural_amenities/natamenf_fips.csv"));natamen_raw <- natamen_raw[,-1]
natamen.clean <- subset(natamen_raw,select=c(state_county_fips,Scale))
write.csv(natamen.clean,"output/tidy_county_data/natural_amenities.csv",row.names = F)
<file_sep>/exploratory/county_map_demo.R
# this script demonstrates how to make a quick map of any county-wise data
# set working directory to your local vortex folder
setwd("~/documents/vortex")
library(raster)
library(rgdal)
library(rgeos)
library(stringr)
library(dplyr)
# load US counties shapefile
counties <- readOGR("raw_data/census/us_counties_shapefile", "cb_2014_us_county_500k")
counties <- crop(counties, extent(-126, -59, 22, 53)) # crop to US48
counties$area <- gArea(counties, byid=T) # calculate area per county
# load csv of county data, and pad the fips codes with zeroes so they match the expected format
d <- read.csv("output/tidy_county_data/tornado.csv", stringsAsFactors=F)
d$state_fips <- str_pad(d$state_fips, 2, "left", 0)
d$county_fips <- str_pad(d$county_fips, 3, "left", 0)
# add the county data to the county shapefile
counties@data <- left_join(counties@data, d,
by=c("STATEFP"="state_fips", # the second argument here should be the name of your state fips variable
"COUNTYFP"="county_fips")) # same for county
# plot a map
variable <- "n_storms" # the variable you want to map
values <- counties@data[,variable] / counties$area
values <- log10(values) # i'm using a log transformation here due to the tornado frequency distribution
colors <- colorRampPalette(c("darkblue", "darkmagenta", "red", "yellow"))(100)[cut(values, breaks=100)]
colors[is.na(colors)] <- "darkblue" # what color to use for counties with no data -- set this to NA if you want them to be white
plot(counties, col=colors, axes=F, border=F)
<file_sep>/raw_data/poverty_unemployment_med_income/README.txt
Unemployment data were downloaded from http://www.ers.usda.gov/dataFiles/CountyLevelDatasets/Unemployment.xls
Poverty data were downloaded from http://www.ers.usda.gov/dataFiles/CountyLevelDatasets/PovertyEstimates.xls
Per-capita income were downloaded from http://www.bea.gov/newsreleases/regional/lapi/2015/xls/lapi1115.xls
Table with state names/abbreviations downloaded from http://www2.census.gov/geo/docs/reference/state.txt
Table with all county fips downloaded from http://www2.census.gov/geo/docs/reference/codes/files/national_county.txt
Unemployment and poverty data were downloaded from USDA Economic Research Service; several datasets available at http://www.ers.usda.gov/data-products/county-level-data-sets/download-data.aspx
Documentation for data at http://www.ers.usda.gov/data-products/county-level-data-sets/documentation.aspx
Poverty estimates were obtained from U.S. Census Bureau's Small Area Income and Poverty Estimate (SAIPE) program, and unemployment and median household income came from the Bureau of Labor Statistics (BLS) Local Area Unemployment Statistics (LAUS) program. More details on data documentation site.
Income data were obtained from US Bureau of Economic Analysis, news release here http://www.bea.gov/newsreleases/regional/lapi/lapi_newsrelease.htm
Full release in PDF form found here: http://www.bea.gov/newsreleases/regional/lapi/2015/pdf/lapi1115.pdf
Note: this dataset presented significant formatting challenges:
- Counties were not listed with state name or FIPS; state had to be matched to each county entry
- State/county combinations were matched to a table of states/counties and associated FIPS
- Virginia has an unusual way of coding cities and counties, and this dataset has merged several municipalies then lists them as "larger municipality + smaller municipalitie(s)". All had to be separated in order for the county/state name to be matched to FIPS.<file_sep>/shiny/app1/server.R
library(plyr)
library(markdown)
library(devtools)
library(maps)
library(mapproj)
library(ggplot2)
library(grid)
library(gridExtra)
library(gridBase)
library(dplyr)
library(tidyr)
library(stringr)
library(mgcv)
if(!require(colormap)) install_github("matthewkling/colormap", "colormap")
select <- dplyr::select
shinyServer(
function(input, output) {
### intro tab content ###
output$katrina <- renderImage({
dims <- c(1919, 558)
scale = .7
list(src = "www/Katrina_Storm.jpg",
contentType = 'image/jpg',
width = dims[1]*scale,
height = dims[2]*scale,
alt = "<NAME>")
}, deleteFile = F)
output$workflow <- renderImage({
dims <- c(960,540)
scale = 1.3
list(src = "www/workflow_diagram.png",
contentType = 'image/png',
width = dims[1]*scale,
height = dims[2]*scale,
alt = "Project workflow diagram")
}, deleteFile = F)
output$report <- downloadHandler(
filename="demographics_of_disaster.pdf",
content=function(file){
file.copy("www/demographics-disaster.pdf", file)
}
)
### explore correlations tab content ###
output$title1 <- renderUI({
HTML(paste(paste(capfirst(beforeparens(input$yv)), "vs."),
capfirst(beforeparens(input$xv)),
switch(input$region,
"USA"="in the United States",
paste("in", input$region)),
sep="<br/>"))
})
d <- reactive({
# isolate data specific to user-selected variables
d <- data.frame(fips=e$fips,
#state_fips=e$state_fips,
#county_fips=e$county_fips,
state=e$STNAME,
pop=e$TOTPOP,
x=e[,d2r(input$xv)],
y=e[,d2r(input$yv)])
# subset to selected state
if(input$region != "USA") d <- filter(d, state %in% input$region)
d <- mutate(d,
xlog=log10(x), ylog=log10(y),
xpercentile=ecdf(x)(x), ypercentile=ecdf(y)(y))
# approximate log-destroyed values
d$xlog[d$xlog==-Inf] <- min(d$xlog[is.finite(d$xlog)])
d$ylog[d$ylog==-Inf] <- min(d$ylog[is.finite(d$ylog)])
# get 2D color values
colvars <- c(switch(input$xscale, "linear"="x", "log10"="xlog", "percentile"="xpercentile"),
switch(input$yscale, "linear"="y", "log10"="ylog", "percentile"="ypercentile"))
goodrows <- apply(d[,colvars], 1, function(x) all(is.finite(x)))
palette <- switch(input$palette,
inferno=c("yellow", "red", "black", "blue", "white"),
dayglo=c("yellow", "green", "dodgerblue", "magenta", "white"),
alfalfa=c("darkgreen", "dodgerblue", "gray95", "yellow", "white"),
proton=c("cyan", "black", "gray95", "magenta", "white"))
#if(input$transpose_palette) palette[c(2,4)] <- palette[c(4,2)]
d$color[goodrows] <- colors2d(na.omit(d[goodrows,colvars]), palette[1:4])
d$color[is.na(d$color)] <- palette[5]
return(d)
})
scatterplot <- reactive({
d <- d()
# set point size and transparency should vary by number of counties
alpha <- switch(input$region, "USA"=.6, .8)
size <- switch(input$region, "USA"=6, 20)
# x axis label and data transformation
xlab <- input$xv
if(input$xscale=="percentile"){
d$x <- d$xpercentile
xlab <- paste0(xlab, ": percentile")
}
xlab <- paste0(xlab, "\n(point size proportional to county population)")
# y axis label and data transformation
ylab <- input$yv
if(input$yscale=="percentile"){
d$y <- d$ypercentile
ylab <- paste0(ylab, ": percentile")
}
# plot
p <- ggplot(d, aes(x, y, alpha=pop)) +
geom_point(size = scales::rescale(log(d$pop)) * size,
fill=d$color, color=NA,
alpha=alpha, shape=21) +
theme_minimal() +
theme(text=element_text(size=20)) +
labs(x=xlab, y=ylab)
# apply smoothers and variable transformations
if(input$smoother %in% c("lm", "loess")) p <- p + geom_smooth(color="black", se=input$se, method=input$smoother)
if(input$smoother=="gam") p <- p + geom_smooth(color="black", se=input$se, method="gam", formula = y ~ s(x))
if(input$yscale=="log10") p <- p + scale_y_log10()
if(input$xscale=="log10") p <- p + scale_x_log10()
return(p)
})
output$scatterplot <- renderPlot({ plot(scatterplot()) })
output$map <- renderPlot({
region <- tolower(input$region)
if(input$region=="USA") region <- "."
map("county", regions=region, fill=TRUE, col=d()$color,
resolution = 0, lty = 0, projection = "polyconic",
myborder = 0, mar = c(0,0,0,0))
map("state", regions=region, col = "white", fill = FALSE, add = TRUE,
lty = 1, lwd = 1, projection = "polyconic",
myborder = 0, mar = c(0,0,0,0))
}, height=600)
output$download_correlation_plot <- downloadHandler(
filename = function() { paste0(beforeparens(input$yv), "_vs_", beforeparens(input$xv), ".png") },
content = function(file) {
png(file, width=1200, height=600)
vp.scatter <- viewport(height=unit(1, "npc"), width=unit(0.45, "npc"),
just=c("left","top"),
y=1, x=0)
vp.map <- viewport(height=unit(1, "npc"), width=unit(0.55, "npc"),
just=c("left","top"),
y=1, x=0.45)
pushViewport(vp.map)
grid.rect()
par(plt = gridPLT(), new=TRUE)
region <- tolower(input$region)
if(input$region=="USA") region <- "."
map("county", regions=region, fill=TRUE, col=d()$color,
resolution = 0, lty = 0, projection = "polyconic",
myborder = 0, mar = c(0,0,0,0))
map("state", regions=region, col = "white", fill = FALSE, add = TRUE,
lty = 1, lwd = 1, projection = "polyconic",
myborder = 0, mar = c(0,0,0,0))
popViewport(1)
plot(scatterplot(), vp=vp.scatter)
dev.off()
})
### compare groups tab content ###
output$title2 <- renderUI({
HTML(paste(capfirst(beforeparens(input$envvar)),
"exposure comparison",
switch(input$histogram_region,
"USA"="for the United States",
paste("for", input$histogram_region)),
sep="<br/>"))
})
g <- reactive({
s <- data.frame(e[,g2r(input$groups)])
s <- as.data.frame(as.matrix(s) * e$TOTPOP)
if(ncol(s)==1) names(s) <- g2r(input$groups)
names(s) <- input$groups
v <- e[,d2r(input$envvar)]
if(class(v)=="factor") v <- as.character(v)
v <- as.numeric(v)
g <- data.frame(state=as.character(e$STNAME)) %>%
cbind(v) %>%
cbind(s) %>%
tidyr::gather(group, pop, -v, -state) %>%
dplyr::group_by(group) %>%
mutate(prop_pop = pop / sum(na.omit(pop)),
group=factor(group)) %>%
na.omit()
if(input$histogram_region != "USA") g <- filter(g, state==input$histogram_region)
return(g)
})
m <- reactive({
m <- group_by(g(), group) %>% dplyr::summarize(wmean = weighted.mean(v, pop))
m
})
histogram <- reactive({
p <- ggplot() +
geom_area(data=g(),
aes(v, ..density.., weight=prop_pop, color=factor(group), fill=factor(group)),
alpha=.15, size=.5, bins=15, position="identity", stat="bin") +
geom_vline(data=m(), aes(xintercept=wmean, color=factor(group)), size=1.5) +
theme_minimal() +
theme(axis.text.y=element_blank(),
text=element_text(size=20),
legend.position="top") +
labs(x=input$envvar,
y="\nrelative proportion of group",
color="group", fill="group")
if(input$scale=="log10") p <- p + scale_x_log10()
p
})
output$histogram <- renderPlot({ plot(histogram()) })
output$download_histogram <- downloadHandler(
filename = function() { paste0(beforeparens(input$envvar), ".png") },
content = function(file) {
png(file, width=800, height=600)
plot(histogram() +
labs(title=paste(capfirst(beforeparens(input$envvar)),
"exposure comparison",
switch(input$histogram_region,
"USA"="for the United States",
paste("for", input$histogram_region)))))
dev.off()
})
}
)<file_sep>/code/CleanMasterForAnalysis.R
# This script distills and organizes the "master county" dataset (which includes every variable from every source dataset),
# producing a table of data for inclusion in the shiny app. It also scales and combines risk variables to create an overall
# risk index. It exports two copies of each file, one to the shiny app data folder and one to the primary data output folder.
# load input data
master_county_data <- read.csv('output/master_county_data/master_county_data.csv')
#dangerous dropping of NAs
#master_county_data <-na.omit(master_county_data)
#### ENVIRONMENTAL RISK DATA ####
riskdata <- master_county_data[,c('state_fips',
'county_fips',
'CensusRace...STNAME',
'CensusRace...CTYNAME',
'land_area',
'hail...total_intensity',
'tornado...total_intensity',
'hurricane...total_intensity',
'wind...total_intensity'
)]
riskdata$highfirerisk <- master_county_data$Fire_risk_2014...risk_4+master_county_data$Fire_risk_2014...risk_5
# Rename columns to avoid spaces
colnames(riskdata)[colnames(riskdata)=='CensusRace...STNAME'] <- 'STNAME'
colnames(riskdata)[colnames(riskdata)=='CensusRace...CTYNAME'] <- 'CTYNAME'
colnames(riskdata)[colnames(riskdata)=='hail...total_intensity'] <- 'hail_tot_intensity'
colnames(riskdata)[colnames(riskdata)=='tornado...total_intensity'] <- 'tornado_tot_intensity'
colnames(riskdata)[colnames(riskdata)=='hurricane...total_intensity'] <- 'hurricane_tot_intensity'
colnames(riskdata)[colnames(riskdata)=='wind...total_intensity'] <- 'wind_tot_intensity'
#write.csv(riskdata, 'output/master_county_data/riskraw.csv', row.names=FALSE)
# Standardize all risk variables
#names(risk)
riskdata$hail_scaled <- scale(riskdata$hail_tot_intensity) # default for scale is substract mean, divide by sd
riskdata$tornado_scaled <- scale(riskdata$tornado_tot_intensity)
riskdata$wind_scaled <- scale(riskdata$wind_tot_intensity)
riskdata$hurricane_scaled <- scale(riskdata$hurricane_tot_intensity)
riskdata$fire_scaled <- scale(riskdata$highfirerisk)
# Create cumulative risk index
riskdata$risk_ind_sum <- (riskdata$hail_scaled + riskdata$tornado_scaled +
riskdata$wind_scaled + riskdata$fire_scaled +
riskdata$hurricane_scaled)
write.csv(riskdata, 'output/master_county_data/cleanedrisk.csv', row.names = FALSE)
write.csv(riskdata, 'shiny/app1/data/cleanedrisk.csv', row.names = FALSE)
#### SOCIOECONOMIC DATA ####
socialdata<- master_county_data[,c('state_fips',
'county_fips',
'CensusRace...STNAME',
'CensusRace...CTYNAME',
'land_area',
'natural_amenities...Scale',
'CensusRace...TOT_POP',
'CensusRace...H',
'poverty_2014...PCTPOVALL_2014', 'incomelower48...Dollars',
'unemployed_2014...Unemployment_rate_2014',
'unemployed_2014...Median_Household_Income_2014')]
colnames(socialdata)[colnames(socialdata)=='CensusRace...STNAME'] <- 'STNAME'
colnames(socialdata)[colnames(socialdata)=='CensusRace...CTYNAME'] <- 'CTYNAME'
colnames(socialdata)[colnames(socialdata)=='natural_amenities...Scale'] <- 'Natural_Amenities'
colnames(socialdata)[colnames(socialdata)=='CensusRace...TOT_POP'] <- 'TOTPOP'
colnames(socialdata)[colnames(socialdata)=='CensusRace...H'] <- 'CensusRace_H'
colnames(socialdata)[colnames(socialdata)=='poverty_2014...PCTPOVALL_2014'] <- 'PCTPOVALL_2014'
colnames(socialdata)[colnames(socialdata)=='incomelower48...Dollars'] <- 'Income_Dollars'
colnames(socialdata)[colnames(socialdata)=='unemployed_2014...Unemployed_rate_2014'] <- 'UnemplyRate'
colnames(socialdata)[colnames(socialdata)=='unemployed_2014...Median_Household_Income_2014'] <- 'MedianHouseholdIncome_UE'
socialdata$PercMino<- (master_county_data$CensusRace...TOT_POP - master_county_data$CensusRace...WA)/master_county_data$CensusRace...TOT_POP
socialdata$PercHisp<- master_county_data$CensusRace...H/master_county_data$CensusRace...TOT_POP
socialdata$PercBlk<- master_county_data$CensusRace...BA/master_county_data$CensusRace...TOT_POP
socialdata$PercWh<- master_county_data$CensusRace...WA/master_county_data$CensusRace...TOT_POP
socialdata$PercAs<- master_county_data$CensusRace...AA/master_county_data$CensusRace...TOT_POP
socialdata$PercPIHI<- master_county_data$CensusRace...Na/master_county_data$CensusRace...TOT_POP
socialdata$PercAI<- master_county_data$CensusRace...IA/master_county_data$CensusRace...TOT_POP
socialdata$PercNHW<- master_county_data$CensusRace...NHW/master_county_data$CensusRace...TOT_POP
write.csv(socialdata, 'output/master_county_data/cleanedsocial.csv', row.names=FALSE)
write.csv(socialdata, 'shiny/app1/data/cleanedsocial.csv', row.names=FALSE)
<file_sep>/raw_data/tornado_wind_hail/README.md
# Tornado, wind & hail data
These data come from NOAA's storm prediction center severe weather database:
http://www.spc.noaa.gov/wcm/
Each of the three datasets is automatically downloaded via a dedicated link:
- Tornado: http://www.spc.noaa.gov/wcm/data/Actual_tornadoes.csv
- Hail: http://www.spc.noaa.gov/wcm/data/1955-2015_hail.csv.zip
- Wind: http://www.spc.noaa.gov/wcm/data/1955-2015_wind.csv.zip
The three files share a common format, which is described in the metadata:
http://www.spc.noaa.gov/wcm/data/SPC_severe_database_description.pdf<file_sep>/code/raster_to_counties_FIRE_2014.R
## THIS SCRIPT CHANGES FIRE DATA FROM RASTER LEVEL TO COUNTY LEVEL
library(raster)
library(rgdal)
library(rgeos)
library(stringr)
library(dplyr)
# load US counties shapefile
counties <- readOGR("raw_data/census/us_counties_shapefile", "cb_2014_us_county_500k")
head(counties@data)
counties <- crop(counties, extent(-126, -59, 22, 53)) # crop to US48 using lat long, extent creates a box
extent(counties) # shows you boundaries of counties in lat long
counties$area <- gArea(counties, byid=T) # calculate area per county
setwd("raw_data/fire/whp_2014_classified/")
r <- raster("whp2014_cls")
# sync projections
counties <- spTransform(counties, crs(r)) #better to change counties because transforming a grid degrades the data
# the below for loop breaks apart the computation into states to make it manageable
States <- data.frame()
State.names <- unique(counties$STATEFP)
for(i in State.names[1:49]) {
State <- counties[counties$STATEFP==i,]
rState <- crop(r, State)
rState <- as.data.frame(rasterToPoints(rState))
coordinates(rState) <- c("x", "y")
crs(rState) <- crs(State)
o <- over(rState, State)
d <- o %>%
mutate(value = rState$whp2014_cls) %>%
group_by(GEOID) %>%
summarize(mean_risk = mean(value),
max_risk = max(value),
risk_1 = length(value[value==1])/length(value),
risk_2 = length(value[value==2])/length(value),
risk_3 = length(value[value==3])/length(value),
risk_4 = length(value[value==4])/length(value),
risk_5 = length(value[value==5])/length(value),
risk_6 = length(value[value==6])/length(value),
risk_7 = length(value[value==7])/length(value))
State@data <- left_join(State@data, d)
States <- rbind(States, State@data)
}
names(States)[1] <- "state_fips"
names(States)[2] <- "county_fips"
Fire_Risk_by_County <- States
setwd("~/vortex/")
write.csv(Fire_Risk_by_County, "output/tidy_county_data/Fire_risk_2014.csv", row.names=F)<file_sep>/code/join_tidy_county_data.R
# This script merges the tidy county tables from all the source datasets.
# Inputs: All csv files in the "tidy_county_data" folder
# Output: "master_county_data.csv"
# Author: <NAME>
library(dplyr)
library(stringr)
library(rgdal)
library(raster)
library(rgeos)
#load data
files <- list.files('output/tidy_county_data', full.names=T)
tables <- lapply(files, read.csv, stringsAsFactors=F)
# build a combined state_county_fips variable in tables that lack it
tables <- lapply(tables, function(x){
if(!'state_county_fips' %in% names(x)){
x$state_county_fips <- paste0(str_pad(x$state_fips, 2, 'left', 0), str_pad(x$county_fips, 3, 'left', 0))
}else{
x$state_county_fips <- str_pad(x$state_county_fips, 5, 'left', 0)
}
return(x)
})
# add dataset-specific tag to dataset-specific variable names to avoid name conflicts
for(i in 1:length(tables)) names(tables[[i]])[!grepl('_fips', names(tables[[i]]))] <-
paste0(gsub('.csv', '', basename(files[i])), '...', names(tables[[i]])[!grepl('_fips', names(tables[[i]]))])
# merge datasets
master <- Reduce(full_join, tables)
# add county land area to table
counties <- readOGR('raw_data/census/us_counties_shapefile', 'cb_2014_us_county_500k')
counties <- crop(counties, extent(-126, -59, 22, 53)) # crop to US48
counties <- data.frame(state_county_fips=counties$GEOID,
land_area=gArea(counties, byid=T))
master <- left_join(master, counties)
# export csv
write.csv(master, 'output/master_county_data/master_county_data.csv', row.names=F)
<file_sep>/code/poverty_clean.R
#data obtained from http://www.ers.usda.gov/dataFiles/CountyLevelDatasets/PovertyEstimates.xls
#setwd("vortex") #code will not run appropriately from another directory
library(rio)
download.file("http://www.ers.usda.gov/dataFiles/CountyLevelDatasets/PovertyEstimates.xls","raw_data/poverty_unemployment_med_income/PovertyEstimates.xls",method="curl")
pov.raw <- import("raw_data/poverty_unemployment_med_income/PovertyEstimates.xls")
pov <- pov.raw[-(1:(which(pov.raw[,1]=="FIPStxt")-1)),] #remove the rows above the column names, held comments from original excel file
colnames(pov) <- pov[which(pov[,1]=="FIPStxt"),] #adds rownames
if (which(pov$FIPStxt=="FIPStxt")!=0){pov <- pov[-which(pov$FIPStxt=="FIPStxt"),]} #if the names are still in a row, removes.
pov <- pov[-which(is.na(pov$Rural_urban_Continuum_Code_2003)),] #removes data for just states and misc census areas (leaves only counties)
if (which(names(pov)=="FIPStxt")!=0){names(pov)[which(names(pov)=="FIPStxt")] <- "state_county_fips"} #changes FIPS code column
#selecting desired data
categories <- c(
"state_county_fips",
"POVALL_2014",
"PCTPOVALL_2014"
)
pov.clean.2014 <- pov[,categories]
write.csv(pov.clean.2014,"output/tidy_county_data/poverty_2014.csv",row.names=F) #writes out cleaned data
<file_sep>/exploratory/fips.table.R
#Creates table containing state/county names and fips, so files with only some attributes can be converted.
#State data from http://www2.census.gov/geo/docs/reference/state.txt
#County data from http://www2.census.gov/geo/docs/reference/codes/files/national_county.txt (info/GUI here https://www.census.gov/geo/reference/codes/cou.html)
state <- read.table("state.txt",sep="|",header=T,colClasses = "character")
state.abbrv <- subset(state,select = c(STUSAB,STATE_NAME) )
county <- read.csv("fips.csv",colClasses = "character",header=F)
names(county) <- c("STUSAB","state_fips","county_fips","county_name_full","fips_class")
fips.table <- merge(state.abbrv,county,by="STUSAB")
fips.table$state_county_fips <- paste(fips.table$state_fips,fips.table$county_fips,sep="")
#remove non-states
discard.terr <- which(fips.table$STATE_NAME=="American Samoa"|fips.table$STATE_NAME=="Guam"|fips.table$STATE_NAME=="Northern Mariana Islands"|fips.table$STATE_NAME=="Puerto Rico"|fips.table$STATE_NAME=="U.S. Minor Outlying Islands"|fips.table$STATE_NAME=="U.S. Virgin Islands")
fips.table <- fips.table[-discard.terr,]
fips.table$lc_county_names <- fips.table$county_name_full
fips.table$lc_county_names <- tolower(fips.table$lc_county_names)
fips.table$lc_county_names[which(fips.table$STATE_NAME!="Virginia")] <- gsub(" county","",fips.table$lc_county_names)[which(fips.table$STATE_NAME!="Virginia")] #removes county from names, except for Virginia because Virginia is so odd.
fips.table$lc_county_names <- gsub(" parish","",fips.table$lc_county_names) #removes parish from names
write.csv(fips.table,"fips.table.csv",row.names = F)
fips.table$lc_county_name <-
<file_sep>/raw_data/hurricane/README.md
# Hurricane data
These data come from NOAA's HURDAT2 database for the Atlantic region, and represent the tracks of every hurricane since 1851.
Data are automatically downloaded when the hurricane.r script is run. The direct download link for the dataset is http://www.nhc.noaa.gov/data/hurdat/hurdat2-1851-2015-021716.txt
Metadata can be found at http://www.nhc.noaa.gov/data/hurdat/hurdat2-format-atlantic.pdf
Starting from this raw file, our scripts:
1. restructure the data into a tidy tabular format
2. interpolate the raw 6-hour time steps to a one-hour frequency to better represent continuous storm paths
3. derive an index of destructive force by cubing maximum windspeed at each timestep (wind force is proportional to the cube of velocity)
4. sum the index values for all points falling in each US county
5. convert this final data into a standard format and save as a CSV<file_sep>/shiny/app1/text/compare_groups.md
This visualization shows how population demographics differ in their natural distaster exposure. Select an environmental variable and two or more groups to compare the means (vertical lines) and frequency distributions (area histograms) of exposure among populations. <file_sep>/shiny/app1/text/explore_correlations.md
These charts visualize bivariate relationships across space. Each point on the scatterplot corresponds to a county on the map. The scatterplot reveals the correlation between the selected variables, and also serves as a two-dimensional color legend for the map.
* To explore the demographics of disaster, choose a social variable for the X dimension and an environmental variable for the Y dimension (or investigate a totally different question by combining variables differently).
* To see a map of a single variable, choose it for both the X and Y dimensions.
* Many variables have skewed distributions -- choose linear, log, or percentile scale transformations to rescale the data.
* Three types of best-fit line are available, with counties weighted by population in these regressions.
* Use the other controls to play with colors, zoom into a single state, download your charts, and more!<file_sep>/code/tornado_wind_hail.R
# This script downloads tornado/hail/wind data from NOAA and converts it into tidy county format.
# Input: raw NOAA storms data and US counties shapefile
# Output: tidy county-wise exposure tables: tornado.csv, hail.csv, wind.csv
# Author: <NAME>
# libraries
library(dplyr)
library(rgdal)
library(raster)
library(rgeos)
library(ggplot2)
library(broom)
library(maptools)
library(viridis)
####### functions #######
# function to load storms data
# metadata is at http://www.spc.noaa.gov/wcm/data/SPC_severe_database_description.pdf
# column names are common to all weather types, but wind has an extra variable
load_data <- function(path){
d <- read.csv(path, header=F, stringsAsFactors=F)
varnames <- c("id", "year", "month", "day", "date", "time", "time_zone",
"state", "state_fips", "state_code", "intensity",
"injuries", "fatalities", "loss", "crop_loss",
"slat", "slon", "elat", "elon", "length", "width",
"num_states", "state_num", "segment",
paste0("county_fips_", 1:4))
if(grepl("wind", basename(path))) varnames <- c(varnames, "mag_type")
names(d) <- varnames
return(d)
}
# function to tabulate weather events per county
countify <- function(data){
require(stringr)
names(data)[is.na(names(data))] <- "a"
data <- data %>%
mutate(state_fips = str_pad(state_fips, 2, "left", "0"),
county_fips = str_pad(county_fips_1, 3, "left", "0")) %>%
group_by(state_fips, county_fips) %>%
dplyr::summarize(n_storms=n(),
total_intensity=sum(intensity))
data<- filter(data, county_fips != "000") #removing aggregate state and country rows
return(data)
}
# function to fill NA values with minimum valid value
na2min <- function(x){
x$n_storms[is.na(x$n_storms)] <- 0
x$total_intensity[is.na(x$total_intensity) | x$total_intensity<0] <- min(na.omit(x$total_intensity[x$total_intensity>=0]))
return(x)
}
# function to make shapefile from county data table
geojoin <- function(data, shapefile){
#shapefile@data <- mutate_each(shapefile@data, funs(as.integer), STATEFP, COUNTYFP)
shapefile@data <- left_join(shapefile@data, data, by=c("STATEFP"="state_fips", "COUNTYFP"="county_fips"))
return(shapefile)
}
# function to save some simple maps
make_map <- function(weather){
f <- d[[weather]]
s <- tidy(f, region="GEOID")
s <- left_join(s, f@data, by=c("id"="GEOID"))
png(paste0("output/charts/", weather, "_frequency_map.png"), width=3000, height=2000)
p <- ggplot(s, aes(long, lat, fill=n_storms/area, group=group, order=order)) +
geom_polygon(color=NA) +
scale_fill_viridis(option="A", na.value="black",
trans="log10", breaks=10^(0:10)) +
theme(panel.background=element_blank(), panel.grid=element_blank(),
axis.text=element_blank(), axis.title=element_blank(), axis.ticks=element_blank(),
legend.position="top", text=element_text(size=40)) +
coord_map("stereographic") +
guides(fill=guide_colourbar(barwidth=50, barheight=3)) +
labs(fill=paste(weather, "events per unit area "))
plot(p)
dev.off()
}
######## data setup #########
# download weather data
download.file("http://www.spc.noaa.gov/wcm/data/Actual_tornadoes.csv",
"raw_data/tornado_wind_hail/tornado_raw.csv")
download.file("http://www.spc.noaa.gov/wcm/data/1955-2015_wind.csv.zip",
"raw_data/tornado_wind_hail/wind_raw.zip")
download.file("http://www.spc.noaa.gov/wcm/data/1955-2015_hail.csv.zip",
"raw_data/tornado_wind_hail/hail_raw.zip")
unzip("raw_data/tornado_wind_hail/wind_raw.zip", exdir = "raw_data/tornado_wind_hail")
unzip("raw_data/tornado_wind_hail/hail_raw.zip", exdir = "raw_data/tornado_wind_hail")
# load weather event data
files <- list.files("raw_data/tornado_wind_hail", pattern="\\.csv", full.names=T)
names(files) <- c("hail", "wind", "tornado")
# load US counties shapefile
counties <- readOGR("raw_data/census/us_counties_shapefile", "cb_2014_us_county_500k")
counties <- crop(counties, extent(-126, -59, 22, 53)) # crop to US48
counties$area <- gArea(counties, byid=T) # calculate area per county
####### processing ##########
d <- lapply(files, load_data)
d <- lapply(d, countify)
d <- lapply(d, na2min)
for(w in names(d)) write.csv(d[[w]], paste0("output/tidy_county_data/", w, ".csv"), row.names=F)
#d <- lapply(d, geojoin, shapefile=counties)
#lapply(names(d), make_map)
<file_sep>/shiny/app1/text/intro.md
#### Welcome to Demographics of Disaster!
This tool is motivated by a simple question: *which US subpopulations are most burdened by climate-related natural disasters?* By combining a number of socioeconomic and meteorological datasets into a flexible visualization framework, the app lets you explore various facets of this issue. Click the tabs above to get started.
This app was created by a few UC Berkeley grad students as a class project for the [Data Sciences for the 21st Century](http://ds421.berkeley.edu) program, and is powered by [Shiny](http://shiny.rstudio.com). The project workflow is scripted and fully reproducible. For more details, check out our report or our GitHub repo below.<file_sep>/shiny/app1/global.r
# TODO
# normalize relevant risk variables by county area
library(dplyr)
library(tidyr)
library(maps)
library(mapproj)
library(stringr)
select <- dplyr::select
# load data
ds <- read.csv("data/cleanedsocial.csv", stringsAsFactors=F) %>%
mutate(fips = as.integer(paste0(state_fips, str_pad(county_fips, 3, "left", 0)))) %>%
select(-STNAME, -CTYNAME, -state_fips, -county_fips, -land_area, -Income_Dollars)
dr <- read.csv("data/cleanedrisk.csv", stringsAsFactors=F) %>%
#select(-land_area) %>%
mutate(state_fips=as.integer(state_fips),
county_fips=as.integer(county_fips)) %>%
mutate(fips = as.integer(paste0(state_fips, str_pad(county_fips, 3, "left", 0)))) %>%
select(-CTYNAME, -state_fips, -county_fips)
# fips-to-name dictionary from maps library;
FIPS <- maps::county.fips
FIPS$polyname <- as.character(FIPS$polyname)
FIPS$polyname[FIPS$polyname=="florida,miami-dade"] <- "florida,dade"
# a clean counties table with the proper number and order of counties for plotting
cty <- readRDS("data/counties.rds") %>%
mutate(polyname = name) %>%
select(polyname) %>%
left_join(., FIPS) %>%
mutate(ID=1:length(polyname))
#if(!all.equal(ds$fips, dr$fips)) stop("social and risk data are misaligned")
e <- cbind(dr, select(ds, -fips))
fill <- function(x) na.omit(x)[1]
e <- left_join(cty, e) %>%
group_by(ID) %>%
summarise_each(funs(fill)) %>%
ungroup() %>%
filter(!duplicated(ID))
#if(!all.equal(cty$fips, e$fips)) stop("incorrect county structure")
e <- as.data.frame(e)
# fill in some missing values -- this is a patch that should maybe be transferred to the data prep scripts
na2min <- function(x){
x[is.na(x) | x<0] <- min(na.omit(x[x>=0]))
return(x)
}
e <- mutate_each_(e, funs(na2min), names(e)[grepl("tot_intensity|risk_ind_sum", names(e))]) %>%
mutate(population_density = TOTPOP/land_area)
# variable names dictionary and translation functions
vars <- read.csv("data/variable_names", stringsAsFactors=F) %>%
filter(category != "other") %>%
arrange(desc(category), display)
r2d <- function(x) vars$display[match(x, vars$raw)]
d2r <- function(x) vars$raw[match(x, vars$display)]
g2r <- function(x) vars$raw[match(x, vars$group)]
# fake inputs for dev/debugging -- not used
input <- list(xv=vars$display[vars$category=="social"][1],
yv=vars$display[vars$category=="risk"][1],
xscale="linear",
yscale="linear",
smoother="none",
region="USA",
palette="inferno",
transpose_palette=F,
groups=na.omit(vars$group[vars$group!=""])[1:2],
envvar=vars$display[vars$category=="risk"][1],
scale="linear",
histogram_region="USA")
beforeparens <- function(x){
if(grepl("\\(", x)) return(substr(x, 1, regexpr("\\(", x)[1]-2))
return(x)}
capfirst <- function(x) paste0(toupper(substr(x,1,1)), substr(x,2,nchar(x)))
<file_sep>/code/income_clean.R
#data obtained from http://www.bea.gov/newsreleases/regional/lapi/2015/xls/lapi1115.xls
#setwd("vortex") #code will not run appropriately from another directory
library(rio) #used to import Excel files
#####Downloading data from sources####
download.file("http://www.bea.gov/newsreleases/regional/lapi/2015/xls/lapi1115.xls","raw_data/poverty_unemployment_med_income/lapi1115.xls",method="curl")
state<-import("http://www2.census.gov/geo/docs/reference/state.txt", format="|")
county<-import("https://www2.census.gov/geo/docs/reference/codes/files/national_county.txt", format=",")
####Make table of FIPS values####
state.abbrv <- subset(state,select = c(STUSAB,STATE_NAME) )
names(county) <- c("STUSAB","state_fips","county_fips","county_name_full","fips_class")
fips.table <- merge(state.abbrv,county,by="STUSAB")
fips.table$state_county_fips <- paste(fips.table$state_fips,fips.table$county_fips,sep="")
#remove non-states
discard.terr <- which(fips.table$STATE_NAME=="American Samoa"|fips.table$STATE_NAME=="Guam"|fips.table$STATE_NAME=="Northern Mariana Islands"|fips.table$STATE_NAME=="Puerto Rico"|fips.table$STATE_NAME=="U.S. Minor Outlying Islands"|fips.table$STATE_NAME=="U.S. Virgin Islands")
fips.table <- fips.table[-discard.terr,]
fips.table$lc_county_names <- fips.table$county_name_full
fips.table$lc_county_names <- tolower(fips.table$lc_county_names)
fips.table$lc_county_names[which(fips.table$STATE_NAME!="Virginia")] <- gsub(" county","",fips.table$lc_county_names)[which(fips.table$STATE_NAME!="Virginia")] #removes county from names, except for Virginia because Virginia is so odd.
fips.table$lc_county_names <- gsub(" parish","",fips.table$lc_county_names) #removes parish from names
fips.table <- fips.table[-which(fips.table$STUSAB == "DC"),]
per.cap.raw <- import("raw_data/poverty_unemployment_med_income/lapi1115.xls")
names(per.cap.raw) <- c("location","per.cap.2012","per.cap.2013","per.cap.2014","state.rank.per.cap.2014","percent.2013","percent.2014","state.rank.percent.2014")
####Initial reading, cleaning####
per.cap.raw <- per.cap.raw[-which(is.na(per.cap.raw$per.cap.2012)|is.na(per.cap.raw$location)),] #removes rows that don't have data, leaving only states/counties.
if("United States" %in% per.cap.raw$location){per.cap.raw <- per.cap.raw[-(1:which(per.cap.raw$location=="United States")),]} #removes United States line
#changing numeric columns to numeric
per.cap.raw[,"per.cap.2012"] <- as.numeric(per.cap.raw[,"per.cap.2012"])
per.cap.raw[,"per.cap.2013"] <- as.numeric(per.cap.raw[,"per.cap.2013"])
per.cap.raw[,"per.cap.2014"] <- as.numeric(per.cap.raw[,"per.cap.2014"])
per.cap.raw[,"state.rank.per.cap.2014"] <- as.numeric(per.cap.raw[,"state.rank.per.cap.2014"])
per.cap.raw[,"percent.2013"] <- as.numeric(per.cap.raw[,"percent.2013"])
per.cap.raw[,"percent.2014"] <- as.numeric(per.cap.raw[,"percent.2014"])
per.cap.raw[,"state.rank.percent.2014"] <- as.numeric(per.cap.raw[,"state.rank.percent.2014"])
####Adding state to the county rows####
per.cap.raw$STATE_NAME <- NA
state.rows <- which(is.na(per.cap.raw$state.rank.per.cap.2014)) #use if column weas convertic to numeric (NA inserted)
state.list <- per.cap.raw$location[state.rows]
st.begin <- state.rows; st.end <- c(state.rows[-1]-1,length(per.cap.raw$location))
state.range <- data.frame(st.begin,st.end) #ranges for each state's counties (all entries between states are from that state; they acted as headers in original document)
for (j in 1:length(state.list)) #using the row ranges for each state, labels counties accordingly.
{
per.cap.raw$STATE_NAME[state.range$st.begin[j]:state.range$st.end[j]] <- state.list[j]
}
####Removing specific errors, standardizing county names/capitalization####
per.cap.fix <- per.cap.raw #new DF, helps tracking for tracking errors if they occur
#States without systemic errors/spot-fixes
per.cap.fix$location <- gsub("ñ","n",per.cap.fix$location) #official FIPS table does not use the accents
per.cap.fix$location[which(per.cap.fix$location=="Petersburg Borough" & per.cap.fix$STATE_NAME=="Alaska")] <- "Petersburg Census Area" #Petersburg not technically a borough, not listed as such in official FIPS list.
per.cap.fix$location[which(per.cap.fix$location=="Fremont (includes Yellowstone National Park)" & per.cap.fix$STATE_NAME=="Idaho")] <- "Fremont" #removes note from county name
per.cap.fix$location[which(per.cap.fix$location=="Oglala Lakota" & per.cap.fix$STATE_NAME=="South Dakota")] <- "Shannon" #county name changed in May 2015 and has not been updated in FIPS database
#Entries (from Virginia) that do not have "city" in them, but should.
per.cap.fix$location[which(per.cap.fix$location=="Alexandria" & per.cap.fix$STATE_NAME == "Virginia")] <- "Alexandria city"
per.cap.fix$location[which(per.cap.fix$location=="Chesapeake" & per.cap.fix$STATE_NAME == "Virginia")] <- "Chesapeake city"
per.cap.fix$location[which(per.cap.fix$location=="Hampton" & per.cap.fix$STATE_NAME == "Virginia")] <- "Hampton city"
per.cap.fix$location[which(per.cap.fix$location=="Newport News" & per.cap.fix$STATE_NAME == "Virginia")] <- "Newport News city"
per.cap.fix$location[which(per.cap.fix$location=="Norfolk" & per.cap.fix$STATE_NAME == "Virginia")] <- "Norfolk city"
per.cap.fix$location[which(per.cap.fix$location=="Portsmouth" & per.cap.fix$STATE_NAME == "Virginia")] <- "Portsmouth city"
per.cap.fix$location[which(per.cap.fix$location=="Suffolk" & per.cap.fix$STATE_NAME == "Virginia")] <- "Suffolk city"
per.cap.fix$location[which(per.cap.fix$location=="Virginia Beach" & per.cap.fix$STATE_NAME == "Virginia")] <- "Virginia Beach city"
#Entries that have merged smaller municipalities with larger (mostly Virginia); easier and less opaque than using a pattern-based fix.
#Note from full release (http://www.bea.gov/newsreleases/regional/lapi/2015/pdf/lapi1115.pdf): Virginia combination areas consist of one or two independent cities with populations of less than 100,000 combined with an adjacent county. The county name appears first, followed by the city name(s). Separate estimates for the jurisdictions making up the combination areas are not available.
#merged.index <- grep("\\+", per.cap.fix$location) #pulls locations with " +" in location name
#merged <- per.cap.fix[merged.index,] #useful to see what locations are, base replacements on, makes altering names further down
separated <- as.data.frame(matrix(data = NA, nrow=0, ncol = 9)) #dataframe to put un-merged municipalities into
names(separated) <- names(per.cap.fix)
#Separating municipalities (mostly Virginia; this strategy used for tranparency/easier troubleshooting)
Maui = per.cap.fix[which(per.cap.fix$location=="Maui + Kalawao"),]; Maui$location <- "Maui"
Kalawao = per.cap.fix[which(per.cap.fix$location=="Maui + Kalawao"),]; Kalawao$location <- "Kalawao"
Albemarle = per.cap.fix[which(per.cap.fix$location=="Albemarle + Charlottesville"),]; Albemarle$location <- "Albemarle"
Charlottesville.city = per.cap.fix[which(per.cap.fix$location=="Albemarle + Charlottesville"),]; Charlottesville.city$location <- "Charlottesville city"
Alleghany = per.cap.fix[which(per.cap.fix$location=="Alleghany + Covington"),]; Alleghany$location <- "Alleghany"
Covington.city = per.cap.fix[which(per.cap.fix$location=="Alleghany + Covington"),]; Covington.city$location <- "Covington city"
Augusta = per.cap.fix[which(per.cap.fix$location=="Augusta, Staunton + Waynesboro"),]; Augusta$location <- "Augusta"
Staunton.city = per.cap.fix[which(per.cap.fix$location=="Augusta, Staunton + Waynesboro"),]; Staunton.city$location <- "Staunton city"
Waynesboro.city = per.cap.fix[which(per.cap.fix$location=="Augusta, Staunton + Waynesboro"),]; Waynesboro.city$location <- "Waynesboro city"
Campbell = per.cap.fix[which(per.cap.fix$location=="Campbell + Lynchburg"),]; Campbell$location <- "Campbell"
Lynchburg.city = per.cap.fix[which(per.cap.fix$location=="Campbell + Lynchburg"),]; Lynchburg.city$location <- "Lynchburg city"
Carroll = per.cap.fix[which(per.cap.fix$location=="Carroll + Galax"),]; Carroll$location <- "Carroll"
Galax.city = per.cap.fix[which(per.cap.fix$location=="Carroll + Galax"),]; Galax.city$location <- "Galax city"
Dinwiddie = per.cap.fix[which(per.cap.fix$location=="Dinwiddie, Colonial Heights + Petersburg"),]; Dinwiddie$location <- "Dinwiddie"
Colonial.Heights.city = per.cap.fix[which(per.cap.fix$location=="Dinwiddie, Colonial Heights + Petersburg"),]; Colonial.Heights.city$location <- "Colonial Heights city"
Petersburg.city = per.cap.fix[which(per.cap.fix$location=="Dinwiddie, Colonial Heights + Petersburg"),]; Petersburg.city$location <- "Petersburg city"
Fairfax = per.cap.fix[which(per.cap.fix$location=="Fairfax, Fairfax City + Falls Church"),]; Fairfax$location <- "Fairfax"
Fairfax.city = per.cap.fix[which(per.cap.fix$location=="Fairfax, Fairfax City + Falls Church"),]; Fairfax.city$location <- "Fairfax city"
Falls.Church.city = per.cap.fix[which(per.cap.fix$location=="Fairfax, Fairfax City + Falls Church"),]; Falls.Church.city$location <- "Falls Church city"
Frederick = per.cap.fix[which(per.cap.fix$location=="Frederick + Winchester"),]; Frederick$location <- "Frederick"
Winchester.city = per.cap.fix[which(per.cap.fix$location=="Frederick + Winchester"),]; Winchester.city$location <- "Winchester city"
Greensville = per.cap.fix[which(per.cap.fix$location=="Greensville + Emporia"),]; Greensville$location <- "Greensville"
Emporia.city = per.cap.fix[which(per.cap.fix$location=="Greensville + Emporia"),]; Emporia.city$location <- "Emporia city"
Henry = per.cap.fix[which(per.cap.fix$location=="Henry + Martinsville"),]; Henry$location <- "Henry"
Martinsville.city = per.cap.fix[which(per.cap.fix$location=="Henry + Martinsville"),]; Martinsville.city$location <- "Martinsville city"
James.City = per.cap.fix[which(per.cap.fix$location=="James City + Williamsburg"),]; James.City$location <- "James City"
Williamsburg.city = per.cap.fix[which(per.cap.fix$location=="James City + Williamsburg"),]; Williamsburg.city$location <- "Williamsburg city"
Montgomery = per.cap.fix[which(per.cap.fix$location=="Montgomery + Radford"),]; Montgomery$location <- "Montgomery"
Radford.city = per.cap.fix[which(per.cap.fix$location=="Montgomery + Radford"),]; Radford.city$location <- "Radford city"
Pittsylvania= per.cap.fix[which(per.cap.fix$location=="Pittsylvania + Danville"),]; Pittsylvania$location <- "Pittsylvania"
Danville.city = per.cap.fix[which(per.cap.fix$location=="Pittsylvania + Danville"),]; Danville.city$location <- "Danville city"
Prince.George = per.cap.fix[which(per.cap.fix$location=="<NAME> + Hopewell"),]; Prince.George$location <- "<NAME>"
Hopewell.city = per.cap.fix[which(per.cap.fix$location=="<NAME> + Hopewell"),]; Hopewell.city$location <- "Hopewell city"
Prince.William = per.cap.fix[which(per.cap.fix$location=="<NAME>, Manassas + Manassas Park"),]; Prince.William$location <- "<NAME>"
Manassas.city = per.cap.fix[which(per.cap.fix$location=="<NAME>, Manassas + Manassas Park"),]; Manassas.city$location <- "Manassas city"
Manassas.Park.city = per.cap.fix[which(per.cap.fix$location=="<NAME>, Manassas + Manassas Park"),]; Manassas.Park.city$location <- "Manassas Park city"
Roanoke.city = per.cap.fix[which(per.cap.fix$location=="Roanoke + Salem"),]; Roanoke.city$location <- "Roanoke city"
Salem.city = per.cap.fix[which(per.cap.fix$location=="Roanoke + Salem"),]; Salem.city$location <- "Salem city"
Rockbridge = per.cap.fix[which(per.cap.fix$location=="Rockbridge, Buena Vista + Lexington"),]; Rockbridge$location <- "Rockbridge"
Buena.Vista.city = per.cap.fix[which(per.cap.fix$location=="Rockbridge, Buena Vista + Lexington"),]; Buena.Vista.city$location <- "Buena Vista city"
Lexington.city = per.cap.fix[which(per.cap.fix$location=="Rockbridge, Buena Vista + Lexington"),]; Lexington.city$location <- "Lexington city"
Rockingham = per.cap.fix[which(per.cap.fix$location=="Rockingham + Harrisonburg"),]; Rockingham$location <- "Rockingham"
Harrisonburg.city = per.cap.fix[which(per.cap.fix$location=="Rockingham + Harrisonburg"),]; Harrisonburg.city$location <- "Harrisonburg city"
Southampton = per.cap.fix[which(per.cap.fix$location=="Southampton + Franklin"),]; Southampton$location <- "Southampton"
Franklin.city = per.cap.fix[which(per.cap.fix$location=="Southampton + Franklin"),]; Franklin.city$location <- "Franklin city"
Spotsylvania = per.cap.fix[which(per.cap.fix$location=="Spotsylvania + Fredericksburg"),]; Spotsylvania$location <- "Spotsylvania"
Fredericksburg.city = per.cap.fix[which(per.cap.fix$location=="Spotsylvania + Fredericksburg"),]; Fredericksburg.city$location <- "Fredericksburg city"
Washington = per.cap.fix[which(per.cap.fix$location=="Washington + Bristol"),]; Washington$location <- "Washington"
Bristol.city = per.cap.fix[which(per.cap.fix$location=="Washington + Bristol"),]; Bristol.city$location <- "Bristol city"
Wise = per.cap.fix[which(per.cap.fix$location=="Wise + Norton"),]; Wise$location <- "Wise"
Norton.city = per.cap.fix[which(per.cap.fix$location=="Wise + Norton"),]; Norton.city$location <- "Norton city"
York = per.cap.fix[which(per.cap.fix$location=="York + Poquoson"),]; York$location <- "York"
Poquoson.city = per.cap.fix[which(per.cap.fix$location=="York + Poquoson"),]; Poquoson.city$location <- "Poquoson city"
separated = rbind( #binds rows with fixed names
Maui,
Kalawao,
Albemarle,
Charlottesville.city,
Alleghany,
Covington.city,
Augusta,
Staunton.city,
Waynesboro.city,
Campbell,
Lynchburg.city,
Carroll,
Galax.city,
Dinwiddie,
Colonial.Heights.city,
Petersburg.city,
Fairfax,
Fairfax.city,
Falls.Church.city,
Frederick,
Winchester.city,
Greensville,
Emporia.city,
Henry,
Martinsville.city,
James.City, #for the record, it is "James City County". Because Virginia.
Williamsburg.city,
Montgomery,
Radford.city,
Pittsylvania,
Danville.city,
Prince.George,
Hopewell.city,
Prince.William,
Manassas.city,
Manassas.Park.city,
Roanoke.city,
Salem.city,
Rockbridge,
Buena.Vista.city,
Lexington.city,
Rockingham,
Harrisonburg.city,
Southampton,
Franklin.city,
Spotsylvania,
Fredericksburg.city,
Washington,
Bristol.city,
Wise,
Norton.city,
York,
Poquoson.city
)
per.cap.counties <- per.cap.fix[-which(is.na(per.cap.fix$state.rank.per.cap.2014)),] #removes state (and DC) entries from dataframe
if(("Albemarle" %in% per.cap.counties$location)==FALSE) {per.cap.counties <- rbind(per.cap.counties,separated)} #checks to make sure the separated counties haven't been added yet (admittedly arbitrary selection of county in VA, but one that doesn't share a name with any counties in other states.)
if(length(grep("\\+", per.cap.counties$location) != 0)) {per.cap.counties <- per.cap.counties[-grep("\\+", per.cap.counties$location),]} #removes the merged county names if they haven't been removed.
####Matching counties to FIPS table####
per.cap.counties$lc_county_names <- NA
per.cap.counties$lc_county_names <- tolower(per.cap.counties$location) #takes them to lowercase so they can be matched
fips.add <- merge(fips.table,per.cap.counties,by=c("STATE_NAME","lc_county_names"),all=T)
#check <- fips.add[which(is.na(fips.add$per.cap.2012)|is.na(fips.add$state_county_fips)),] #shows lines that have not merged appropriately; richmond/bedford virginia are both counties and cities, the cities not specifically mentioned in the per capita data.
####Pulling desired data####
categories <- c(
"state_county_fips",
"per.cap.2014"
)
#to match Valeri's original format, changing per.cap.2014 to Dollars
per.cap <- fips.add[,categories]
names(per.cap)[which(names(per.cap)=="per.cap.2014")] <- "Dollars"
write.csv(per.cap,"output/tidy_county_data/incomelower48.csv",row.names=F) #writes out cleaned data; preserved original cleaned file and columns name
<file_sep>/code/TrimmingCensusRaceData.R
######### Downloading and Cleaning the Demographic Data by county ###########
###### Data comes from Census Bureau Population Estimates from 2014 #########
#download data
download.file("https://www.census.gov/popest/data/counties/asrh/2014/files/CC-EST2014-ALLDATA.csv", "raw_data/census/CensusRaceEst/CC-EST2014-ALLDATA.csv", method="curl")
#read data
CC2014 <- read.csv("raw_data/census/CensusRaceEst/CC-EST2014-ALLDATA.csv")
# Adjust column names for consistency when compiling scripts via join_tidy_county_data.R
names(CC2014)[2:3]<-c("state_fips", "county_fips")
# To identify columns of interest: see names pdf in rawdata/census/CensusRaceEst directory #
#COLUMNS 1:20 -- Single races by male and female
#+
#COL57 H_MALE
#COL58 H_FEMALE
#COL33 NH_MALE
#COL34 NH_FEMALE
CC_AGE_SEX<-cbind(CC2014[,1:20], CC2014[,57:58], CC2014[,33:36])
# aggregate age data
# totals, select row where Age=0, and years 3-7 representing population estimates in July 2010-2014
CC_SEX<-subset(CC_AGE_SEX, AGEGRP == 0 & YEAR!=1 & YEAR!=2)
#rename table and aggregate sexes
CC<-CC_SEX
CC$WA<-CC$WA_MALE+CC$WA_FEMALE
CC$BA<-CC$BA_MALE+CC$BA_FEMALE
CC$IA<-CC$IA_MALE+CC$IA_FEMALE
CC$AA<-CC$AA_MALE+CC$AA_FEMALE
CC$Na<-CC$NA_MALE+CC$NA_FEMALE
CC$NH<-CC$NH_MALE+CC$NH_FEMALE
CC$H<-CC$H_MALE+CC$H_FEMALE
CC$NHW<-CC$NHWA_MALE+ CC$NHWA_FEMALE
#trim male female columns, adjust column names
CC<-cbind(CC[,2:6], CC[,8], CC[,27:34])
View(CC)
names(CC)[6]<-"TOT_POP"
View(CC)
#Split by Year into a list of lists for seperate tables!
CCbyYR<-split(CC,CC$YEAR)
summary(CCbyYR)
#Export each dataframe in CCbyYR to a csv
CC.df<- do.call("rbind", lapply(CCbyYR, as.data.frame))
#write.csv(CC.df, file = "CensusRace.csv")
# Here we write only year == 7 which reflects popolation estimates for July 2014.
write.csv(CC.df[CC.df$YEAR==7,], file = "output/tidy_county_data/CensusRace.csv", row.names=F)
<file_sep>/exploratory/README.md
### Exploratory files
These are ancillary files created during exploratory data analysis. They are not part of the primary project and can be ignored.<file_sep>/README.md
## Demographics of Disaster
This repository contains all the code and data associated with a group class project for [Stat 259](http://gastonsanchez.com/stat259), a UC Berkeley course associated with the [Data Sciences for the 21st Century](http://ds421.berkeley.edu) program.
Our final products include a [web app](https://matthewkling.shinyapps.io/demographics_of_disaster/) built with Shiny, and a report compiled with latex and overleaf and found inside the report directory.
The project was motivated by a simple question: *how are US subpopulations differentially burdened by climate-related natural disasters?* By combining a number of socioeconomic and meteorological datasets into a flexible visualization framework, the Shiny app lets you explore various facets of this issue.
Our pipeline is fully reproducible, and nearly every step is scripted, exceptions being the downloading of several source datasets only accessible via GUI.
To run all scripts and reproduce this project, first, clone the github repository onto your local machine. Then, visit the forest fire directory under raw data and follow instructions in the readme to download, prepare, and clean fire data. This will take roughly 6-8 hours. After this step completes, please run the make file in the main directory with the following script from a BASH or UNIX shell: 'make'
Note: You may need to install some dependencies and the following R libraries in order to execute the make command: rio, raster, data.table, viridis, dplyr, tidyr, stringr, rgeos, rgdal, broom, maptools, ggplot2, xlsx.
<file_sep>/exploratory/exposure_histograms.R
library(dplyr)
library(tidyr)
library(ggplot2)
select <- dplyr::select
setwd("~/documents/vortex")
# open master data table
f <- read.csv("output/master_county_data/master_county_data.csv")
###### race ######
# split data into race and non-race frames
race <- f[,grepl("Census|_fips", names(f))]
names(race) <- sub("CensusRace...", "", names(race))
d <- f[,!grepl("Census", names(f))]
# variables to visualize
variables <- names(d)[grepl("\\.\\.\\.", names(d))]
variables <- variables[!grepl("Fire_risk", variables) | grepl("\\.risk_", variables)] # drop fire metadata variables
# generate an exposure-by-race density plot for all variables
for(var in variables){
v <- d[,var]
if(class(v)=="factor") v <- as.character(v)
v <- as.numeric(v)
v <- cbind(race, v) %>%
select(v, state_county_fips, TOT_POP, WA:H) %>%
select(-NH, -Na) %>%
gather(race, pop, -v, -state_county_fips, -TOT_POP) %>%
group_by(race) %>%
mutate(prop_pop = pop / sum(na.omit(pop))) %>%
na.omit()
m <- summarize(v, wmean = weighted.mean(v, pop))
name <- sub("\\.\\.\\.", ": ", var)
colors <- c("darkgoldenrod1", "black", "red", "forestgreen", "dodgerblue")
p <- ggplot(v, aes(v, weight=prop_pop, color=factor(race), fill=factor(race))) +
geom_density(adjust=2, alpha=.2, size=.25) +
geom_vline(data=m, aes(xintercept=wmean, color=factor(race))) +
scale_fill_manual(values=colors) +
scale_color_manual(values=colors) +
theme_minimal() +
theme(axis.text.y=element_blank()) +
labs(x=name,
y="relative proportion of racial group",
title=name,
color="race", fill="race")
ggsave(paste0("output/charts/race_histograms/", var, ".png"), p, width=8, height=6)
# log scale
ggsave(paste0("output/charts/race_histograms/", var, "_log10.png"), p+scale_x_log10(), width=8, height=6)
}
##### poverty #####
d <- f
variables <- names(d)[grepl("\\.\\.\\.", names(d))]
variables <- variables[!grepl("poverty_pct", variables)]
variables <- variables[!grepl("Fire_risk", variables) | grepl("\\.risk_", variables)] # drop fire metadata variables
variables <- variables[!grepl("CensusRace", variables)]
pov <- select(d, poverty_pct_2014...PCTPOVALL_2014, CensusRace...TOT_POP)
names(pov) <- c("pov", "pop")
# generate an exposure-by-race density plot for all variables
for(var in variables){
v <- d[,var]
if(class(v)=="factor") v <- as.character(v)
v <- as.numeric(v)
v <- cbind(pov, v)
name <- sub("\\.\\.\\.", ": ", var)
colors <- c("darkgoldenrod1", "black", "red", "forestgreen", "dodgerblue")
p <- ggplot(v, aes(pov, v, weight=pop, alpha=pop)) +
geom_smooth(method=lm, color="darkred", fill="darkred") +
geom_point()+
theme_minimal() +
scale_alpha(trans="log10", range=c(0,1), breaks=10^c(0:10)) +
labs(y=name,
x="percent below poverty line",
title=name,
alpha="population")
ggsave(paste0("output/charts/poverty_scatterplots/", var, ".png"), p, width=8, height=6)
# log scale
ggsave(paste0("output/charts/poverty_scatterplots/", var, "_log10.png"),
p + scale_y_log10(),
width=8, height=6)
}
<file_sep>/code/unemployment_clean.R
#data obtained from http://www.ers.usda.gov/dataFiles/CountyLevelDatasets/Unemployment.xls
#setwd("vortex") #code will not run appropriately from another directory
library(rio)
download.file("http://www.ers.usda.gov/dataFiles/CountyLevelDatasets/Unemployment.xls","raw_data/poverty_unemployment_med_income/Unemployment.xls",method="curl")
unem.raw <- import("raw_data/poverty_unemployment_med_income/Unemployment.xls")
unem <- unem.raw[-(1:(which(unem.raw[,1]=="FIPS_Code")-1)),] #remove the rows above the column names, held comments from original excel file
colnames(unem) <- unem[which(unem[,1]=="FIPS_Code"),] #adds rownames
if (which(unem$FIPS_Code=="FIPS_Code")!=0){unem <- unem[-which(unem$FIPS_Code=="FIPS_Code"),]} #if the names are still in a row, removes.
unem <- unem[-which(is.na(unem$Rural_urban_continuum_code_2003)),] #removes data for just states and misc census areas (leaves only counties)
if (which(names(unem)=="FIPS_Code")!=0){names(unem)[which(names(unem)=="FIPS_Code")] <- "state_county_fips"} #changes FIPS code column
#selecting desired data
categories <- c(
"state_county_fips",
"Unemployed_2014",
"Unemployment_rate_2014",
"Median_Household_Income_2014" #had been removed, but was included from this file in master cleaning
)
unem.clean.2014 <- unem[,categories]
write.csv(unem.clean.2014,"output/tidy_county_data/unemployed_2014.csv",row.names=F) #writes out cleaned data
| 1068c9ddc98edb191ce8ac71b933084e4bf6d24d | [
"Makefile",
"Text",
"R",
"Markdown"
]
| 28 | R | matthewkling/vortex | 8c1ccd0ff4cd2b3f57f9c988d1b44d6787676a68 | a1d882e0bb76b78a3e7c199e25040afb7a39151d |
refs/heads/master | <repo_name>lgrandperrin/AlgorithmicLibrary<file_sep>/README.md
# AlgorithmicLibrary
[GitHub Link](https://github.com/lgrandperrin/AlgorithmicLibrary/)
These files are a library of algorithms in C language. You can find search algorithms, sorts of algorithms as well as binary trees.
<file_sep>/lib/array.c
#include "array.h"
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
void array_create(struct array *self) {
self->capacity = 0;
self->size = 0;
int *data = calloc(self->capacity, sizeof(int));
self->data = data;
}
void array_destroy(struct array *self) {
free(self->data);
}
bool array_equals(const struct array *self, const int *content, size_t size) {
if(self->size == size){
for(size_t i=0; i<size; ++i){
if(self->data[i] != content[i]){
return false;
}
}
return true;
}
return false;
}
void array_add(struct array *self, int value) {
if(self->capacity==self->size){
self->capacity +=2;
int *data = calloc(self->capacity, sizeof(int));
memcpy(data, self->data, self->size *sizeof(int));
free(self->data);
self->data=data;
}
self->data[self->size]=value;
self -> size +=1;
}
void array_insert(struct array *self, int value, size_t index) {
if(self->capacity==self->size){
self->capacity +=1;
int *data = calloc(self->capacity, sizeof(int));
memcpy(data, self->data, self->size *sizeof(int));
free(self->data);
self->data=data;
}
for (size_t i = self->size; i > index; --i) {
self->data[i] = self->data[i - 1];
}
self->data[index] = value;
self->size += 1;
}
void array_remove(struct array *self, size_t index) {
for (size_t i = index + 1; i < self->size; ++i) {
self->data[i - 1] = self->data[i];
}
self->size -= 1;
}
int *array_get(const struct array *self, size_t index) {
if(self->size == 0)
return NULL;
return &(self->data[index]);
}
bool array_is_empty(const struct array *self) {
if(self->size ==0)
return true;
return false;
}
size_t array_size(const struct array *self) {
return self->size;
}
size_t array_search(const struct array *self, int value) {
size_t i = 0;
while((i < self->size) && (self->data[i] != value)){
i++;
}
return i;
}
size_t array_search_sorted(const struct array *self, int value){
return array_binary_search(self, value, 0, self->size);
}
size_t array_binary_search(const struct array *self, int e, size_t bot, size_t top){
if (bot == top)
return self->size;
size_t mid = (bot + top) / 2;
if (e < self->data[mid])
return array_binary_search(self, e, bot, mid);
if (self->data[mid] < e)
return array_binary_search(self, e, mid + 1, top);
return mid;
}
void array_import(struct array *self, const int *other, size_t size) {
if(!array_is_empty(self)){
size_t i = array_size(self);
for(size_t j = 0; j<i; j++){
array_remove(self,j);
}
}
for(int i = 0; i<size; i++){
array_add(self,other[i]);
}
}
void array_dump(const struct array *self) {
for(size_t i = 0; i<self->size; i++){
printf("%d ", self -> data[i]);
}
}
bool array_is_sorted(const struct array *self) {
if(self->size ==0)
return true;
for (size_t i = 1; i < self->size; ++i){
if (self->data[i - 1] > self->data[i]){
return false;
}
}
return true;
}
void array_swap(struct array *self, size_t i, size_t j) {
int tmp = self->data[i];
self->data[i] = self->data[j];
self->data[j] = tmp;
}
void array_selection_sort(struct array *self) {
for (size_t i=0; i < self->size-1; ++i) {
size_t j = i;
for (size_t k=j+1; k<self->size; ++k) {
if (self->data[k]<self->data[j]) {
j=k;
}
}
array_swap(self, i, j);
}
}
void array_bubble_sort(struct array *self) {
for (size_t i=0; i<self->size-1; ++i) {
for (size_t j = self->size-1; j > i; --j) {
if (self->data[j] < self->data[j-1]) {
array_swap(self, j, j-1);
}
}
}
}
void array_insertion_sort(struct array *self) {
for (size_t i=1; i < self->size; ++i) {
int x=self->data[i];
size_t j=i;
while (j > 0 && self->data[j-1] > x) {
self->data[j] = self->data[j-1];
j--;
}
self->data[j]=x;
}
}
ssize_t array_partition(struct array *self, ssize_t i, ssize_t j) {
ssize_t pivot_index = i;
const int pivot = self->data[pivot_index];
array_swap(self, pivot_index, j);
ssize_t l = i;
for (ssize_t k = i; k < j; ++k) {
if (self->data[k] < pivot) {
array_swap(self, k, l);
l++;
}
}
array_swap(self, l, j);
return l;
}
void array_quick_sort_partial(struct array *self, ssize_t i, ssize_t j) {
if (i < j) {
ssize_t p = array_partition(self, i, j);
array_quick_sort_partial(self, i, p - 1);
array_quick_sort_partial(self, p + 1, j);
}
}
void array_quick_sort(struct array *self) {
array_quick_sort_partial(self, 0, self->size - 1);
}
void array_heap_sort(struct array *self) {
}
bool array_is_heap(const struct array *self) {
}
void array_heap_add(struct array *self, int value) {
}
int array_heap_top(const struct array *self) {
return 0;
}
void array_heap_remove_top(struct array *self) {
}
<file_sep>/lib/tree.c
#include "tree.h"
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <assert.h>
struct tree_node {
int value;
struct tree_node *left;
struct tree_node *right;
};
void tree_create(struct tree *self) {
assert(self);
self->root = NULL;
}
void tree_destroy(struct tree *self) {
}
bool tree_contains(const struct tree *self, int value) {
return false;
}
void tree_insert(struct tree *self, int value) {
}
void tree_remove(struct tree *self, int value) {
}
bool tree_is_empty(const struct tree *self) {
assert(self);
return (self -> root == NULL);
}
size_t tree_size(const struct tree *self) {
return 0;
}
size_t tree_height(const struct tree *self) {
return 0;
}
void tree_walk_pre_order(const struct tree *self, tree_func_t func, void *user_data) {
}
void tree_walk_in_order(const struct tree *self, tree_func_t func, void *user_data) {
}
void tree_walk_post_order(const struct tree *self, tree_func_t func, void *user_data) {
}
void tree_dump(const struct tree *self) {
}
<file_sep>/lib/list.c
#include "list.h"
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <assert.h>
struct list_node {
int value;
struct list_node *next;
// struct list_node *prev;
};
void list_create(struct list *self) {
assert(self);
self->first=NULL;
}
void list_destroy(struct list *self) {
while(!list_is_empty(self)){
struct list_node *element = self -> first;
self -> first = element -> next;
free(element);
}
}
bool list_equals(const struct list *self, const int *data, size_t size) {
struct list_node *tmp = self->first;
if(list_size(self) == size){
for(size_t i=0; i<size; ++i){
if(tmp->value != data[i]){
return false;
}
tmp = tmp ->next;
}
return true;
}
return false;
}
void list_add_back(struct list *self, int value) {
struct list_node *element = malloc(sizeof(*element));
if(element == NULL)
return;
element -> value = value;
element -> next = NULL;
if(list_is_empty(self)==1)
self ->first = element;
else{
struct list_node *tmp = self->first;
while(tmp->next != NULL)
tmp = tmp -> next;
tmp->next = element;
}
}
void list_add_front(struct list *self, int value) {
struct list_node *element = malloc(sizeof(struct list_node));
if(element == NULL)
return;
element -> value = value;
element -> next = self -> first;
self -> first = element;
}
void list_insert(struct list *self, int value, size_t index) {
struct list_node *element = malloc(sizeof(*element));
element -> value = value;
struct list_node *cur_element = self->first;
struct list_node **prev_element = &self->first;
int i=0;
while(cur_element != NULL && i < index){
prev_element = &cur_element->next;
cur_element = cur_element ->next;
++i;
}
element->next = cur_element;
*prev_element = element;
}
void list_remove(struct list *self, size_t index) {
struct list_node *cur_element = NULL;
struct list_node *prev_element = NULL;
int i =0;
if(self->first->next != NULL && i != index){
prev_element = self->first;
cur_element = prev_element->next;
++i;
while(cur_element != NULL && i < index){
prev_element = cur_element;
cur_element = cur_element ->next;
++i;
}
if(cur_element != NULL){
prev_element -> next = cur_element->next;
free(cur_element);
}
}
else{
if(self->first != NULL){
cur_element = self->first;
cur_element = cur_element ->next;
free(self->first);
self->first = cur_element;
}
}
}
int *list_get(const struct list *self, size_t index) {
struct list_node *ptr;
ptr = self -> first;
for(size_t i = 0; i < index; ++i){
ptr = ptr -> next;
}
return &ptr -> value;
}
bool list_is_empty(const struct list *self) {
assert(self);
return (self -> first == NULL);
}
size_t list_size(const struct list *self) {
if(self->first == NULL)
return 0;
struct list_node *ptr = self ->first;
size_t i = 1;
while(ptr->next != NULL){
ptr = ptr -> next;
++i;
}
return i;
}
size_t list_search(const struct list *self, int value) {
struct list_node *ptr = self->first;
size_t i = 0;
while((ptr -> value != value) && (ptr -> next != NULL)){
ptr = ptr -> next;
++i;
}
if(ptr->value == value)
return i;
else return i+1;
}
void list_import(struct list *self, const int *other, size_t size) {
while(!list_is_empty(self)){
list_remove(self,0);
}
for(size_t i=0; i<size;++i){
list_insert(self, other[i], i);
}
}
void list_dump(const struct list *self) {
struct list_node *tmp = self->first;
while(tmp != NULL){
printf("%d ", tmp -> value);
tmp = tmp -> next;
}
printf("---");
}
bool list_is_sorted(const struct list *self) {
if (self->first == NULL)
return true;
struct list_node *ptr1 = self ->first;
struct list_node *ptr2 = self ->first->next;
for(size_t i = 1; i < list_size(self); i++){
if(ptr1 -> value > ptr2->value)
return false;
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return true;
}
void list_merge_sort(struct list *self) {
}
<file_sep>/lib/str.c
#include "str.h"
size_t str_length(const char *str) {
size_t len = 0;
if(str != NULL){
while(str[len] != '\0'){
len++;
}
}
return len;
}
int str_compare(const char *str1, const char *str2) {
size_t i=0;
while(str1[i] != '\0' && str2[i] != '\0'){
if(str1[i] != str2[i])
return str1[i] - str2[i];
i++;
}
return str1[i] - str2[i];
}
const char *str_search(const char *haystack, const char *needle) {
size_t i = 0;
while (haystack[i] != '\0') {
size_t j = 0;
while (needle[j] && haystack[i+j] && needle[j] == haystack[i+j])
j++;
if (needle[j] == '\0')
return haystack + i;
i++;
}
return NULL;
}
| f9e5ee5689ad2c00f1d108ed57dd8a4b852690ff | [
"Markdown",
"C"
]
| 5 | Markdown | lgrandperrin/AlgorithmicLibrary | 10246d9fe9f517c58034e3edfa882be08708382b | 6549343d755860c97d19dd20bc3df6bcacd026e4 |
refs/heads/main | <file_sep><?php
include_once("RO.html");
?> | 9e24f3e4b5e89e8e393ca595dd8be3e0ce4ad952 | [
"PHP"
]
| 1 | PHP | hsm-Gowthambalu/Mega-Advertisers-RO | 4d02f66cbb29e80385d6acd42ec34cd57aa62db2 | 5cc2f93d035f0c5176b258f9af56f5f9c3c0566a |
refs/heads/master | <file_sep>class Song
attr_accessor :name, :artist
def initialize(name)
@name = name
end
def self.new_by_filename(file_name)
artist_name = file_name.split(" - ")[0] #split on the artist
song_name = file_name.split(" - ")[1] #split on the song name
song = Song.new(song_name) #create a new song with the song_name created above
song.artist = Artist.find_or_create_by_name(artist_name) #assign this song's artist to new artist or find the existing artist
song.artist.add_song(self) #add the song
song #return the song
end
end
<file_sep>class MP3Importer
attr_reader :path
def initialize(path)
@path = path
# /spec/fixtures/mp3s" path
end
#
# Let's start with the MP3 Importer. Build an MP3Importer class that parses a directory of files and sends the filenames to a song class to create a library of music with artists that are unique. To do this, you'll need two methods: MP3Importer#files and MP3Importer#import.
def files
#get all file names from the path
file_array = []
Dir.foreach(@path) {|file| file_array << file }
file_array.slice(2,file_array.length-1)
end
# <NAME> - <NAME> - indie.mp3"
#
def import
files.each do |file|
Song.new_by_filename(file)
end
end
end
# Song.new_by_filename(some_filename)
<file_sep>class Artist
attr_accessor :name, :songs
@@all = []
def self.all
@@all
end
def initialize (name)
@name = name
@songs = []
end
def add_song(song)
@songs << song
end
def save #save the artist instance to the class of artists
@@all << self
end
def self.find_or_create_by_name(name)
self.find_by_name(name) || self.create_by_name(name)
end
def self.find_by_name(name)
Artist.all.find do |artist|
artist.name == name
end
end
def self.create_by_name(name)
#song isnt there so create a new one
new_artist = Artist.new(name)
new_artist.save
new_artist
end
# Artist #save adds the artist instance to the @@all class variable
def print_songs
@songs.each do |song|
puts song.name
end
end
end
| 9ce7921ccfc84fab805b18de10d45d7494118df4 | [
"Ruby"
]
| 3 | Ruby | volpja46/ruby-collaborating-objects-lab-web-080717 | 9df82bcd57fd4657c4c90b3588564f356e8c8b74 | 79c1add965d10d86ffcbe10579a21d25e0b0d32d |
refs/heads/main | <repo_name>chrisdetmering/StarWars<file_sep>/src/StarWarsPage.js
import React, {Component} from 'react';
import Input from './Input.js';
import SearchButton from './SearchButton.js';
import Table from './Table.js';
import axios from 'axios';
import PageButtons from './PageButtons';
class StarWarsPage extends Component {
constructor (props) {
super(props);
this.state = {
input : '',
characters: [],
isLoaded: false,
count: 0,
}
this.handleInputChange = this.handleInputChange.bind(this);
this.searchCharacters = this.searchCharacters.bind(this);
this.handlePageChange = this.handlePageChange.bind(this);
this.getCharacters = this.getCharacters.bind(this);
}
componentDidMount() {
this.getCharacters(`https://swapi.dev/api/people`);
}
async getCharacters(url) {
const response = await axios.get(url)
const count = response.data.count;
let characters = response.data.results;
characters = await Promise.all(characters.map(async character => {
character.homeWorld = await this.getHomeWorld(character.homeworld);
character.species = await this.getSpecies(character.species);
return character
}))
this.setState({
characters,
isLoaded: true,
count
});
}
async getHomeWorld(url) {
const response = await axios.get(url);
return response.data.name;
}
async getSpecies(url) {
if (url.length === 0) {
return "Human";
} else {
const response = await axios.get(url[0]);
return response.data.name;
}
}
searchCharacters(event) {
event.preventDefault();
this.getCharacters(`https://swapi.dev/api/people/?search=${this.state.input}`);
}
handleInputChange(e) {
this.setState({input: e.target.value});
}
handlePageChange(event) {
const pageNumber = event.target.id;
if (this.state.input === '') {
this.getCharacters(`https://swapi.dev/api/people/?page=${pageNumber}`);
} else {
this.getCharacters(`https://swapi.dev/api/people/?search=${this.state.input}&page=${pageNumber}`);
}
}
render () {
const {isLoaded} = this.state;
return (
<div>
<div className='text-warning mt-5 w-75 border border-white rounded mx-auto'>
<h1 className='d-flex justify-content-center display-3'>STAR WARS</h1>
<form className='form'>
<Input change={this.handleInputChange}/>
<SearchButton click={this.searchCharacters}/>
</form>
</div>
<div className='text-white'>
{isLoaded ?
<Table characters={this.state.characters}/>
: <div className='d-flex justify-content-center m-5'>Loading...</div>}
</div>
<div>
<PageButtons
click={this.handlePageChange}
count={this.state.count}>
</PageButtons>
</div>
</div>
)
}
}
export default StarWarsPage;<file_sep>/src/Table.js
function Table(props) {
return (
<div className='mt-5'>
<table className='table table-striped table-bordered table-hover w-75 mx-auto'>
<thead className='text-warning'>
<tr>
<th scope='col'>NAME</th>
<th scope='col'>BIRTH YEAR</th>
<th scope='col'>HEIGHT</th>
<th scope='col'>MASS</th>
<th scope='col'>HOMEWORLD</th>
<th scope='col'>SPECIES</th>
</tr>
</thead>
<tbody className='text-white'>
{props.characters.map((character, i) => {
return(
<tr key={i}>
<td>{character.name}</td>
<td>{character.birth_year}</td>
<td>{character.height}</td>
<td>{character.mass}</td>
<td>{character.homeWorld}</td>
<td>{character.species}</td>
</tr>
)})}
</tbody>
</table>
</div>
);
}
export default Table;<file_sep>/src/SearchButton.js
function SearchButton(props) {
return (
<div className='d-flex justify-content-center m-3'>
<button
onClick={props.click}
className='btn btn-warning text-white'>Search</button>
</div>
);
}
export default SearchButton;<file_sep>/src/Input.js
function Input(props) {
return (
<div className='d-flex justify-content-center m-5'>
<input
onChange={props.change}
className='form-control-sm bg-warning'>
</input>
</div>
);
}
export default Input;<file_sep>/src/PageButtons.js
function createPageButtons(pageCount, click) {
const buttons = [];
for (let i = 1; i <= pageCount; i++) {
buttons.push(
<button
key={i}
onClick={click}
id={i}
className='btn btn-warning text-white mx-1'>{i}</button>
)
}
return buttons;
}
function PageButtons({click, count}) {
const pageCount = Math.ceil(count / 10);
return (
<div className='d-flex justify-content-center m-3'>
{createPageButtons(pageCount, click)}
</div>
);
}
export default PageButtons;<file_sep>/README.md
#to Refactor
#1. Table.js > just pass in characters
#2. Change conditional rendering in StarWarsPage render method
#3. Presentational vs Container components | ca768da4e816917d55bf3a1c7bf3ecccaf2319f9 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | chrisdetmering/StarWars | 72cbda7f1f1865ea5d1397f4e8660fc43e697093 | 0a0fdc8a36f9d4af7ed3fd1200fd0ccac9d90f55 |
refs/heads/master | <repo_name>poojithavangala/Important-Tasks<file_sep>/ApachePOI/src/getDataFromExcel/ExcelDriven.java
package getDataFromExcel;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDriven {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
FileInputStream N = new FileInputStream("C:\\Users\\Fluffyy\\Desktop\\Exceltest.xlsx");
//First to get data from excel We have traverse from workbook --> Sheet --> Row --> column --> then grab the value required/set the value needed.
XSSFWorkbook W = new XSSFWorkbook(N); //workbook class and pass the argument of the excel object that is declared.
XSSFSheet sheet=W.getSheet("Sheet1");
XSSFRow row=sheet.getRow(2);
XSSFCell cell=row.getCell(1);
System.out.println(cell.getBooleanCellValue());
}
}
<file_sep>/TestNGExamples/src/testNGFramework/Test1.java
package testNGFramework;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Test1 {
@BeforeMethod //type of testNG annotation executed before any other test case execution
public void Login()
{
System.out.println("Login is successful");
}
@Test(enabled=false)//using this TestNG annotation we stop/pause the test case
public void Deposit()
{
System.out.println("Deposit is successful");
}
@Test(priority=2)// Using this annotation we set the priority to the test case to be executed
public void WithDraw()
{
System.out.println("WithDraw is successful");
}
@AfterMethod//type of testNG annotation executed after all other test case execution
public void Logout()
{
System.out.println("Logout is successful");
}
}
<file_sep>/ProtractorExamples/Select-Wrapper.js
//reduce effort during drop down using wrapper class.
var SelectWrapper = require('./Select-Wrapper.js');
var mySelect = new SelectWrapper(By.id("userSelect"));
describe("Select Wrapper class",function(){
it("handling dropdown with wrapper class locator",function(){
browser.get("http://www.way2automation.com/angularjs-protractor/banking/#/customer");
mySelect.selectByText("<NAME>");
browser.sleep(3000);
});
it("Finding count and printing all dropdown items",function(){
browser.get("http://www.way2automation.com/angularjs-protractor/banking/#/customer");
var dropoptions = mySelect.getOptions();
dropoptions.then(function(options){
console.log(options.length);
});
});
});<file_sep>/seleniumLearn/src/sample/Alerts.java
package sample;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Alerts {
public static void main(String[] args) {
WebDriver D=new FirefoxDriver();
D.get("http://www.tizag.com/javascriptT/javascriptalert.php");
//click on confirmation alert button to view the pop-up window
D.findElement(By.xpath("html/body/table[3]/tbody/tr[1]/td[2]/table/tbody/tr/td/div[4]/form/input")).click();
//To display the text present on the pop-up window
System.out.println(D.switchTo().alert().getText());
//Switch control from driver(D) to alert for inspecting.
D.switchTo().alert().accept();//Accept method is used to create a positive scenario(YES, OK, DONE)
//D.switchTo().alert().dismiss(); //Dismiss is a method to click cancel buttons on the alert window
}
}
<file_sep>/ProtractorExamples/Expecttobe.js
describe("Validation of expect statement",function(){
var expected_text;
beforeEach(function(){
browser.get("http://www.way2automation.com/angularjs-protractor/calc/");
element(by.model("first")).sendKeys("2");
element(by.model("second")).sendKeys("4");
element(by.buttonText("Go!")).click();
expected_text=element(by.binding("latest")).getText();
});
it("validation test1 for 2+4 is true",function(){
expected_text.then(function(text){
console.log("Result is:" +text);
expect(parseInt(text)).toBe(6);
});
});
it("validation test1 for 2+4 is not 6",function(){
expected_text.then(function(text){
console.log("Result is:" +text);
expect(parseInt(text)).not.toBe(4);
});
});
});<file_sep>/TestNGExamples/bin/dataDriven/dataDrive.properties
Username = poojitha
Password = <PASSWORD>!
URL = https://google.com
browser=Chrome<file_sep>/javaLearn1/src/Getter.java
public class Getter {
String name;
int age;
int timeToretirement(){
int yearsLeft = 65 - age ;
return yearsLeft;
}
int getAge(){
return age;
}
String getName(){
return name;
}
public static void main(String[] args) {
Getter person1 = new Getter();
person1.name = "pooh";
person1.age = 20;
int years = person1.timeToretirement();
System.out.println("Years till retirement : " + years);
int age = person1.getAge();
System.out.println("Age is : " + age);
String name = person1.getName();
System.out.println("Name is : " + name);
}
}
<file_sep>/ProtractorExamples/CalculatorAdd.js
describe("Calculator App Testing",function(){
beforeEach(function(){
browser.get("http://www.way2automation.com/angularjs-protractor/calc/");
});
afterEach(function(){
browser.sleep(4000);
console.log("executed it block");
});
it("Test Case1 validation",function(){
element(by.model("first")).sendKeys("2");
element(by.model("second")).sendKeys("4");
element(by.buttonText("Go!")).click();
element(by.binding("latest")).getText().then(function(text){
console.log("Result is : " +text);
});
});
it("Test Case1 validation",function(){
element(by.model("first")).sendKeys("2");
element(by.model("second")).sendKeys("5");
element(by.buttonText("Go!")).click();
element(by.binding("latest")).getText().then(function(text){
console.log("Result is : " +text);
});
});
});<file_sep>/javaLearn1/src/Machine1.java
//Interfaces example
public class Machine1 implements Info{
private int id = 7;
public void start(){
System.out.println("Start the engine");
}
public void showinfo() {
// TODO Auto-generated method stub
}
}
<file_sep>/seleniumLearn/src/sample/StaticDropDown.java
package sample;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class StaticDropDown {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Fluffyy\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Thread.sleep(5000);
driver.get("http://www.spicejet.com/");
//When you find <select> tag in the static drop down HTML page then go with this method of selection.
Select s = new Select(driver.findElement(By.id("ctl00_mainContent_ddl_Adult")));
Thread.sleep(5000);
s.selectByValue("4");
Thread.sleep(5000);
s.selectByIndex(0);
Thread.sleep(5000);
s.selectByVisibleText("3 Adults");
Thread.sleep(5000);;
//Dynamic dropdown
driver.findElement(By.xpath("//input[@id='ctl00_mainContent_ddl_originStation1_CTXT']")).click();
Thread.sleep(5000);
driver.findElement(By.xpath("//*[@id='dropdownGroup1']/div/ul[4]/li[3]/a")).click();
Thread.sleep(5000);
driver.findElement(By.xpath("(//*[@id='dropdownGroup1']/div/ul[1]/li[4]/a)[2]")).click();
//CheckBoxes
Thread.sleep(5000);
driver.findElement(By.id("ctl00_mainContent_chk_StudentDiscount")).click();
System.out.println(driver.findElement(By.id("ctl00_mainContent_chk_StudentDiscount")).isSelected());
driver.close();
}
}
<file_sep>/ProtractorExamples/Test1.js
describe("To test a banking app",function(){
it("Enter Text",function(){
browser.get("https://angularjs.org/");
element(by.model("yourName")).sendKeys("poojitha");
element(by.binding("yourName")).getText().then(function(text){
console.log(text);
});
});
});<file_sep>/seleniumLearn/src/sample/WebTable.java
package sample;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WebTable {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Fluffyy\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver W = new ChromeDriver();
W.get("https://www.w3schools.com/html/html_tables.asp");
WebElement table = W.findElement(By.id("customers")); //Locating table element in the web page
//Fining rows in table
List<WebElement> eachrow = table.findElements(By.tagName("tr"));
System.out.println("Number of rows : " + eachrow.size());
//Find number of columns present in each row
}
}
<file_sep>/seleniumLearn/src/sample/MultipleWindowHandling.java
package sample;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MultipleWindowHandling {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Fluffyy\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver c = new ChromeDriver();
c.get("https://accounts.google.com/SignUp?hl=en-GB");
c.findElement(By.linkText("Learn more")).click();
System.out.println(c.getTitle());//Gives the title of the parent window
//To handle all the windows id's that are controlled by webdriver(if there is more than 1 window)
Set<String> id=c.getWindowHandles();//All the windows are stored as a set of strings in "id" object
Iterator<String> it=id.iterator();//iterator is a java method that helps in moving from parent window to child window
String parent_id=it.next();//Here .next(); method is used to move to the parent window
String child_id=it.next(); // Here another next method is used to move from parent window to child window in a set.
c.switchTo().window(child_id); // To switch from parent to child window
System.out.println(c.getTitle()); // prints the title of child window.
c.switchTo().window(parent_id); //switching back to parent window
System.out.println(c.getTitle());
}
}
<file_sep>/javaLearn1/src/Car.java
public class Car {
private String make;
int speed;
int gear;
public Car(){
this.speed = 0;
this.gear = 0;
System.out.println("Executing constructors without arguments");
}
public Car(int speed,int gear){
this.speed = speed;
this.gear = gear;
System.out.println("Executing constructors with arguments");
}
// "this" refers to the instance of the class (object)
public void setMake(String make) {
this.make = make;
}
public String getMake() {
return make;
}
}
<file_sep>/seleniumLearn/src/sample/MyNewScript.java
package sample;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MyNewScript {
public static void main(String[] args) throws InterruptedException {
//WebDriver c = new FirefoxDriver();
//Thread.sleep(5000);
//Thread.sleep(5000);
//m.close();
System.setProperty("webdriver.chrome.driver","C:\\Users\\Fluffyy\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver c = new ChromeDriver();
c.get("https://www.facebook.com/");
Thread.sleep(5000);
c.findElement(By.id("email")).sendKeys("<EMAIL>");
Thread.sleep(5000);
c.findElement(By.id("pass")).sendKeys("<PASSWORD>");
Thread.sleep(5000);
c.findElement(By.id("u_0_q")).click();
//Thread.sleep(5000);
//c.findElement(By.id("pass")).sendKeys("<PASSWORD>");
//Thread.sleep(5000);
//c.findElement(By.xpath("//*[@id='login_form']/table/tbody/tr[3]/td[2]/div/a")).click();
Thread.sleep(5000);
c.close();
}
}
<file_sep>/Cucumber/src/stepDefinitionFile/AttitudeTest.java
package stepDefinitionFile;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class AttitudeTest {
@Given("I work in ([^\"]*)")
public void ln(String str)//regular expression argument will come and fall into the method ln(String str)
{
if(str.equals("Latenights"))
{
System.out.println("Latenight automation");
}
if(str.equals("Mornings"))
{
System.out.println("Execute another automation test case");
}
}
@When("^I meet ([^\"]*)$")
public void Imeet(String str)
{
if(str.equals("watchmen"))
{
System.out.println("RUN this test case under this test case ");
}
if(str.equals("NewspaperBoy"))
{
System.out.println("Run this test case");
}
}
@Then("^I ([^\"]*) him$")
public void Greet(String str)
{
if (str.equals("Greeted"))
{
System.out.println("Greeted");
}
if(str.equals("skipGreeting"))
{
System.out.println("Skipped it");
}
}
@Given("we work in \"([^\"]*)\"$")
public void we_work_in(String arg1) throws Throwable
{
System.out.println("Print this parameterized case");
}
}
<file_sep>/javaLearn1/src/Setters.java
//Setter method
class Frog {
String name;
int age;
public void setName(String newName){
name = newName;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
public class Setters {
public static void main(String[] args) {
Frog frog1 = new Frog();
//frog1.name = "Ben";
//frog1.age = 5;
frog1.setName("Bertie");
//System.out.println(frog1.getName());
}
}
<file_sep>/ProtractorExamples/CustomerLogin.js
describe("Customer Login",function(){
it("click on customer login",function(){
browser.get("http://www.way2automation.com/angularjs-protractor/banking/#/login");
element(by.buttonText("Customer Login")).click();
browser.sleep(3000);
element.all(by.css("#userSelect option")).then(function(items){
console.log("Total values in dropdown are"+items.length);
for (i=0;i<items.length;i++){
items[i].getText().then(function(text){
console.log(text);
});
}
for (i=0;i<items.length;i++){
items[i].getAttribute("value").then(function(text){
console.log(text);
});
}
element(by.model("custId")).$("[value='2']").click();
browser.sleep(3000);
});
});
});<file_sep>/seleniumLearn/src/sample/Action_demo.java
package sample;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Action_demo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Fluffyy\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver d=new ChromeDriver();
d.get("https://www.amazon.com/");
Actions a = new Actions(d); // Actions class a will invoke all the driver "d" features to perform tasks
WebElement move = d.findElement(By.xpath("//a[@id='nav-link-shopall']"));
a.moveToElement(move).build().perform();//a object uses build to build the whole action to be performed
//& to execute the action perform() method is used
a.moveToElement(d.findElement(By.xpath("//input[@id='twotabsearchtextbox']"))).click().keyDown(Keys.SHIFT).sendKeys("hello").build().perform();
}
}
| 5c76898a549408c2220befa41b474e5ecd2748b6 | [
"JavaScript",
"Java",
"INI"
]
| 19 | Java | poojithavangala/Important-Tasks | 521f4f80476bc648127132e563869fd24af00472 | 8adcc9c09f85638bca2cd0c2d3717cdfb2911b60 |
refs/heads/master | <repo_name>AhmedAboulezz/Blog<file_sep>/blog/forms.py
from django import forms
from .models import Blog
class BlogForm(forms.ModelForm):
blog=forms.CharField(label='',
widget=forms.Textarea(
attrs={'placeholder': "Your blog",
"class": "form-control"
}
))
def __init__(self,user, *args, **kwargs):
super(BlogForm, self).__init__(*args, **kwargs)
self.user = user
self.fields['user'].initial = user
def clean(self):
cleaned_data=super(BlogForm, self).clean()
user=cleaned_data.get(self.user)
if Blog.objects.filter(user=self.user).count()>=3:
raise forms.ValidationError("You are allowed to post only 3 blogs")
class Meta:
model=Blog
fields = ['user',
'blog',
'tags']
widgets = {'user': forms.HiddenInput()}
# def clean_blog(self,*args,**kwargs):
# content=self.cleaned_data.get('blog')
# if content=='abc':
# raise forms.ValidationError("SORRRRY")
# return content
<file_sep>/blog/admin.py
from django.contrib import admin
from .models import Blog
from .forms import BlogForm
# Register your models here.
class AdminBlog(admin.ModelAdmin):
form = BlogForm
admin.site.register(Blog)<file_sep>/blog/models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
class Blog(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE)
blog=models.CharField(max_length=140)
tags = models.CharField(max_length=25)
# def save(self, *args, **kwargs):
# if self.__class__.objects.filter(user=self.user).count() > 2:
# raise ValidationError("Too Much")
# return super(Blog, self).save(*args, **kwargs)
def __str__(self):
return "Blog #"+str(self.id)+" written by "+'"'+str(self.user)+'"'
<file_sep>/blog/views.py
from django.shortcuts import render
from django.views.generic import DeleteView , UpdateView , CreateView
from .models import Blog
import random
from django.db.models import Max
from django.urls import reverse_lazy
from .forms import BlogForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
#
# class BlogListView(ListView):
# Blogobjects=Blog.objects.all()
#
# IDs = []
# for i in Blogobjects:
# IDs.append(i.id)
# random_ID=random.choice(IDs)
# queryset = Blog.objects.get(id=random_ID)
# print(queryset)
# if queryset == queryset:
# random_ID = random.choice(IDs)
# queryset = Blog.objects.get(id=random_ID)
#
# x=2
# extra_context = {'IDs': random_ID,'x':x}
# template_name = 'blog/home.html'
def BlogListView(request):
userid = request.user.id
max_id = Blog.objects.all().aggregate(max_id=Max("id"))['max_id']
if max_id is not None:
while True:
pk = random.randint(1, max_id)
blogobj = Blog.objects.filter(pk=pk, user__is_active=True).first()
# print(Blog.objects.filter(is_active=True))
if blogobj:
return render(request, "blog/home.html", {"blogobj": blogobj, "userid": userid})
else:
blogobj= None
return render(request, "blog/home.html", {"blogobj": blogobj, "userid": userid})
# class BlogDetailView(DetailView):
# def get_object(self):
# return self.request.user
# myobjects=Blog.objects.all()
# print(myobjects.filter(user_id=1))
def BlogDetailView(request, id):
userid = request.user.id
blogobj = Blog.objects.all()
userblog=(blogobj.filter(user_id=id))
return render(request,template_name = 'blog/myblogs.html',context={"blogs":userblog,"userid":userid})
class BlogDeleteView(LoginRequiredMixin,DeleteView):
model=Blog
template_name = 'blog/Deletemyblogs.html'
success_url = reverse_lazy('home')
class BlogUpdateView(LoginRequiredMixin,UpdateView):
queryset = Blog.objects.all()
form_class = BlogForm
# fields = ['blog',
# 'tags']
template_name = 'blog/updatemyblogs.html'
success_url = reverse_lazy('home')
class BlogCreateView(LoginRequiredMixin,CreateView):
form_class = BlogForm
template_name = 'blog/createview.html'
success_url = reverse_lazy('home')
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs(*args, **kwargs)
kwargs['user'] = self.request.user
return kwargs
class SignUp(CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('home')
template_name = 'blog/signup.html'
| 8a08a105faa1e6826cf4c9abd2642825a09201a3 | [
"Python"
]
| 4 | Python | AhmedAboulezz/Blog | 2fdbe9dc651b0ee2822f4dcef06d5a250b8627af | 9fa3885786b33a0bdbcbff2e48f01894937cbdfd |
refs/heads/master | <file_sep>/**
* Created by luoyuyu on 2017/2/14.
*/
function myfun() {
x=document.getElementById("testForJS");
x.style.color="#ff0000";
}<file_sep>/**
* Created by luoyuyu on 2017/2/15.
*/
var x=document.getElementById("myCanvas");
var x=x.getContext("2d");
x.beginPath();
x.arc(0,0,100,0,2*Math.PI);
x.stroke();<file_sep>/**
* Created by luoyuyu on 2017/4/11.
*/
// let user_friendsName =[];
// let user_friendVerified = [];
// user_friendsName[i] = friends[i].screen_name;
// if (friends[i].verified_reason_modified !== ''||friends[i].verified_reason_modified!=""){
// user_friendVerified[i] = friends[i].verified_reason_modified
// }else {
// user_friendVerified[i] = '暂无';
// }
var friendLists = function () {
let user_friends = [];
for (let i=0;i<friends.length;i++){
if (friends[i].verified_reason !== ''||friends[i].verified_reason!=""){
user_friends.push({
'screen_name':friends[i].screen_name,
'verified': friends[i].verified_reason
})
}
else {
user_friends.push({
'screen_name':friends[i].screen_name,
'verified': '暂无'
})
}
}
$('#friend_table').bootstrapTable('destroy').bootstrapTable({
columns: [
{
field: 'screen_name',
title: '微博ID',
sortable: true
}, {
field: 'verified',
title: '微博关注者认证信息',
sortable: true
},{
radio: true
}
],
data: user_friends,
pagination: true,
search: true,
showColumns: true,
clickToSelect: true,
showToggle: true,
});
};
var fellowLists = function () {
let user_fellows = [];
for (let i=0;i<fellows.length;i++){
if (fellows[i].verified_reason !== ''||fellows[i].verified_reason!=""){
user_fellows.push({
'screen_name':fellows[i].screen_name,
'verified': fellows[i].verified_reason
})
}
else {
user_fellows.push({
'screen_name':fellows[i].screen_name,
'verified': '暂无'
})
}
}
$('#fellow_table').bootstrapTable('destroy').bootstrapTable({
columns: [
{
field: 'screen_name',
title: '微博ID',
sortable: true
}, {
field: 'verified',
title: '微博粉丝者认证信息',
sortable: true
},{
radio: true
}
],
data: user_fellows,
pagination: true,
search: true,
showColumns: true,
clickToSelect: true,
showToggle: true,
});
};
// data: [
// {
// id: 1,
// name: '常红燕',
// price: '99.93%'
// }, {
// id: 2,
// name: '林凯毅',
// price: '99.93%'
// },
// {
// id: 3,
// name: '胡锐',
// price: '99.93%'
// },
// {
// id: 4,
// name: 'angel',
// price: '99.93%'
// },
// {
// id: 5,
// name: 'Jhone',
// price: '99.93%'
// },
// {
// id: 6,
// name: 'zhangzhe',
// price: '99.93%'
// },
// {
// id: 7,
// name: 'xidada',
// price: '99.93%'
// }
// ],<file_sep>
document.write("<p><strong>Document.write</strong></p>");
function change() {
x=document.getElementById('pId');
x.innerHTML+="Hello,world! I can use JavaScript to change it."
}
function testMetric() {
var x=document.getElementById("tMetric").value;
if (x==""||isNaN(x)){
alert("Not Numeric");
}
}
var carnames=new Array("Audi",'BMW','BENZI','Volvo');
function showCars() {
for (var i=0;i<carnames.length;i++){
document.write(carnames[i]+"<br>");
}
}
var person={
firstName: "Bill",
lastName: "Gates",
perId: 2014220901027
};
function showPerson() {
document.write(person.firstName+person.lastName+person.perId.toString());
}<file_sep>var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/helloworld',function (req, res, next) {
res.render('helloworld',{title:'~~Hello, World!'});
});
router.get('/api', function(req, res, next) {
res.send({
"title": {
"text": "各类衣裤销售量"
},
"tooltip": {},
"legend": {
"data":["销量1"]
},
"xAxis": {
"data": ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
"yAxis": {},
"series": [{
"name": "销量1",
"type": "bar",
"data": [115, 120, 36, 10, 10, 20]
}]
});
});
router.post('/api', function (req,res) {
})
module.exports = router;
<file_sep># -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy import Item, Field
class InformationItem(Item):
""" 个人信息 """
_id = Field() # 用户ID
NickName = Field() # 昵称
Gender = Field() # 性别
Address = Field() # 地址
Signature = Field() # 个性签名
Regist_time = Field() # 注册时间
Identity = Field() # 用户类别
Birthday = Field() # 生日
Num_Tweets = Field() # 微博数
Num_Follows = Field() # 关注数
Num_Fans = Field() # 粉丝数
Sex_Orientation = Field() # 性取向
Marriage = Field() # 婚姻状况
URL = Field() # 首页链接
class TweetsItem(Item):
""" 微博信息 """
_id = Field() # 用户ID-微博ID
ID = Field() # 用户ID
Content = Field() # 微博内容
PubTime = Field() # 发表时间
Co_oridinates = Field() # 定位坐标
Tools = Field() # 发表工具/平台
Like = Field() # 点赞数
Comment = Field() # 评论数
Transfer = Field() # 转载数
class FollowsItem(Item):
""" 关注人列表 """
_id = Field() # 用户ID
Num_Follows = Field() # 关注数
follows = Field() # 关注
class FansItem(Item):
""" 粉丝列表 """
_id = Field() # 用户ID
Num_Fans = Field() # 粉丝数
fans = Field() # 粉丝
class CommentItem(Item):
""" 评论列表 """
_id = Field()
Tweet_id = Field() # 微博ID
ID = Field() # 微博用户ID
Comment_id = Field() # 评论用户ID
Content = Field() # 评论内容
Time = Field() # 评论发表时间
Liked = Field() # 评论被点赞数
class DulSpiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
<file_sep>/**
* Created by luoyuyu on 24/07/2017.
*/
// var rf=require("fs");
// var allText=rf.readFileSync("../public/bootstrap-test/f1.csv","utf-8");
// console.log(allText)
// var allText = allText.split('\n')
// console.log(allText)
// var line = [];
// for (let i = 1;i<=allText.length;i++){
// line[i] = allText[i-1];
// }
// console.log(line)
var express = require('express');
var router = express.Router();
router.get('/reptile',function (req,res,next){
let readTag = req.query.info;
if (readTag == 'friendTable'){
let user_friends = [];
let rf=require("fs");
let friendText=rf.readFileSync(__dirname +"/bootstrap-test/f1.csv","utf-8");
friendText = friendText.split('\n')
for (let i = 0;i<friendText.length;i++){
let sn = friendText[i].split(',')[1];
let v = friendText[i].split(',')[2];
user_friends.push({
'order': i+1,
'screen_name':sn,
'verified': v
})
}
res.json(['success',user_friends]);
}
if (readTag == 'fellowTable'){
let user_fellows = [];
let rf=require("fs");
let fellowText=rf.readFileSync(__dirname +"/bootstrap-test/f2.csv","utf-8");
fellowText = fellowText.split('\n')
// console.log(fellowText)
for (let i = 0;i<fellowText.length;i++){
let sn = fellowText[i].split(',')[1];
let v = fellowText[i].split(',')[2];
user_fellows.push({
'order': i+1,
'screen_name':sn,
'verified': v
})
}
// console.log(user_fellows)
res.json(['success',user_fellows]);
}
if (readTag == 'weiboTable'){
let weibo_list = [];
let rf=require("fs");
let weiboText=rf.readFileSync(__dirname +"/bootstrap-test/info.csv","utf-8");
weiboText = weiboText.split('\n')
for (let i = 0;i<weiboText.length;i++){
let sn = weiboText[i].split(',')[0];
let t = weiboText[i].split(',')[1];
let s = weiboText[i].split(',')[2];
let r = weiboText[i].split(',')[3];
let c = weiboText[i].split(',')[4];
weibo_list.push({
'order': i+1,
'screen_name':sn,
'text': t,
'source':s,
'reposts_count': r,
'comments_count': c
})
}
res.json(['success',weibo_list]);
}
});
router.get('/userTruth',function (req,res,next){
let readTag = req.query.info;
let reqOrder = req.query.order;
console.log("reqOrder",reqOrder);
if (readTag == 'friendData'){
let user_friends = [];
let rf=require("fs");
let friendText=rf.readFileSync(__dirname +"/bootstrap-test/f1.csv","utf-8");
friendText = friendText.split('\n');
friendText = friendText[reqOrder-1];
// SM 解密过程
console.log("******************************************************** 接收到前端请求指令 ********************************************************")
let crypto = require("crypto");
let ciphter = crypto.createCipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
let s = "";
s += ciphter.update("message","utf8","hex");
s += ciphter.final("hex");
console.log("******************************************************** 密文 ********************************************************")
let sm = rf.readFileSync(__dirname +"/bootstrap-test/SM.csv","utf-8");
console.log(sm)
console.log("******************************************************** 明文 ********************************************************")
console.log("Please detect user, order is : "+reqOrder +"!");
//调用爬虫模块
setTimeout(function () {
//TODO print...
let spider = rf.readFileSync(__dirname +"/bootstrap-test/spider.csv","utf-8");
console.log(spider);
},3500);
//调用深度学习模块
setTimeout(function () {
//TODO print...
let dl = rf.readFileSync(__dirname +"/bootstrap-test/deep.csv","utf-8");
console.log(dl);
for (let i=3;i<10;i++){
user_friends.push(friendText.split(',')[i]);
}
console.log(user_friends);
// SM 加密
console.log("******************************************************** SM4 Decryption ********************************************************")
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
var o = "";
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
o += decipher.update(s,"hex","utf8");
o += decipher.final("utf8");
console.log(o); // aaabbbccc
let sm = rf.readFileSync(__dirname +"/bootstrap-test/SM.csv","utf-8");
console.log(sm)
res.json(['success',user_friends]);
},4500);
}
if (readTag == 'fellowData'){
let user_fellows = [];
let rf=require("fs");
let fellowText=rf.readFileSync(__dirname +"/bootstrap-test/f2.csv","utf-8");
fellowText = fellowText.split('\n');
fellowText = fellowText[reqOrder-1];
// SM 解密过程
console.log("******************************************************** 接收到前端请求指令 ********************************************************")
let crypto = require("crypto");
let ciphter = crypto.createCipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
let s = "";
s += ciphter.update("message","utf8","hex");
s += ciphter.final("hex");
console.log("******************************************************** 密文 ********************************************************")
let sm = rf.readFileSync(__dirname +"/bootstrap-test/SM.csv","utf-8");
console.log(sm)
console.log("******************************************************** 明文 ********************************************************")
console.log("Please detect user, order is : "+reqOrder +"!");
//调用爬虫模块
setTimeout(function () {
//TODO print...
let spider = rf.readFileSync(__dirname +"/bootstrap-test/spider.csv","utf-8");
console.log(spider);
},3500);
//调用深度学习模块
setTimeout(function () {
//TODO print...
let dl = rf.readFileSync(__dirname +"/bootstrap-test/deep.csv","utf-8");
console.log(dl);
for (let i=3;i<10;i++){
user_fellows.push(fellowText.split(',')[i]);
}
console.log(user_fellows);
// SM 加密
console.log("******************************************************** SM4 Decryption ********************************************************")
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
var o = "";
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
o += decipher.update(s,"hex","utf8");
o += decipher.final("utf8");
console.log(o); // aaabbbccc
let sm = rf.readFileSync(__dirname +"/bootstrap-test/SM.csv","utf-8");
console.log(sm)
res.json(['success',user_fellows]);
},4500);
}
});
router.get('/infoTruth',function (req,res,next){
let reqOrder = req.query.order;
console.log(reqOrder)
//TODO read file
let weibo_data = [];
let rf=require("fs");
let fellowText=rf.readFileSync(__dirname +"/bootstrap-test/info.csv","utf-8");
fellowText = fellowText.split('\n');
fellowText = fellowText[reqOrder-1];
// SM 解密过程
console.log("******************************************************** 接收到前端请求指令 ********************************************************")
let crypto = require("crypto");
let ciphter = crypto.createCipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
let s = "";
s += ciphter.update("message","utf8","hex");
s += ciphter.final("hex");
console.log("******************************************************** 密文 ********************************************************")
let sm = rf.readFileSync(__dirname +"/bootstrap-test/SM.csv","utf-8");
console.log(sm)
console.log("******************************************************** 明文 ********************************************************")
console.log("Please detect user, order is : "+reqOrder +"!");
//调用爬虫模块
setTimeout(function () {
//TODO print...
let spider = rf.readFileSync(__dirname +"/bootstrap-test/spider.csv","utf-8");
console.log(spider);
},3500);
//调用深度学习模块
setTimeout(function () {
//TODO print...
let dl = rf.readFileSync(__dirname +"/bootstrap-test/deep.csv","utf-8");
console.log(dl);
for (let i=5;i<17;i++){
weibo_data.push(fellowText.split(',')[i]);
}
// SM 加密
console.log("******************************************************** SM4 Decryption ********************************************************")
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
var o = "";
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
o += decipher.update(s,"hex","utf8");
o += decipher.final("utf8");
console.log(o); // aaabbbccc
let sm = rf.readFileSync(__dirname +"/bootstrap-test/SM.csv","utf-8");
console.log(sm)
// console.log(weibo_data);
res.json(['success',weibo_data]);
},4500);
});
router.get('/url',function (req,res,next){
let url = req.query.url;
console.log("SM2密钥协商... ...");
console.log("SM4解密... ...");
console.log("调用爬虫... ...");
let rf=require("fs");
let urlData=rf.readFileSync(__dirname +"/bootstrap-test/url1.csv","utf-8");
console.log(urlData);
let s = "[dmoz] DEBUG: Crawled (200) <GET "+url+"_>";
console.log(s);
urlData=rf.readFileSync(__dirname +"/bootstrap-test/url2.csv","utf-8");
let deepL = rf.readFileSync(__dirname +"/bootstrap-test/deep.csv","utf-8");
console.log(deepL);
console.log("SM2密钥协商... ...");
console.log("SM4加密... ...");
console.log("将处理好的数据返回前台.. ...");
res.json(['success',urlData]);
});
module.exports = router;<file_sep>/**
* Created by luoyuyu on 2017/3/27.
*/
function sign_up() {
"use strict";
//获取form中的注册信息
let username = $("#username").val().toString();
let password = $("#password").val().toString();
let password1 = $("#password1").val().toString();
let email = $("#email_address").val().toString();
// 对form中的相关信息进行判断,发现问题后,返回给客户端
if (username == ''){
document.getElementById("signupDiv").style.display = "block";
document.getElementById("signupDiv").innerHTML = `<strong>请输入用户名!</strong>`;
setTimeout(function () {
document.getElementById("signupDiv").style.display = "none";
}, 2000);
}
else if(password == '' || password1 ==''){
document.getElementById("signupDiv").style.display = "block";
document.getElementById("signupDiv").innerHTML = `<strong>请输入密码!</strong>`;
setTimeout(function () {
document.getElementById("signupDiv").style.display = "none";
}, 2000);
}
else if (password!=<PASSWORD>1){
document.getElementById("signupDiv").style.display = "block";
document.getElementById("signupDiv").innerHTML = `<strong>请确认两次密码是否一样!</strong>`;
setTimeout(function () {
document.getElementById("signupDiv").style.display = "none";
}, 2000);
}
else if (!validateEmail(email)){
document.getElementById("signupDiv").style.display = "block";
document.getElementById("signupDiv").innerHTML = `<strong>请确认邮箱地址是否正确!</strong>`;
setTimeout(function () {
document.getElementById("signupDiv").style.display = "none";
}, 2000);
}
else { // 对form中的相关信息进行判断无误之后发送注册请求给服务器
$("#myModal").modal(); //弹出模态框进行人脸信息注册
$("#signup_face").click(function () { //注册人脸信息按钮被激活
//判断人脸信息是否合法
/// 首先要将图片上传到nodejs服务器
//人脸注册成功之后,再将username等注册信息写入数据库
////**************************测试**********************
// console.log("接受到用户注册请求...")
// console.log("用户文本账号密码注册成功!");
// console.log("用户名:",username);
// console.log("密码:",password);
// console.log("邮箱:",email);
// console.log("用户人脸信息注册成功!")
// console.log("注册完毕!^_^")
////**************************测试**********************
context.drawImage(video, 0, 0, 400, 300); //640对应video标签里面的width; 480对应video标签里面的height
$.ajax({
url: 'signup/req_snap',
type: 'POST',
data: {
snapData: canvas.toDataURL('image/png'),
username: username,
tag: 0
},
success: function (data) {
signup_face(username,password,email); //人脸认证函数 //$("#username").val().toString() == username
},
error: function (jqXHR, textStatus, errorThrown) {
// console.log("snap++ 错误", jqXHR, textStatus, errorThrown);
swal("网络错误", "请检查网络连接!", "error")
}
});
});
}
}
//一些其他和注册相关的函数,比如检查邮件地址是否正确等等
function validateEmail(email) {
"use strict";
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
<file_sep>/**
* Created by luoyuyu on 2017/2/23.
*/
//INSERT INTO `dataVisDB`.`selectCourses` (`scId`, `courseName`, `selectWeight`, `result`) VALUES ('22', 'DataBase', '0', '0');
var s1="INSERT INTO `dataVisDB`.`selectCourses` (`scId`, `courseName`, `selectWeight`, `result`) VALUES ";
var s2=('22', 'DataBase', '0', '0');
var i=20;
string arr=[];
arr.push(i.toString());
console.log(arr);
document.writeln(arr);<file_sep>/**
* Created by luoyuyu on 2017/4/11.
*/
$('#friend_table').bootstrapTable('destroy').bootstrapTable({
columns: [
{
field: 'id',
title: '序号',
sortable: true
}, {
field: 'name',
title: '好友微博ID',
sortable: true
}, {
field: 'price',
title: '微博好友可信度',
sortable: true
},{
radio: true
}
],
data: [
{
id: 1,
name: '常红燕',
price: '99.93%'
}, {
id: 2,
name: '林凯毅',
price: '99.93%'
},
{
id: 3,
name: '胡锐',
price: '99.93%'
},
{
id: 4,
name: 'angel',
price: '99.93%'
},
{
id: 5,
name: 'Jhone',
price: '99.93%'
},
{
id: 6,
name: 'zhangzhe',
price: '99.93%'
},
{
id: 7,
name: 'xidada',
price: '99.93%'
}
],
pagination: true,
search: true,
showColumns: true,
clickToSelect: true,
showToggle: true,
});<file_sep>/**
* Created by luoyuyu on 2017/4/13.
*/
//这个文件定义了数据操作api的路由
var express = require('express');
var router = express.Router();
var fs=require('fs'); //文件操作
// var Canvas = require('canvas'); //需安装canvas模块
/* GET api listing. */
module.exports = router;<file_sep>/**
* Created by luoyuyu on 2017/2/22.
*/
var rs ={
}<file_sep># encoding=utf-8
import sys
import logging
import datetime
import requests
import re
from lxml import etree
from Dul_spider.weiboID import weiboID
from Dul_spider.scrapy_redis.spiders import RedisSpider
from scrapy.selector import Selector
from scrapy.http import Request
from Dul_spider.items import TweetsItem, InformationItem,CommentItem,FollowsItem, FansItem
import importlib
importlib.reload(sys)
sys.setdefaultencoding('utf8')
class Spider(RedisSpider):
name = "SinaSpider"
host = "https://weibo.cn"
redis_key = "SinaSpider:start_urls"
start_urls = list(set(weiboID))
scrawl_ID = set(start_urls) # 记录待爬的微博ID
finish_ID = set() # 记录已爬的微博ID
logging.getLogger("requests").setLevel(logging.WARNING) # 将requests的日志级别设成WARNING
def start_requests(self):
for uid in self.start_urls:
while self.scrawl_ID.__len__():
ID = self.scrawl_ID.pop()
self.finish_ID.add(ID) # 加入已爬队列
ID = str(ID)
follows = []
followsItems = FollowsItem()
followsItems["_id"] = ID
followsItems["follows"] = follows
fans = []
fansItems = FansItem()
fansItems["_id"] = ID
fansItems["fans"] = fans
url_follows = "https://weibo.cn/%s/follow" % ID
url_fans = "https://weibo.cn/%s/fans" % ID
url_tweets = "https://weibo.cn/%s/profile?filter=1&page=1" % ID
url_information = "https://weibo.cn/attgroup/opening?uid=%s" % ID
url_comments = "https://weibo.cn/comment/inbox?topnav=1&wvr=5&f=1&page=%d" % ID
yield Request(url=url_follows, meta={"item": followsItems, "result": follows},
callback=self.parse_FOF) # 去爬关注人
yield Request(url=url_fans, meta={"item": fansItems, "result": fans}, callback=self.parse_FOF) # 去爬粉丝
yield Request(url=url_information, meta={"ID": ID}, callback=self.parse_information) # 去爬个人信息
yield Request(url=url_tweets, meta={"ID": ID}, callback=self.parse_tweets) # 去爬微博_tweets
yield Request(url=url_comments, meta={"ID": ID}, callback=self.parse_Comments) # 去爬微博评论
def parse_information(self, response):
""" 抓取个人信息 """
informationItem = InformationItem()
selector = Selector(response)
ID = re.findall('(\d+)/info', response.url)[0]
try:
text1 = ";".join(selector.xpath('body/div[@class="c"]//text()').extract()) # 获取标签里的所有text()
nickname = re.findall('昵称[::]?(.*?);'.decode('utf8'), text1)
gender = re.findall('性别[::]?(.*?);'.decode('utf8'), text1)
place = re.findall('地区[::]?(.*?);'.decode('utf8'), text1)
briefIntroduction = re.findall('简介[::]?(.*?);'.decode('utf8'), text1)
birthday = re.findall('生日[::]?(.*?);'.decode('utf8'), text1)
sexOrientation = re.findall('性取向[::]?(.*?);'.decode('utf8'), text1)
sentiment = re.findall('感情状况[::]?(.*?);'.decode('utf8'), text1)
vipLevel = re.findall('会员等级[::]?(.*?);'.decode('utf8'), text1)
authentication = re.findall('认证[::]?(.*?);'.decode('utf8'), text1)
registime = re.findall('注册时间[::]?(.*?);'.decode('utf8'), text1)
url = re.findall('互联网[::]?(.*?);'.decode('utf8'), text1)
informationItem["_id"] = ID
if nickname and nickname[0]:
informationItem["NickName"] = nickname[0].replace(u"\xa0", "")
if gender and gender[0]:
informationItem["Gender"] = gender[0].replace(u"\xa0", "")
if place and place[0]:
place = place[0].replace(u"\xa0", "").split(" ")
informationItem["Province"] = place[0]
if len(place) > 1:
informationItem["City"] = place[1]
if briefIntroduction and briefIntroduction[0]:
informationItem["BriefIntroduction"] = briefIntroduction[0].replace(u"\xa0", "")
if birthday and birthday[0]:
try:
birthday = datetime.datetime.strptime(birthday[0], "%Y-%m-%d")
informationItem["Birthday"] = birthday - datetime.timedelta(hours=8)
except Exception:
informationItem['Birthday'] = birthday[0] # 有可能是星座,而非时间
if sexOrientation and sexOrientation[0]:
if sexOrientation[0].replace(u"\xa0", "") == gender[0]:
informationItem["SexOrientation"] = "同性恋"
else:
informationItem["SexOrientation"] = "异性恋"
if sentiment and sentiment[0]:
informationItem["Sentiment"] = sentiment[0].replace(u"\xa0", "")
if vipLevel and vipLevel[0]:
informationItem["VIPlevel"] = vipLevel[0].replace(u"\xa0", "")
if authentication and authentication[0]:
informationItem["Authentication"] = authentication[0].replace(u"\xa0", "")
if registime and registime[0]:
informationItem["Regist_time"] = authentication[0].replace(u"\xa0", "")
if url:
informationItem["URL"] = url[0]
try:
urlothers = "https://weibo.cn/attgroup/opening?uid=%s" % ID
r = requests.get(urlothers, cookies=response.request.cookies, timeout=5)
if r.status_code == 200:
selector = etree.HTML(r.content)
texts = ";".join(selector.xpath('//body//div[@class="tip2"]/a//text()'))
if texts:
num_tweets = re.findall('微博\[(\d+)\]'.decode('utf8'), texts)
num_follows = re.findall('关注\[(\d+)\]'.decode('utf8'), texts)
num_fans = re.findall('粉丝\[(\d+)\]'.decode('utf8'), texts)
if num_tweets:
informationItem["Num_Tweets"] = int(num_tweets[0])
if num_follows:
informationItem["Num_Follows"] = int(num_follows[0])
if num_fans:
informationItem["Num_Fans"] = int(num_fans[0])
except Exception as e:
pass
except Exception as e:
pass
else:
yield informationItem
yield Request(url="https://weibo.cn/%s/profile?filter=1&page=1" % ID, callback=self.parse_tweets, dont_filter=True)
yield Request(url="https://weibo.cn/%s/follow" % ID, callback=self.parse_FOF, dont_filter=True)
yield Request(url="https://weibo.cn/%s/fans" % ID, callback=self.parse_FOF, dont_filter=True)
def parse_tweets(self, response):
""" 抓取微博数据 """
selector = Selector(response)
ID = re.findall('(\d+)/profile', response.url)[0]
divs = selector.xpath('body/div[@class="c" and @id]')
for div in divs:
try:
tweetsItems = TweetsItem()
id = div.xpath('@id').extract_first() # 微博ID
content = div.xpath('div/span[@class="ctt"]//text()').extract() # 微博内容
cooridinates = div.xpath('div/a/@href').extract() # 定位坐标
like = re.findall('赞\[(\d+)\]'.decode('utf8'), div.extract()) # 点赞数
transfer = re.findall('转发\[(\d+)\]'.decode('utf8'), div.extract()) # 转载数
comment = re.findall('评论\[(\d+)\]'.decode('utf8'), div.extract()) # 评论数
others = div.xpath('div/span[@class="ct"]/text()').extract() # 求时间和使用工具(手机或平台)
tweetsItems["_id"] = ID + "-" + id
tweetsItems["ID"] = ID
if content:
tweetsItems["Content"] = " ".join(content).strip('[位置]'.decode('utf8')) # 去掉最后的"[位置]"
if cooridinates:
cooridinates = re.findall('center=([\d.,]+)', cooridinates[0])
if cooridinates:
tweetsItems["Co_oridinates"] = cooridinates[0]
if like:
tweetsItems["Like"] = int(like[0])
if transfer:
tweetsItems["Transfer"] = int(transfer[0])
if comment:
tweetsItems["Comment"] = int(comment[0])
if others:
others = others[0].split('来自'.decode('utf8'))
tweetsItems["PubTime"] = others[0].replace(u"\xa0", "")
if len(others) == 2:
tweetsItems["Tools"] = others[1].replace(u"\xa0", "")
yield tweetsItems
except Exception as e:
pass
url_next = selector.xpath('body/div[@class="pa" and @id="pagelist"]/form/div/a[text()="下页"]/@href'.decode('utf8')).extract()
if url_next:
yield Request(url=self.host + url_next[0], callback=self.parse_tweets, dont_filter=True)
def parse_FOF(self, response):
""" 抓取关注或粉丝 """
items = response.meta["item"]
selector = Selector(response)
text2 = selector.xpath(
u'body//table/tr/td/a[text()="\u5173\u6ce8\u4ed6" or text()="\u5173\u6ce8\u5979"]/@href').extract()
for elem in text2:
elem = re.findall('uid=(\d+)', elem)
if elem:
response.meta["result"].append(elem[0])
ID = int(elem[0])
if ID not in self.finish_ID: # 新的ID,如果未爬则加入待爬队列
self.scrawl_ID.add(ID)
url_next = selector.xpath(
u'body//div[@class="pa" and @id="pagelist"]/form/div/a[text()="\u4e0b\u9875"]/@href').extract()
if url_next:
yield Request(url=self.host + url_next[0], meta={"item": items, "result": response.meta["result"]},
callback=self.parse_FOF)
else: # 如果没有下一页即获取完毕
yield items
def parse_Comments(self,response):
""" 抓取微博评论 """
selector = Selector(response)
ID = re.findall('(\d+)/comment', response.url)[0]
try:
text = ";".join(selector.xpath('body/div[@class="c"]//text()').extract()) # 获取标签里的所有text()
comment_name = re.findall('<a\s*title=[^>]*usercard[^>]*>'.decode('utf8'),text) #获取并过滤出用户名
for n in range(0, len(comment_name)):
comment_name[n] = comment_name[n].split('\\"')[1]
comment_time = re.findall('WB_time S_func2[^>]*>[^>]*>'.decode('utf8'),text) #获取并过滤出评论时间
for t in range(0, len(comment_time)):
comment_time[t] = comment_time[t].split('>')[1].split('<')[0]
comment_content = re.findall(r'<p class=\\\"detail\\(.*?)<\\\/p>'.decode('utf8'),text) #获取并过滤出评论内容
for t in range(0, len(comment_content)):
a = comment_content[t].split("<\/a>")
b = a[len(a) - 1]
c = re.sub(r"<img(.*?)>", '[表情]', b) # 去掉图片表情
d = re.sub(r"<span(.*?)span>", '', c)
comment_content[t] = re.sub(r"\\t|:|:", '', d) # 去掉最后的/t和最前的冒号
CommentItem["ID"] = ID
if comment_name and comment_name[0]:
CommentItem["Comment_id"] = comment_name[0].replace(u"\xa0", "")
if comment_time and comment_time[0]:
CommentItem["Time"] = comment_time[0].replace(u"\xa0", "")
if comment_content and comment_content[0]:
CommentItem["Content"] = comment_content[0].replace(u"\xa0", "")
yield CommentItem
except Exception as e:
pass
url_next = selector.xpath(u'body//div[@class="pa" and @id="pagelist"]/form/div/a[text()="\u4e0b\u9875"]/@href').extract()
if url_next:
yield Request(url=self.host + url_next[0], callback=self.parse_Comments, dont_filter=True)
<file_sep>/**
* Created by luoyuyu on 2017/3/27.
*/
var express = require('express');
var router = express.Router();
router.get('/',function (req,res,next) {
res.render('welcome');
});
// 退出登陆操作
router.get('/req_signout',function (req,res,next) {
req.session.destroy();
res.json(['success','Sign out successfully!']);
});
module.exports = router;<file_sep>/**
* Created by luoyuyu on 2017/4/16.
*/
var hostIp = 'http://172.16.31.10:8000'; //固定的 -> 正式用
var api_key = '<KEY>'; //固定的 -> 正式用
var api_secret = '<KEY>';//固定的 -> 正式用
// var hostIp ='http://192.168.127.12:8000'; // 随机的 -> 测试用
// var api_key = '<KEY>'; //固定的 -> 测试用
// var api_secret = '<KEY>';//固定的 -> 测试用
var face= function (username,password) { //campare face
"use strict";
const faceppUrl = 'https://api-cn.faceplusplus.com/facepp/v3/compare'; //固定的
let image_url1 = hostIp+'/userImages/'+username+'0.png';//动态的 -> 这个可能会很不安全 0表示注册时的face信息
let image_url2 = hostIp+'/userImages/'+username+'1.png';//动态的 1表示登陆时采集的人脸信息
// console.log("face++开始认证人脸信息!");
// console.log(api_key);
// console.log(api_secret);
// console.log(image_url1);
// console.log(image_url2);
$.ajax({
type: 'POST',
url: faceppUrl,
data: {
api_key: api_key,
api_secret: api_secret,
image_url1: image_url1,
image_url2: image_url2
},
dataType: 'json',
success: function (data) {
if (data.confidence >= 80){ //阈值参数
// 是同一个人,授权登录系统
sweetAlert({
title: "认证成功!",
text: "正在登陆系统...",
type: "success",
allowEscapeKey: true,
allowOutsideClick: true,
showConfirmButton: false,
timer: 600
});
//ajax 发送请求更改后端用户 session
$.ajax({
url: 'signin/req_signin',
type: 'GET',
data: {
info :"sign in",
username:username,
password:<PASSWORD>,
},
dataType: 'json',
success: function(data){
//返回登陆成功信息。do something... ...
// console.log("返回登陆成功信息。do something... ...");
if (data[0] == 'success'){
//更改session成功后,进行页面跳转
location.href='/index'
}
else {
document.getElementById("signinDiv").className = "alert alert-danger";
document.getElementById("signinDiv").style.display = "block";
document.getElementById("signinDiv").innerHTML = `<strong>${data[1]}</strong>`;
setTimeout(function () {
document.getElementById("signinDiv").style.display = "none";
}, 2000);
}
},
error: function(jqXHR, textStatus, errorThrown){
// swal("网络错误!", "请检查网络连接后再试一次^_^!", "error")
}
});
}
else {
//不是同一个人,不授权
swal("认证失败", "请确认您是否有本账号的权限或调整角度重新认证", "error")
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("网络错误!", "请检查网络连接后再试一次^_^!", "error")
}
});
};
var signup_face= function (username,password,email) { //判断人脸信息是否合法
"use strict";
const faceppUrl = 'https://api-cn.faceplusplus.com/facepp/v3/detect'; //固定的
let image_url = hostIp+'/userImages/'+username+'0.png';//动态的 -> 这个可能会很不安全 0表示注册,1表示认证
$.ajax({
type: 'POST',
url: faceppUrl,
data: {
api_key: api_key,
api_secret: api_secret,
image_url: image_url,
return_attributes:'gender,age,smiling,headpose,facequality,blur,eyestatus'
},
dataType: 'json',
success: function (data) {
if (data.faces.length == 0){ //阈值参数 -> 没有检测出人脸信息
swal("注册失败", "请确认采集到您的人脸!", "error")
}
else { // 人脸信息注册成功——>将文本账号密码写入数据库
swal({
title: "人脸信息注册成功!",
text: "性别:" + data.faces[0].attributes.gender.value + " 年龄:" + data.faces[0].attributes.age.value,
type: "info",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true
}, function () {
// 点击OK,将文本账号密码写入数据库
//当判断注册的人脸信息符合要求,才会发送ajax将账号密码写入数据库
$.ajax({
url: 'signup/req_signup',
type: 'GET',
data: {
info: "sign up",
username: username,
password: <PASSWORD>,
email: email
},
dataType: 'json',
success: function (data) {
//返回注册信息。do something... ...
// console.log("返回注册信息",data);
if (data[0] == 'success') {
document.getElementById("signupDiv").className = "alert alert-success";
document.getElementById("signupDiv").style.display = "block";
document.getElementById("signupDiv").innerHTML = `<strong>${data[1]}</strong>`;
//在这个地方加入模态框
location.href = '/signin';
}
else {
swal({
title: "您注册的账号已经被使用!",
text: "请尝试别的账号^_^!",
type: "error",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true
},function () {
location.href='/signup';
});
document.getElementById("signupDiv").style.display = "block";
document.getElementById("signupDiv").innerHTML = `<strong>${data[1]}</strong>`;
setTimeout(function () {
document.getElementById("signupDiv").style.display = "none";
}, 2000);
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("网络错误!", "注册时网络错误!", "error")
}
});
});
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("网络错误!", "请检查网络连接后再重试一次^_^!", "error")
}
});
};<file_sep>var friendLists = function () {
//c初始化用户社交关系图谱
var user_rel = echarts.init(document.getElementById('user_rel'));
user_rel.setOption(option.user_relOption);
let user_friends;
$.ajax({
url: 'read/reptile',
type: 'GET',
data: {
info: "friendTable",
},
dataType: 'json',
success: function (data) {
//返回注册信息。do something... ...
// console.log("返回注册信息",data);
if (data[0] == 'success') {
user_friends = data[1];
console.log("user_friends->",user_friends)
$('#friend_table').bootstrapTable('destroy').bootstrapTable({
columns: [
{
field: 'order',
title: '序号',
sortable: true,
width: '12.5%'
},
{
field: 'screen_name',
title: '微博ID',
sortable: true,
width: '12.5%'
}, {
field: 'verified',
title: '微博关注者认证信息',
sortable: true,
width: '70%'
},{
radio: true,
width: '5%'
}
],
data: user_friends,
pagination: true,
search: true,
showColumns: true,
clickToSelect: true,
showToggle: true,
});
}
else {
swal("网络错误!", "网络错误!", "error")
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("网络错误!", "网络错误!", "error")
}
});
};
var fellowLists = function () {
let user_fellows = [];
$.ajax({
url: 'read/reptile',
type: 'GET',
data: {
info: "fellowTable",
},
dataType: 'json',
success: function (data) {
//返回注册信息。do something... ...
// console.log("返回注册信息",data);
if (data[0] == 'success') {
user_fellows = data[1];
$('#fellow_table').bootstrapTable('destroy').bootstrapTable({
columns: [
{
field: 'order',
title: '序号',
sortable: true,
width: '12.5%'
},
{
field: 'screen_name',
title: '微博ID',
sortable: true,
width: '12.5%'
}, {
field: 'verified',
title: '微博粉丝者认证信息',
sortable: true,
width: '70%'
},{
radio: true,
width: '5%'
}
],
data: user_fellows,
pagination: true,
search: true,
showColumns: true,
clickToSelect: true,
showToggle: true,
});
}
else {
swal("网络错误!", "网络错误!", "error")
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("网络错误!", "网络错误!", "error")
}
});
};
var weiboLists = function () {
let weibo_list = [];
$.ajax({
url: 'read/reptile',
type: 'GET',
data: {
info: "weiboTable",
},
dataType: 'json',
success: function (data) {
//返回注册信息。do something... ...
// console.log("返回注册信息",data);
if (data[0] == 'success') {
weibo_list = data[1];
$('#weibo_table').bootstrapTable('destroy').bootstrapTable({
columns: [
{
field: 'order',
title: '序号',
sortable: true,
width: '10%'
},
{
field: 'screen_name',
title: '微博ID',
sortable: true,
width: '10%'
}, {
field: 'text',
title: '微博内容',
sortable: true,
width: '48%'
},{
field: 'source',
title: '微博来源',
sortable: true,
width: '15%'
},
{
field: 'reposts_count',
title: '转发数',
sortable: true,
width: '10%'
},
{
field: 'comments_count',
title: '评论数',
sortable: true,
width: '10%'
},
{
radio: true,
width: '1%'
}
],
data: weibo_list,
pagination: true,
search: true,
showColumns: true,
clickToSelect: true,
showToggle: true,
});
}
else {
swal("网络错误!", "网络错误!", "error")
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("网络错误!", "网络错误!", "error")
}
});
};<file_sep>from scrapy import cmdline
cmdline.execute("scrapy crawl SinaSpider".split())<file_sep>/**
* Created by luoyuyu on 2017/4/18.
*/
let AppKey = '3196979142';
let AppSecret = '<KEY>';
// var getAccessToken = function(W){https://api.weibo.com/oauth2/access_token
// W.parseCMD('/friendships/friends/ids.json', function (oResult, bStatus) { //oResult:接口返回数据(JSON格式)
// if (bStatus) { //bStatus:接口返回状态,true - 接口正常、false - 接口异常
// //to do something...
// console.log("bStatus...");
// console.log("bStatus",bStatus);
// console.log("oResult",oResult)
// }
//
// }, {
// access_token: access_token // access_token ->要替换
// }, {
// method: 'get',
// cache_time: 30
// });
// };
//13402863568
// 50809217a
var screen_name;
var friends;
var fellows;
var weibo;
// 获取相关信息,用于规则计算
var getUserInfo = function (W,access_token,uid){
$.ajax({
url: 'https://api.weibo.com/2/users/show.json',
type: 'GET',
data: {
access_token :access_token,
uid: uid
},
dataType: 'jsonp',
success: function(data){
console.log("getUserInfo",data);
screen_name = data.data.screen_name;
console.log("screen_name",screen_name);
// 清空div内容,新增用户微博昵称
$('#connect_weibo').empty();
$('#connect_weibo').append(`微博昵称:${screen_name}`);
},
error: function(jqXHR, textStatus, errorThrown){
swal("网络错误!", "请检查网络连接后再试一次^_^!", "error")
}
});
// W.parseCMD('/users/show.json', function (oResult, bStatus) { //oResult:接口返回数据(JSON格式)
// if (bStatus) { //bStatus:接口返回状态,true - 接口正常、false - 接口异常
// //to do something...
// console.log("getUserInfo",oResult);
// screen_name = oResult.screen_name;
// console.log("screen_name",screen_name);
// }
//
// }, {
// access_token: access_token, // access_token ->要替换
// uid: uid
// }, {
// method: 'get',
// cache_time: 30
// });
};
var getFriendsInfo = function (W,access_token,uid) {
// 数据交互 -> 第三方与开放平台API接口进行数据请求的函数,必须在WB2.anyWhere中通过W对象调用
// W.parseCMD(uri, callback, args, opts)
$.ajax({
url: 'https://api.weibo.com/2/friendships/friends.json',
type: 'GET',
data: {
access_token :access_token,
uid: uid,
count: 200,//单页返回的记录条数,默认为50,最大不超过200。
},
dataType: 'jsonp',
success: function(data){
console.log("getFriendsInfo",data);
friends = data.data.users;
console.log("friends",friends);
friendLists(); // 把信息写入关注者列表
},
error: function(jqXHR, textStatus, errorThrown){
swal("网络错误!", "请检查网络连接后再试一次^_^!", "error")
}
});
};
var getFellowsInfo = function (W,access_token,uid) {
// 数据交互 -> 第三方与开放平台API接口进行数据请求的函数,必须在WB2.anyWhere中通过W对象调用
// W.parseCMD(uri, callback, args, opts)
$.ajax({
url: 'https://api.weibo.com/2/friendships/followers.json',
type: 'GET',
data: {
access_token :access_token,
uid: uid,
count: 200,//单页返回的记录条数,默认为50,最大不超过200。
},
dataType: 'jsonp',
success: function(data){
console.log("getFellowsInfo",data);
fellows = data.data.users;
console.log("fellows",fellows);
fellowLists(); //把信息写入粉丝列表
},
error: function(jqXHR, textStatus, errorThrown){
swal("网络错误!", "请检查网络连接后再试一次^_^!", "error")
}
});
};
var getWeibo = function (W,access_token,uid) {
// 数据交互 -> 第三方与开放平台API接口进行数据请求的函数,必须在WB2.anyWhere中通过W对象调用
$.ajax({
url: 'https://api.weibo.com/2/statuses/public_timeline.json',
type: 'GET',
data: {
access_token :access_token,
count:100
},
dataType: 'jsonp',
success: function(data){
//返回登陆成功信息。do something... ...
// console.log("返回登陆成功信息。do something... ...");
console.log("success...");
console.log("getWeibo",data);
weibo = data.data;
console.log("weibo",weibo);
weiboLists(); //把信息写入微博列表
},
error: function(jqXHR, textStatus, errorThrown){
swal("网络错误!", "请检查网络连接后再试一次^_^!", "error")
}
});
};<file_sep>var crypto = require("crypto");
var ciphter = crypto.createCipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
var s = "";
s += ciphter.update("aaa","utf8","hex");
s += ciphter.update("bbb","utf8","hex");
s += ciphter.update("ccc","utf8","hex");
s += ciphter.final("hex");
console.log(s);
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
var o = "";
var decipher = crypto.createDecipher("bf","luoyuyu-linkaiyi-changhongyan-hurui");
o += decipher.update(s,"hex","utf8");
o += decipher.final("utf8");
console.log(o); // aaabbbccc<file_sep>/**
* Created by luoyuyu on 2017/4/13.
*/
//这个文件定义了数据操作api的路由
var express = require('express');
var router = express.Router();
var fs=require('fs'); //文件操作
//创建子进程
const spawn = require('child_process').spawn;
/* GET api listing. */
router.get('/info_test',function (req,res,next) {
console.log("Deep Learning Run!",req.query.url);
let url = req.query.url;
const cPath = process.cwd() +'/model/model/Model.py';
// const p = `java -jar ${cPath} "${tableName}"`; //"${arr1}" "${arr2}"
// console.log(p);
const ls = spawn('python',[cPath,`${url}`]);
let result = '';
ls.stdout.on('data', (data) => {
result+=data;
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log("Deep Learning Output:",result);
console.log(`child process exited with code ${code}`);
});
});
router.get('/user_test',function (req,res,next) {
console.log("Deep Learning Run!",req.query.url);
let user_name = req.query.user_name;
const cPath = process.cwd() +'/model/model/Model.py';
// const p = `java -jar ${cPath} "${tableName}"`; //"${arr1}" "${arr2}"
// console.log(p);
const ls = spawn('python',[cPath,`${user_name}`]);
let result = '';
ls.stdout.on('data', (data) => {
result+=data;
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log("Deep Learning Output:",result);
console.log(`child process exited with code ${code}`);
});
});
router.get('/media_test',function (req,res,next) {
console.log("Deep Learning Run!",req.query.url);
let media_url = req.query.media_url;
const cPath = process.cwd() +'/model/model/Model.py';
// const p = `java -jar ${cPath} "${tableName}"`; //"${arr1}" "${arr2}"
// console.log(p);
const ls = spawn('python',[cPath,`${media_url}`]);
let result = '';
ls.stdout.on('data', (data) => {
result+=data;
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log("Deep Learning Output:",result);
console.log(`child process exited with code ${code}`);
});
});
module.exports = router;<file_sep>/**
* Created by luoyuyu on 2017/2/20.
*/
function functionOne(){
alert("成功加载");
}<file_sep>// var tencentyoutuyun = require('../../nodejs_sdk');
// var conf = tencentyoutuyun.conf;
// var youtu = tencentyoutuyun.youtu;
//
// var appid = '10081077';
// var secretId = '<KEY>';
// var secretKey = 'oonfNuGcm9OSK0c3IMPacTMm6FH8oLj1';
// var userid = '747350860';
//
// conf.setAppInfo(appid, secretId, secretKey, userid, 0);
//
// var img1 = '../userImages/lyy0.png';
// var img2 = '../userImages/lyy1.png';
//
// youtu.facecompare(img1,img2,function (data) {
// console.log(data);
// console.log(data.data.similarity);
// });
function myFace (username,password) {
var tencentyoutuyun = require('../../nodejs_sdk');
var conf = tencentyoutuyun.conf;
var youtu = tencentyoutuyun.youtu;
var appid = '10081077';
var secretId = '<KEY>';
var secretKey = 'oonfNuGcm9OSK0c3IMPacTMm6FH8oLj1';
var userid = '747350860';
conf.setAppInfo(appid, secretId, secretKey, userid, 0);
var img1 = '../userImages/'+username+'0.png';
var img2 = '../userImages/'+username+'1.png';
youtu.facecompare(img1,img2,function (data) {
console.log(data);
console.log(data.data.similarity);
if (data.data.similarity >= 80){ //阈值参数
// 是同一个人,授权登录系统
sweetAlert({
title: "认证成功!",
text: "正在登陆系统...",
type: "success",
allowEscapeKey: true,
allowOutsideClick: true,
showConfirmButton: false,
timer: 600
});
//ajax 发送请求更改后端用户 session
$.ajax({
url: 'signin/req_signin',
type: 'GET',
data: {
info :"sign in",
username:username,
password:<PASSWORD>,
},
dataType: 'json',
success: function(data){
//返回登陆成功信息。do something... ...
// console.log("返回登陆成功信息。do something... ...");
if (data[0] == 'success'){
//更改session成功后,进行页面跳转
location.href='/index'
}
else {
document.getElementById("signinDiv").className = "alert alert-danger";
document.getElementById("signinDiv").style.display = "block";
document.getElementById("signinDiv").innerHTML = `<strong>${data[1]}</strong>`;
setTimeout(function () {
document.getElementById("signinDiv").style.display = "none";
}, 2000);
}
},
error: function(jqXHR, textStatus, errorThrown){
// swal("网络错误!", "请检查网络连接后再试一次^_^!", "error")
}
});
}
else {
//不是同一个人,不授权
swal("认证失败", "请确认您是否有本账号的权限或调整角度重新认证", "error")
}
});
};
<file_sep>/**
* Created by luoyuyu on 2017/4/11.
*/
function btn_infoUlr_click () {
swal({
title: "您想检测该URL的微博虚假性吗?",
text: "URL...",
type: "info",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
},function () {
setTimeout(function(){
sweetAlert({
title: "Good Job!",
text: "您的请求成功!",
type: "success",
allowEscapeKey: true,
allowOutsideClick: true,
showConfirmButton: false,
timer: 600
});
}, 1000);
})
}<file_sep>var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser'); // POST 必要的模块
var urlencodedParser = bodyParser.urlencoded({
extended: false
}); // POST 必要的模块
/* GET home page. */
router.get('/', function(req, res, next) {
// res.sendFile(process.cwd() + '/public/html/welcome.html'); // process.cwd() -> /usr/../uploadFiles1.3
res.render('welcome');
});
router.get('/index',function (req,res,next) {
res.render('index');
});
router.get('/info_test',function (req,res,next) {
res.render('info_test');
});
router.get('/media_test',function (req,res,next) {
res.render('media_test');
});
router.get('/user_test',function (req,res,next) {
res.render('user_test');
});
router.get('/blank',function (req,res,next) {
res.render('blank');
});
module.exports = router;
<file_sep>/**
* Created by Winglau on 2016/11/21.
*/
var fs = require('fs');
var express = require('express');
var multer = require('multer');
var app = express();
var upload = multer({ dest: 'upload/' });
// 多图上传
app.post('/upload',upload.array('logo', 2) /*upload.single('logo')*/, function(req, res, next){
//res.send({ret_code: '0'});
console.log(req.files);
req.files.forEach(function(item){
var path1 = item.path;
var path2 = item.destination+item.originalname;
console.log(path1,path2);
res.send(
renameFile(path1,path2)
);
})
});
var renameFile =function(path1,path2){
fs.rename(path1,path2,function(){
console.log('done!');
})
}
app.get('/form', function(req, res, next){
var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
res.send(form);
});
app.listen(3000);<file_sep>/**
* Created by luoyuyu on 2017/3/27.
*/
var express = require('express');
var router = express.Router();
var fs=require('fs'); //文件操作
// var Canvas = require('canvas'); //需安装canvas模块
"use strict";
let db = require('../database/usersModel');
router.get('/',function (req,res,next) {
res.render('signup');
});
//这是给注册时->上传用户脸部照片
router.post('/req_snap',function (req,res,next) {
// let base64Data = req.body.snapData;
let tag = req.body.tag; //tag == 0;表示注册时的人脸信息; tag == 1; 表示登录时的人脸信息
let username = req.body.username;
console.log("username, req.body.username",username, req.body.username);
let picName = username+tag;
let imgData = req.body.snapData;
//过滤data:URL
let base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
let dataBuffer = new Buffer(base64Data, 'base64');
fs.writeFile("./public/userImages/"+picName+".png", dataBuffer, function(err) {
if(err){
res.send(err);
}else{
res.send("保存成功!");
}
});
// let img = new Canvas.Image;
// img.onload = function(){
// let w = img.width;
// let h = img.height;
// let canvas = new Canvas(w, h);
// let ctx = canvas.getContext('2d');
// ctx.drawImage(img, 0, 0);
// let out = fs.createWriteStream(process.cwd()+'/public/userImages' +'/'+username+tag+'.jpg');
// let stream = canvas.createJPEGStream({
// bufsize : 2048,
// quality : 80
// });
//
// stream.on('data', function(chunk){
// out.write(chunk);
// });
//
// stream.on('end', function(){
// out.end();
// res.send("上传成功!");
// });
// };
//
// img.onerror = function(err){
// res.send(err);
// };
//
// img.src = base64Data;
});
// 注册操作
router.get('/req_signup',function (req,res,next) {
console.log("sign up information:",req.query.info);
let username =req.query.username;
let password =req.query.password;
let email = req.query.email;
//根据用户名得到用户数量 ->如果用户名已经存在,则不允许用户继续注册
db.findOne({"username":username},function (err,results) {
if(err){
res.json(['err','网络错误^_^']);
console.log(err);
}else if(results){
res.json(['err','用户名已存在^_^']);
}else{
db.create({ // 创建一组user对象置入model
username: username,
password: <PASSWORD>,
email: email
},function(err,results){
if (err) {
res.json(['err','注册信息写入数据库失败^_^']);
console.log(err);
} else {
console.log(results);
res.json(['success','注册成功^_^']);
}
});
}
});
});
module.exports = router; | 812a3f457b6bc726e1e7fb51d491994cb1d66c36 | [
"JavaScript",
"Python"
]
| 26 | JavaScript | Thanksyy/2017dv-2.0 | 14aa8ea7b8820deb1c33fd2fea1d384f3b37cb95 | 7f4d6397d6a531f939e0cde13fe1b80d184eb4f5 |
refs/heads/main | <repo_name>millertim83/Calculator<file_sep>/README.md
# Calculator Application
<img width="342" alt="Screen Shot 2021-08-12 at 8 59 21 AM" src="https://user-images.githubusercontent.com/80060826/129201867-0d0d836a-8b00-4040-9ce0-540050a4807e.png">
I built this fully functional calculator using HTML, CSS, and JavaScript.
You can use the calculator [here](https://millertim83.github.io/Calculator/).
<file_sep>/script.js
let firstOperand = '';
let secondOperand = '';
let operator = ''
const clearButton = document.getElementById('clear-button');
const displayScreen = document.getElementById('display-screen');
clearButton.addEventListener('click', (e) => {
displayScreen.textContent = '0';
firstOperand = '';
operator = '';
secondOperand = ''
})
document.querySelectorAll('.numbers')
.forEach(numberButton => {
numberButton.addEventListener('click', () => {
const number = numberButton.textContent;
if (!operator) {
firstOperand += number;
displayScreen.textContent = firstOperand;
}
if (firstOperand && operator) {
secondOperand += number;
displayScreen.textContent = secondOperand;
}
});
});
const decimal = document.getElementById('decimal-button')
.addEventListener('click', (e) => {
if (firstOperand) {
firstOperand = handleDecimal(firstOperand);
displayScreen.textContent = firstOperand;
}
if (!firstOperand) {
firstOperand = handleDecimal(firstOperand);
displayScreen.textContent = firstOperand;
console.log(firstOperand);
} else if (firstOperand && operator) {
secondOperand = handleDecimal(secondOperand);
displayScreen.textContent = secondOperand;
console.log(secondOperand);
}
});
function handleDecimal(operand) {
const operandArray = operand.split('');
if (operandArray.indexOf('.') === -1) {
operandArray.push('.');
}
return operandArray.join('');
}
document.querySelectorAll('.operators')
.forEach(operatorButtons => {
operatorButtons.addEventListener('click', (e) => {
const selectedOperator = e.target.textContent;
if (firstOperand && operator && secondOperand) {
const result = calculateResult();
displayScreen.textContent = result;
firstOperand = result;
secondOperand = '';
}
if (firstOperand) {
operator = selectedOperator;
}
console.log(operator);
})
})
document.getElementById('equal-button')
.addEventListener('click', (e) => {
if (firstOperand && operator && secondOperand) {
const result = calculateResult();
firstOperand = result;
operator = '';
secondOperand = '';
displayScreen.textContent = result;
}
})
function calculateResult () {
switch (operator) {
case '+':
return add();
case '-':
return subtract();
case '/':
return divide();
case 'X':
return multiply();
}
}
function add() {
return `${trimDecimal(parseFloat(firstOperand) + parseFloat(secondOperand))}`;
}
function subtract() {
return `${trimDecimal(parseFloat(firstOperand) - parseFloat(secondOperand))}`;
}
function divide() {
return `${trimDecimal(parseFloat(firstOperand) / parseFloat(secondOperand))}`;
}
function multiply() {
return `${trimDecimal(parseFloat(firstOperand) * parseFloat(secondOperand))}`;
}
function trimDecimal(calculation) {
if (Number.isInteger(calculation)) {
return calculation;
} else {
return calculation.toFixed(3);
}
}
| f044148456889efe0f9f50cc34c8cbd48ed32cf1 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | millertim83/Calculator | 4130129574bfbf9c987c77d7d29b5d1da3204a48 | 65b2bdf786d12e62cb28c7c0856f38c0be5f68a1 |
refs/heads/main | <repo_name>Arahis/spaceX<file_sep>/src/redux/reducers/index.js
import { combineReducers } from 'redux'
import launchReducer from './launch-reducer'
const rootReducers = combineReducers({
launches: launchReducer,
})
export default rootReducers
<file_sep>/src/common/components/main-content/MainContent.js
import React, { useEffect, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Layout, Button } from "antd";
import { UnorderedListOutlined } from "@ant-design/icons";
import { fetchLaunch, fetchMoreLaunches } from "../../../redux/actions";
import { LaunchList } from "../launch-list";
import { pageSelector } from "../../../redux/selectors";
import { ErrorScreen } from "../error-screen";
const { Content } = Layout;
const MainContent = () => {
const dispatch = useDispatch();
const launchData = useSelector((state) => state.launches);
const error = useSelector((state) => state.launches.error);
const isLoading = useSelector((state) => state.launches.loading);
const page = useSelector(pageSelector);
const { upcoming, history } = launchData;
useEffect(() => {
dispatch(fetchLaunch());
}, [dispatch]);
const handleLoading = useCallback(() => {
dispatch(fetchMoreLaunches(page));
}, [dispatch, page]);
return (
<Content className="wrapper">
{error ? (
<ErrorScreen />
) : (
<>
<LaunchList title={"Upcoming"} launches={upcoming} />
<LaunchList title={"History"} launches={history} />
<div className="button-container">
<Button
icon={<UnorderedListOutlined />}
onClick={handleLoading}
className="fetch-button"
>
{isLoading ? "Loading..." : "Load more"}
</Button>
</div>
</>
)}
</Content>
);
};
export default MainContent;
<file_sep>/src/redux/selectors/index.js
import { prop, propOr } from "ramda";
import { createSelector } from "reselect";
const getLaunch = prop("launches");
const getPage = propOr(0, "page");
export const getLaunchData = createSelector(getLaunch);
export const pageSelector = createSelector(getLaunch, getPage);
<file_sep>/src/utils/api/index.js
import axios from "axios";
const fetchLaunches = async ({ order, sort, limit, offset }) => {
try {
const { data } = await axios.get(
`https://api.spacexdata.com/v3/launches/`,
{
params: {
order,
sort,
limit,
offset,
},
}
);
return { data };
} catch (error) {
return { error };
}
};
export { fetchLaunches };
<file_sep>/src/utils/dataConverter.js
import dayjs from "dayjs";
export const dataConverter = (value) => {
let newDate = dayjs(value).format("HH:mm:ssA YYYY");
let convertedDate = `${newDate} (UTC)`;
return convertedDate;
};
<file_sep>/src/App.js
import "./App.css";
import { Layout } from "antd";
import { NavBar } from "./common/components/nav-bar";
import { MainContent } from "./common/components/main-content";
function App() {
return (
<Layout>
<NavBar />
<MainContent />
</Layout>
);
}
export default App;
<file_sep>/src/common/components/launch-list/LaunchList.js
import React from "react";
import { Divider, Skeleton } from "antd";
import LaunchItem from "../launch-item/LaunchItem";
const LaunchList = ({ title, launches = [] }) => {
return (
<>
<Divider plain>{title}</Divider>
{launches.length ? (
launches.map((launch, index) => (
<LaunchItem key={index} launch={launch} />
))
) : (
<div>
<Skeleton active paragraph={{ rows: 2 }} />
<Skeleton active paragraph={{ rows: 2 }} />
<Skeleton active paragraph={{ rows: 2 }} />
</div>
)}
</>
);
};
export default LaunchList;
<file_sep>/src/common/components/nav-bar/NavBar.js
import React from "react";
import logo from "../../../assets/img/spacex_logo.png";
import avatar from "../../../assets/img/avatar.jpg";
import { Layout, Avatar, Image } from "antd";
const { Header } = Layout;
const NavBar = () => {
return (
<Header className="nav-bar">
<div className="logo">
<img src={logo} alt="logo" className="logo" />
</div>
<p className="header-text">Created by: <span className="text-bold">Dasha</span></p>
<Avatar
size={40}
src={<Image src={avatar} />}
/>
</Header>
);
};
export default NavBar;
<file_sep>/src/common/components/launch-item/index.js
export { default as LaunchItem } from "./LaunchItem";
<file_sep>/src/common/components/launch-list/index.js
export { default as LaunchList } from "./LaunchList";
<file_sep>/src/common/components/launch-item/LaunchItem.js
import React from "react";
import { Card, Typography, Skeleton } from "antd";
import { LinkOutlined, PlayCircleFilled } from "@ant-design/icons";
import { dataConverter } from "../../../utils/dataConverter";
const { Paragraph } = Typography;
const LaunchItem = ({ launch }) => {
const {
mission_name,
flight_number,
launch_success,
details,
links: { mission_patch, video_link, article_link },
} = launch;
let launchStatus;
switch (launch_success) {
case null:
launchStatus = "unknown";
break;
case true:
launchStatus = "success";
break;
case false:
launchStatus = "failure";
break;
default:
return;
}
const launchDate = dataConverter(launch.launch_date_utc);
return (
<Card style={{ height: "150px", marginTop: 16 }} className="wrapper">
<div className="img-container">
{mission_patch ? (
<img src={mission_patch} alt="mission_patch" />
) : (
<Skeleton.Image />
)}
</div>
<div className="info-container">
<div className="card-upper">
<p className="flight">#{flight_number}</p>
<p className="mission">{mission_name}</p>
<p className={`status ${launchStatus}`}>{launchStatus}</p>
<a
href={article_link}
className="article-link"
title="Link to the launch article"
>
<LinkOutlined />
</a>
</div>
<div className="card-lower">
<div className="card-lower__info">
<p className="date">
Launch Date: <b>{launchDate}</b>
</p>
<Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 0 }}>
{details
? details
: "Sorry, we do not have any info about this launch. But we are sure soon it will become available."}
</Paragraph>
</div>
<a href={video_link} className="video-link" title="Watch the video">
<PlayCircleFilled /> WATCH
</a>
</div>
</div>
</Card>
);
};
export default LaunchItem;
<file_sep>/src/common/styles/index.js
import "./antd/nav-bar.scss";
import "./antd/content-wrapper.scss";
import "./antd/card.scss";
import "./antd/fetch-button.scss";
import "./antd/error-container.scss";
<file_sep>/src/redux/index.js
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import createSagaMiddleware from "redux-saga";
import rootSaga from "./sagas";
import rootReducers from "./reducers";
const sagaMiddleware = createSagaMiddleware();
const middleware = [sagaMiddleware];
const store = createStore(
rootReducers,
composeWithDevTools(applyMiddleware(...middleware))
);
sagaMiddleware.run(rootSaga);
export { store };
<file_sep>/src/common/components/error-screen/ErrorScreen.js
import React from "react";
import server_img from "../../../assets/img/server_down.png";
const ErrorScreen = () => {
return (
<div className="error-container">
<img src={server_img} alt="server_down" />
<h3>
Ooops! Something went wrong. <br /> Please try again later.
</h3>
</div>
);
};
export default ErrorScreen;
<file_sep>/src/redux/sagas/fetch-launch-saga.js
import { call, put, takeEvery, takeLatest } from "redux-saga/effects";
import { setErrorPage, setLaunchData, isDataLoading } from "../actions";
import { fetchLaunches } from "../../utils/api";
import { FETCH_LAUNCH_DATA } from "../types";
import { FETCH_MORE_LAUNCHES } from "../types";
export function* fetchLaunchSaga({ payload: { page } = { page: 0 } }) {
yield put(isDataLoading());
const { data, error } = yield call(fetchLaunches, {
order: "desc",
sort: "launch_date_utc",
limit: 6,
offset: page * 6,
});
if (error) {
yield put(setErrorPage());
} else {
yield put(setLaunchData(...data));
}
}
export function* watchLaunchSaga() {
yield takeLatest(FETCH_LAUNCH_DATA, fetchLaunchSaga);
}
export function* watchLaunchMoreSaga() {
yield takeEvery(FETCH_MORE_LAUNCHES, fetchLaunchSaga);
}
<file_sep>/src/redux/types/index.js
export const SET_LAUNCH_DATA = "SET_LAUNCH_DATA";
export const FETCH_LAUNCH_DATA = "FETCH_LAUNCH_DATA";
export const FETCH_MORE_LAUNCHES = "FETCH_MORE_LAUNCHES";
export const SET_ERROR = "SET_ERROR";
export const IS_DATA_LOADING = "IS_DATA_LOADING";
<file_sep>/src/redux/actions/index.js
import { SET_LAUNCH_DATA } from "../types";
import { FETCH_LAUNCH_DATA } from "../types";
import { FETCH_MORE_LAUNCHES } from "../types";
import { SET_ERROR } from "../types";
import { IS_DATA_LOADING } from "../types";
export const fetchLaunch = () => ({
type: FETCH_LAUNCH_DATA,
});
export const isDataLoading = () => ({
type: IS_DATA_LOADING,
})
export const fetchMoreLaunches = (page) => ({
type: FETCH_MORE_LAUNCHES,
payload: {
page
}
});
export const setErrorPage = () => ({
type: SET_ERROR,
});
export const setLaunchData = (...data) => ({
type: SET_LAUNCH_DATA,
payload: {
data,
},
});
<file_sep>/src/redux/sagas/index.js
import { all, call } from "redux-saga/effects";
import { watchLaunchSaga, watchLaunchMoreSaga } from "./fetch-launch-saga";
export default function* rootSaga() {
yield all([call(watchLaunchSaga), call(watchLaunchMoreSaga)]);
}
<file_sep>/src/common/components/error-screen/index.js
export { default as ErrorScreen } from "./ErrorScreen"; | b643bae7cac75f8da1130d2a259ab30f241462b5 | [
"JavaScript"
]
| 19 | JavaScript | Arahis/spaceX | b8890cc603c48742404a70df02816a851a6a26d5 | e8bb0a38e8a90a424e0eea7ba5e538343d372c20 |
refs/heads/master | <repo_name>dmpots/codejam<file_sep>/2012/Q/D.py
#!/usr/bin/env python3
import sys
M= "#"
E= "."
I= "X"
class Board:
def __init__(self, w,h):
self.width = w
self.height = h
self.board = [["!"] * h for x in range(0,w)]
def __getitem__(self, x):
return self.board[x]
def __repr__(self):
s = ""
for y in range(self.height):
for x in range(self.width):
s += self[x][y]
s += "\n"
return s
class Ray:
def __init__(self, x,y,theta):
self.x = x
self.y = y
self.theta = theta
def main():
inp = sys.stdin
T = int(inp.readline())
for i in range(1, T+1):
prob = inp.readline().split()
H = int(prob[0])
W = int(prob[1])
D = int(prob[2])
B = Board(w=W, h=H)
for y in range(0, H):
line = inp.readline().rstrip()
for (x, c) in enumerate(line):
B[x][y] = c
if c == "X":
B.start = (x,y)
print(B.start)
sol = 9
print("Case #{}: {}".format(i, sol))
print(B)
sys.stdout.flush()
if __name__ == "__main__":
main()
<file_sep>/2014/Q/T.rb
#!/usr/bin/env ruby
#
require 'pp'
class Case
def initialize(i)
@i = i
end
def solve
"Case ##{@i}: "
end
end
def read_input(f)
cases = []
n = f.readline.to_i
(1..n).each do |i|
end
cases
end
if __FILE__ == $0
read_input($stdin).each do |c|
puts c.solve
end
end
<file_sep>/2009/Q/C.cc
#include <string>
#include <iostream>
using namespace std;
const char* target = "welcome to code jam";
const int tsize = 20;
char s[20] = {};
int solve(const string& line) {
int len = line.size();
int count = 0;
uint32_t max = 1 << len;
for(uint32_t config = 0; config <= max; config++) {
if(__builtin_popcount(config) != 19) continue;
bool good = true;
for(int i = 0, j = 0; i < len; i++) {
if((config >> i) & 1) {
if(target[j++] != line[i]) {good = false; break;}
//s[j++] = line[i];
}
}
if(good) {count++; if(count == 10000) count = 0;}
}
return count;
}
int solve2(const string& line) {
const int len = line.size();
const int tsize = 19;
int count = 0;
for(int w = 0; w < len; w++) {
if(line[w] != 'w' || len-w < tsize ) continue;
for(int e = w+1; e < len; e++) {
if(line[e] != 'e' || len-e < tsize) continue;
for(int l = e+1; l < len; l++) {
if(line[l] != 'l' || len-l < tsize) continue;
for(int c = l+1; c < len; c++) {
cout << c << endl;
if(line[c] != 'c' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
cout << " " << c << endl;
if(line[c] != 'o' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
cout << " " << c << endl;
if(line[c] != 'm' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'e' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != ' ' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 't' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'o' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != ' ' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'c' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'o' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'd' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'e' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != ' ' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'j' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'a' || len-c < tsize) continue;
for(int c = c+1; c < len; c++) {
if(line[c] != 'm' || len-c < tsize) continue;
else {count++; if(count > 10000)count=0;}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return count;
}
int main() {
int N;
string input;
cin >> N;
getline(cin, input);
for(int i = 1; i <= N; ++i) {
getline(cin, input);
int count = solve(input);
cout << "Case #" << i << ": ";
if(count < 1000) cout << '0';
if(count < 100) cout << '0';
if(count < 10) cout << '0';
cout << count << endl;
}
}
<file_sep>/2014/Q/B.rb
#!/usr/bin/env ruby
#
require 'pp'
class Case
def initialize(i, c, f, x)
@i = i
@c = c
@f = f
@x = x
end
def cook_time(rate, needed)
needed / rate
end
def farm_time(rate)
@c / rate
end
def cookies(rate, elapsed_time)
rate * elapsed_time
end
def greedy
times = []
cookies = 0
rate = 2.0
while cookies < @x
remaining = @x - cookies
next_cook_time = cook_time(rate, remaining)
next_farm_time = farm_time(rate) + cook_time(rate+@f, remaining+@c-(cookies(rate, farm_time(rate))))
if next_cook_time < next_farm_time
#puts "cook"
cookies += remaining
times << next_cook_time
else
#puts "farm"
cookies += -@c + (farm_time(rate) * rate)
times << farm_time(rate)
rate += @f
end
end
#puts times
times.reduce(:+)
end
def solve
sprintf "Case ##{@i}: %.7f", greedy
end
end
def read_input(f)
n = f.readline.to_i
(1..n).map do |i|
c,ff,x = f.readline.split
Case.new(i, c.to_f, ff.to_f, x.to_f)
end
end
if __FILE__ == $0
read_input($stdin).each_with_index do |c,i|
#pp c
puts c.solve
end
end
<file_sep>/2014/Q/D.py
#!/usr/bin/env python3
import sys
import pprint
def log(msg):
#print(msg)
pass
def pp(d):
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(d)
def kens_move(kens_blocks, naomi_choice):
if naomi_choice > kens_blocks[0]:
return kens_blocks[-1]
kbr = kens_blocks[:]
kbr.reverse()
for block in kbr:
if block > naomi_choice:
return block
def points_scored(ken, naomi):
if naomi > ken:
return 1
return 0
def naomi_war(naomi_blocks, ignored):
return naomi_blocks[0],naomi_blocks[0]
def naomi_dwar(naomi_blocks, ken_blocks):
if naomi_blocks[-1] < ken_blocks[-1]:
return naomi_blocks[-1],ken_blocks[0]-0.000001
else:
return naomi_blocks[-1],ken_blocks[0]+0.000001
def trace(k, n, p, score):
log("K={} N={} P={} S={}".format(k, n, p, score))
class Case:
def __init__(self, i, naomi, ken):
self.i = i
self.naomi = naomi
self.ken = ken
def run_game(self, naomi_strategy):
score = 0
naomi_blocks = self.naomi[:]
ken_blocks = self.ken[:]
for i in range(1, len(self.ken)+1):
naomi_chosen,naomi_told = naomi_strategy(naomi_blocks, ken_blocks)
ken_chosen = kens_move(ken_blocks, naomi_told)
point = points_scored(ken_chosen, naomi_chosen)
score += point
trace(ken_chosen, naomi_chosen, point, score)
naomi_blocks.remove(naomi_chosen)
ken_blocks.remove(ken_chosen)
return score
def solve(self):
dwar_points = 0
war_points = self.run_game(naomi_war)
log("WAR: {}".format(war_points))
dwar_points = self.run_game(naomi_dwar)
sol = "{} {}".format(dwar_points, war_points)
return "Case #{}: {}".format(self.i, sol)
def __repr__(self):
return "Case #{}: n={}, k={}".format(self.i, self.naomi, self.ken)
def parse_blocks(line):
return sorted(list(map(float, line.split())), reverse=True)
def parse_input(stream):
cases = []
N = int(stream.readline())
for i in range(1, N+1):
stream.readline()
naomi = parse_blocks(stream.readline())
ken = parse_blocks(stream.readline())
cases.append(Case(i, naomi, ken))
return cases
def main():
cases = parse_input(sys.stdin)
#pp(cases)
for case in cases:
print(case.solve())
if __name__ == "__main__":
main()
<file_sep>/2008/1/B.py
#!/usr/bin/env python3
import sys
class Solution(Exception):
def __init__(self, assignment):
self.assignment = assignment
def solve(clauses):
try:
dpll({}, clauses)
except Solution as sol:
return sol.assignment
return None
def dpll(assignment, clauses):
if len(clauses) == 0:
raise Solution(assignment)
# check unsolvable clauses
for clause in clauses:
if len(clause) == 0:
return False
# check forced assignments
forced = []
for clause in clauses:
if len(clause) == 1:
forced.append(clause[0])
for (flavor, value) in forced:
#print("F")
(clauses, assignment) = assign(assignment, clauses, flavor, value)
# check pure assignmetns
pure = set()
ways = {}
for clause in clauses:
for flavor,value in clause:
pure.add(flavor)
ways[flavor] = value
for clause in clauses:
for flavor,value in clause:
if ways[flavor] != value and flavor in pure:
pure.remove(flavor)
#for flavor in pure:
# print("P")
# (clauses, assignment) = assign(assignment, clauses, flavor, ways[flavor])
if len(clauses) == 0:
raise Solution(assignment)
for clause in clauses:
if len(clause) == 0:
return False
# assign least malted flavor
#print("C")
nmcounts = {}
mcounts = {}
for clause in clauses:
for (flavor, malted) in clause:
if malted:
mcounts[flavor] = mcounts.get(flavor,0) + 1
else:
nmcounts[flavor] = nmcounts.get(flavor,0) + 1
oc, oa = clauses, assignment
if len(nmcounts) > 0:
(flavor,_c) = max(nmcounts.items(), key=lambda c: c[1])
clauses,assignment = assign(assignment, clauses, flavor, False)
if not dpll(assignment, clauses):
clauses,assignment = assign(oa, oc, flavor, True)
return dpll(assignment, clauses)
else:
(flavor,_c) = max(mcounts.items(), key=lambda c: c[1])
clauses,assignment = assign(assignment, clauses, flavor, True)
if not dpll(assignment, clauses):
clauses,assignment = assign(oa, oc, flavor, False)
return dpll(assignment, clauses)
return False
def assign(assignment, clauses, flavor, value):
newA = assignment.copy()
newC = []
newA[flavor] = value
for clause in clauses:
c = []
erase = False
for f,v in clause:
# remove clause if it is satisfied
if f == flavor and v == value:
erase = True
# remove term if it is negated
elif (f == flavor) and (v == (not value)):
pass
# otherwise let it be
else:
c.append((f,v))
if not erase:
newC.append(c)
#print("A({}) = {}: {}".format(flavor, value, newA))
return newC,newA
def main():
ifp = sys.stdin
ofp = sys.stdout
C = int(ifp.readline())
for c in range(1, C+1):
#if c == 44:
# print(" ".join(ifp.readlines()[:15]))
N = int(ifp.readline())
M = int(ifp.readline())
clauses = []
for i in range(0, M):
customer = ifp.readline().split()
T = int(customer.pop(0))
clause = []
for x in range(0, T):
X = int(customer.pop(0))
Y = bool(int(customer.pop(0)))
clause.append((X,Y))
clauses.append(clause)
sol = solve(clauses)
if sol:
print("Case #{}: ".format(c), end="",file=ofp)
for f in range(1, N+1):
if f in sol:
print(int(sol[f]),end=" ",file=ofp)
else:
print(0, end=" ",file=ofp)
print()
else:
print("Case #{}: {}".format(c, "IMPOSSIBLE"), file=ofp)
ofp.flush()
if __name__ == "__main__":
main()
<file_sep>/2013/Q/B.rb
#!/usr/bin/env ruby
require 'pp'
class Board
def initialize(i, board)
@board = board
@N = i
end
def result
head = "Case ##{@N}:"
end
end
def read_input(f)
boards = []
tT = f.readline.to_i
(1..tT).each do |t|
n,m = f.readline.split.map{|i| i.to_i}
board = []
(1..n).each do
board << f.readline.chomp.split
end
boards << Board.new(t, board)
end
pp boards
end
if __FILE__ == $0
boards = read_input($stdin)
boards.each do |b|
puts b.result
end
end
<file_sep>/2008/1/C.py
#!/usr/bin/env python3
import sys
import math
s5 = 22360679774997896964091736687312762354406183596115257242708972454105209256378048994144144083787822750
sig = 10**100
def mul(x,y):
const = x[0]*y[0] + x[1]*y[1] * 5
sqrt = x[0] * y[1] + x[1] * y[0]
(_,const) = divmod(const, sig)
(_,sqrt) = divmod(sqrt, sig)
return [const, sqrt]
def fast(n, x):
s = 1
while (s*2) < n:
x = mul(x,x)
s = s * 2
#print("S: "+str(s)+" R: "+str(n-s))
return (n-s, x)
def expand(x):
#print("E")
b,a = divmod((x[1] * sig * s5), sig*sig)
b = b + x[0]
#print("X: ",x,"A: ",a, "B: ",b)
bs = str(b)
digs = bs[-3:]
digs = "0"*(3-len(digs))+digs
return digs
def solve(n):
x = [3, 1]
first = True
while n > 0:
#print("N: "+str(n))
n,y = fast(n,[3,1])
if first:
first = False
x = y
else:
x = mul(x,y)
return expand(x)
def main():
ifp = sys.stdin
ofp = sys.stdout
N = int(ifp.readline())
for (i,line) in enumerate(ifp, start=1):
n = int(line)
sol = solve(n)
print("Case #{}: {}".format(i, sol), file=ofp)
ofp.flush()
if __name__ == "__main__":
main()
<file_sep>/2009/Q/B.py
#!/usr/bin/env python3
import sys
def solve(W,H, em):
dm = []
sol = []
for r in range(0,H):
sol.append([])
dm.append([])
for c in range(0,W):
dm[r].append(-1)
sol[r].append(-1)
basin = 0
for r in range(0,H):
for c in range(0,W):
e = em[r][c]
elevs = [e]
# N
if r != 0:
elevs.append(em[r-1][c])
# S
if r != H-1:
elevs.append(em[r+1][c])
# E
if c != W-1:
elevs.append(em[r][c+1])
# W
if c != 0:
elevs.append(em[r][c-1])
if min(elevs) == e:
dm[r][c] = basin
basin += 1
for row in range(0,H):
for col in range(0,W):
pos = row,col
d = dm[row][col]
while d < 0:
r,c = pos
e = em[r][c]
ne = 10000
#N
if r != 0 and em[r-1][c] < ne:
pos = r-1,c
ne = em[r-1][c]
d = dm[r-1][c]
#W
if c != 0 and em[r][c-1] < ne:
pos = r,c-1
ne = em[r][c-1]
d = dm[r][c-1]
#E
if c != W-1 and em[r][c+1] < ne:
pos = r,c+1
ne = em[r][c+1]
d = dm[r][c+1]
#S
if r != H-1 and em[r+1][c] < ne:
pos = r+1,c
ne = em[r+1][c]
d = dm[r+1][c]
sol[row][col] = d
lex = {}
i = 0
for r in range(0,H):
for c in range(0,W):
if sol[r][c] not in lex:
lex[sol[r][c]] = chr(97+i)
i += 1
sol[r][c] = lex[sol[r][c]]
return sol
def main():
ifp = sys.stdin
ofp = sys.stdout
N = int(ifp.readline())
for i in range(1,N+1):
H,W = map(int, ifp.readline().split())
em = []
for j in range(0,H):
row = list(map(int, ifp.readline().split()))
em.append(row)
print("Case #{}:".format(i))
sol = solve(W,H,em)
for row in sol:
print(' '.join(map(str,row)), file=ofp)
ofp.flush()
if __name__ == "__main__":
main()
<file_sep>/2008/1/A.py
#!/usr/bin/env python3
import sys
def dotp(xs, ys):
return sum([x * y for (x,y) in zip(xs,ys)])
def solve(xs, ys):
return dotp(sorted(xs), sorted(ys, reverse=True))
def main():
ifp = sys.stdin
ofp = sys.stdout
T = int(ifp.readline())
for i in range(1, T+1):
n = ifp.readline()
xs = map(int, ifp.readline().split())
ys = map(int, ifp.readline().split())
sol = solve(xs, ys)
print("Case #{}: {}".format(i, sol), file=ofp)
ofp.flush()
if __name__ == "__main__":
main()
<file_sep>/2014/1A/B.py
#!/usr/bin/env python3
import sys
import pprint
import argparse
import collections
from operator import attrgetter, methodcaller, itemgetter
debug = False
def log(msg, *args):
global debug
if debug:
print(msg.format(*args))
def parse_args():
parser = argparse.ArgumentParser(description='Google CodeJam Template')
parser.add_argument('-d', '--debug', action='store_true',
help='print debugging messages')
parser.add_argument('-c', '--case', metavar='N', type=int,
help='only run case N (default: run them all)')
args = parser.parse_args()
if args.debug:
global debug
debug = True
return args
class Tree:
def __init__(self, node):
self.node = node
self.children = []
def print_tree(tree):
print("{}({})".format(tree.node, tree.size))
for child in tree.children:
print(" {}({})".format(child.node, child.size))
for child in tree.children:
print_tree(child)
def build_tree(root, edges):
def dfs(node, visited):
visited.add(node)
n = Tree(node)
children = []
for child in edges[node]:
if child not in visited:
n.children.append(dfs(child, visited))
n.size = 1 + sum(map(lambda c: c.size, n.children))
return n
def bfs(rootnode):
queue = collections.deque()
tree = Tree(rootnode)
queue.append(tree)
visited = set([rootnode])
while len(queue) > 0:
n = queue.popleft()
for child in edges[n.node]:
if not child in visited:
c = Tree(child)
n.children.append(c)
queue.append(c)
visited.add(child)
return tree
def annotate_size(tree):
size = 1
for c in tree.children:
annotate_size(c)
size += c.size
tree.size = size
tree = bfs(root)
annotate_size(tree)
return tree
#return dfs(root, set())
def balanced_tree_size(root):
def dfs(node):
log("N: {}", node.node)
if len(node.children) == 0 or len(node.children) == 1:
return 1
cs = [dfs(c) for c in node.children]
cs.sort(reverse=True)
return 1 + cs[0] + cs[1]
#cs = [(c.size, dfs(c)) for c in node.children]
#cs.sort(key=lambda x: (x[0], x[0]-x[1]), reverse=True)
#return cs[0][1] + cs[1][1] + sum(map(itemgetter(0), cs[2:]))
#childs = sorted(node.children, key=attrgetter('size'), reverse=True)
#return dfs(childs[0]) + dfs(childs[1]) + sum(map(attrgetter('size'), childs[2:]))
return dfs(root)
class Case:
def __init__(self, i, edges):
self.i = i
self.edges = edges
def solve(self):
log("Solving: {}", self)
counts = []
num_nodes = len(self.edges.keys())
for n in self.edges.keys():
tree = build_tree(n, self.edges)
size = balanced_tree_size(tree)
#print_tree(tree)
log("####{}",size)
counts.append(num_nodes - size)
sol = str(min(counts))
return self.case() + sol
def case(self):
return "Case #{}: ".format(self.i)
def __repr__(self):
return self.case() + str(self.edges)
def parse_input(stream):
cases = []
T = int(stream.readline())
for i in range(1, T+1):
N = int(stream.readline())
edges = collections.defaultdict(list)
for j in range(N-1):
n1,n2 = map(int, stream.readline().split())
edges[n1].append(n2)
edges[n2].append(n1)
# parse case input
cases.append(Case(i, edges))
return cases
def main():
sys.setrecursionlimit(1500)
options = parse_args()
cases = parse_input(sys.stdin)
for case in cases:
if not options.case or options.case == case.i:
print(case.solve())
sys.stdout.flush()
main()
<file_sep>/2014/Q/C.rb
#!/usr/bin/env ruby
#
require 'pp'
require 'set'
class Integer
def fact
(1..self).reduce(:*) || 1
end
end
class Board
def initialize(rows, cols, mines)
@rows = rows
@cols = cols
@mines = mines
@board = []
@rows.times {@board << []}
fill_empty
place_mines
#puts "BOARD"
#puts self
#puts "BOARD"
end
def fill_empty
@rows.times {|r| @cols.times {|c| @board[r][c] = 'x'}}
end
def place_mines
mines = @mines
ul = [0,0]
ur = [0,@cols-1]
br = [@rows-1, @cols-1]
bl = [@rows-1, 0]
while mines > 0
#puts "BOARD:"
#puts self
cells = optimial_order(outer_box(ul, ur, bl, br), mines)
take = [mines, cells.size].min
allocate = cells[0...take]
allocate.each do |cell|
r,c = cell
@board[r][c] = "*"
end
mines -= take
ul = ul[0]+1,ul[1]+1
ur = ur[0]+1,ur[1]-1
br = br[0]-1,br[1]-1
bl = bl[0]-1,bl[1]+1
end
end
def optimial_order(cells, mines)
return cells.to_a if mines > cells.size
return_order = []
order = cells.to_a.reverse
saved_board = clone_board
last = nil
needed_mines = mines
while needed_mines > 0 and not order.empty?
last = order.pop
return_order << last
@board[last[0]][last[1]] = "*"
needed_mines -= 1
end
ordered_board = clone_board
#puts "BB"
#puts self
solved = solve
if not solved and last
return_order.pop
@board = ordered_board
@board[last[0]][last[1]] = "x"
last_board = clone_board
choices = []
(0...@rows).each {|r| (0...@cols).each {|c| choices << [r,c] if @board[r][c] == "x"}}
#choices = (order - return_order)
#puts "CHOICES: #{choices}"
choices.each do |cell|
#puts "CHOOSE: #{cell}"
@board = last_board.map {|r| r.clone}
r,c = cell
@board[r][c] = "*"
#puts "B"
#puts self
if solve
#puts "SOLVED"
return_order << cell
break
end
#puts "S"
#puts self
end
end
#puts "DONE"
@board = saved_board
if return_order.size < mines
return cells.to_a
end
return return_order
end
def optimial_order2(cells, mines)
return cells.to_a if mines > cells.size
saved_board = clone_board
order = try_cells(cells.to_a, mines)
@board = saved_board
if not order or order.size < mines
#puts "FAILED TO FIND OPTIMIAL ORDER"
return cells.to_a
end
return order
end
def try_cells(cells, mines)
#puts "TRY CELLS"
#puts self
if cells.empty? or mines == 0
return cells if solved?
return nil
end
#puts "TRYING: #{cells}"
initial_board = clone_board
cells = cells.reject do |cell|
r,c = cell
@board[r][c] = "*"
#puts "B: #{cell}"
#puts self
solved = solve
@board = initial_board.map {|r| r.clone}
#puts "B: #{cell} -- #{solved}"
#puts self
not solved
end
#puts "PRUNED: #{cells}"
return nil if cells.size < mines
cells.each_with_index do |cell,i|
#puts "CELL: #{cell}"
#puts self
r,c = cell
@board[r][c] = "*"
solved = solve
@board = initial_board.map {|r| r.clone}
@board[r][c] = "*"
if solved
#puts "SOLVED: #{cell}"
#puts self
sub_order = try_cells(cells[0...i] + cells[i+1...cells.size], mines - 1)
if sub_order
#puts "SUB_SOLVED: #{sub_order}"
#puts self
return [cell] + sub_order if sub_order
end
end
#puts "NO LUCK"
@board[r][c] = "x"
#puts self
end
@board = initial_board
#puts "FAILED"
return nil
end
def optimial_order1(cells, mines)
return cells.to_a if mines > cells.size
order = []
orig_board = clone_board
remaining_cells = cells.to_a
solved = true
#puts "Remaining: #{cells.to_a}"
backtracks, bt_limit = 0,100
while remaining_cells.size > 0 and mines > 0 and solved
solved = false
max_cell = remaining_cells.first
remaining_cells.each do |cell|
r,c = cell
@board[r][c] = "*"
before_solve = clone_board
#puts "Before Solve: "
#puts self
if solve
max_cell = cell
#puts "Solved:"
solved = true
#puts self
@board = before_solve
break
end
@board = before_solve
#puts "Restored: "
#puts self
@board[r][c] = "x"
end
if not solved and backtracks < bt_limit and not order.empty?
backtracks += 1
solved = true
bt = order.sample
order.delete(bt)
#puts "BT: #{bt}"
#puts self
@board[bt[0]][bt[1]] = "x"
remaining_cells << bt
mines += 1
else
order << max_cell
#puts "BS: #{solved}"
#puts self
@board[max_cell[0]][max_cell[1]] = "*"
mines -= 1
remaining_cells.delete(max_cell)
end
#puts self
end
order += remaining_cells.to_a
@board = orig_board
#puts order
order
end
def zeros
(0...@rows).map {|r| (0...@cols).map{|c| zero([r,c])}.count(true)}.reduce(:+)
#@board.map{|r| r.map{|cell| zero(cell)}.count(true)}.reduce(:+)
end
def outer_box(ul, ur, bl, br)
cells = Set.new([ul, ur, bl, br])
cell = ul
while cell != ur
cells << cell
cell = cell[0],cell[1]+1
end
while cell != br
cells << cell
cell = cell[0]+1,cell[1]
end
while cell != bl
cells << cell
cell = cell[0],cell[1]-1
end
while cell != ul
cells << cell
cell = cell[0]-1,cell[1]
end
cells
end
def place_mines_1
mines = @mines
r,c = 0,0
r_n,c_n = 0,1
r_ur,c_ur = 0, @cols-1
r_br,c_br = @rows-1, @cols-1
r_bl,c_bl = @rows-1, 0
r_ul,c_ul = 0,0
while mines > 0
#puts self
#puts ""
@board[r][c] = "*"
mines -= 1
if r == r_ur and c == c_ur
#puts "A"
r = r+1
r_n = 1
c_n = 0
elsif r == r_br and c == c_br
#puts "B"
c = c-1
r_n = 0
c_n = -1
elsif r == r_bl and c == c_bl
#puts "C"
r = r-1
r_n = -1
c_n = 0
else
#puts "D"
r += r_n
c += c_n
end
if r == r_ul and c == c_ul
#puts "E", r, c
r = r + 1
c = c + 1
r_n, c_n = 0,1
r_ul,c_ul = r_ul+1, c_ul+1
r_ur,c_ur = r_ur+1, c_ur-1
r_br,c_br = r_br-1, c_br-1
r_bl,c_bl = r_bl-1, c_bl+1
end
end
end
def to_s
s = ""
@rows.times do |r|
@cols.times do |c|
s << @board[r][c]
end
s << "\n"
end
s
end
def solve
starting_clicks = []
@board.each_with_index do |row,r|
row.each_with_index do |v,c|
starting_clicks << [r,c] if v == "x"
end
end
solved = false
while starting_clicks.size > 0 and not solved?
orig_board = clone_board
play_click(starting_clicks.pop)
#puts "CLICK:"
#puts self
@board = orig_board unless solved?
end
return solved?
end
def solved?
@board.map{|r| not r.include?("x")}.reduce(:&)
end
def clone_board
@board.map {|r| r.clone}
end
def play_click(start_click)
visited = Set.new(start_click)
worklist = [start_click]
while not worklist.empty?
#puts "#{worklist}"
cell = worklist.pop
visited.add(cell)
r,c = cell
#puts "#{cell}"
#puts "#{neighbors(cell)}"
if cell == start_click
@board[r][c] = "c"
else
@board[r][c] = "."
end
if zero(cell)
neighbors(cell).each do |n|
nr,nc = n
if @board[nr][nc] != "*" and not visited.include?(n)
worklist.push(n)
end
end
end
end
end
def zero(cell)
neighbors(cell).map {|r,c| @board[r][c] != "*"}.reduce(:&)
end
def neighbors(cell)
r,c = cell
[
[r-1,c-1],[r-1,c],[r-1,c+1],
[r,c-1] , [r,c+1],
[r+1,c-1],[r+1,c],[r+1,c+1]
].reject{|r,c| r < 0 or c < 0 or r > @rows-1 or c > @cols-1}
end
end
class Case
attr_reader :board
def initialize(i, rows, cols, mines)
@i = i
@rows = rows
@cols = cols
@mines = mines
@board = Board.new(rows,cols,mines)
end
def solve
#puts @board
@board.solve
result = "Case ##{@i}:\n"
if @board.solved?
result << @board.to_s
else
result << "Impossible"
end
end
end
def read_input(f)
n = f.readline.to_i
(1..n).map do |i|
rows,cols,mines = f.readline.split
Case.new(i, rows.to_i, cols.to_i, mines.to_i)
end
end
if __FILE__ == $0
read_input($stdin).each_with_index do |c,i|
#pp c
puts c.solve
#puts c.board
end
end
<file_sep>/2009/Q/A.py
#!/usr/bin/env python3
import sys
def solve(words, prob):
cnt = 0
for w in words:
for (i,c) in enumerate(w):
if c not in prob[i]:
break
else:
cnt += 1
return cnt
def main():
ifp = sys.stdin
ofp = sys.stdout
L,D,N = map(int, ifp.readline().split())
words = set()
for i in range(0, D):
words.add(ifp.readline().rstrip())
for i in range(1, N+1):
pattern = ifp.readline().rstrip()
prob = []
c = 0
state = 0
for c in pattern:
if c == "(":
state = 1
prob.append("")
elif c == ")":
state = 0
else:
if state == 0:
prob.append(c)
elif state == 1:
prob[-1] += c
#print(prob)
sol = solve(words, prob)
print("Case #{}: {}".format(i, sol), file=ofp)
ofp.flush()
if __name__ == "__main__":
main()
<file_sep>/2014/Q/T.py
#!/usr/bin/env python3
import sys
import pprint
def pp(d):
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(d)
class Case:
def __init__(self, i, data):
self.i = i
self.data = data
def solve(self):
sol = ""
return "Case #{}: {}".format(self.i, sol)
def __repr__(self):
return "Case #{}: {}".format(self.i, self.data)
def parse_input(stream):
cases = []
for (i, line) in enumerate(stream, 1):
line = line.rstrip()
cases.append(Case(i, line.split()))
return cases
def main():
cases = parse_input(sys.stdin)
pp(cases)
for case in cases:
print(case.solve())
if __name__ == "__main__":
main()
<file_sep>/2008/1/Makefile
CC=clang++
P=A
A: A.cc
$(CC) $^ -o $@
B: B.cc
$(CC) $^ -o $@
C: C.cc
$(CC) $^ -o $@
<file_sep>/2014/Q/A.rb
#!/usr/bin/env ruby
#
require 'pp'
require 'set'
class Case
def initialize(i, row1, board1, row2, board2)
@i = i
@row1 = Set.new board1[row1-1]
@row2 = Set.new board2[row2-1]
end
def solve
res = @row1 & @row2
"Case ##{@i}: " +
case res.size
when 0 then "Volunteer cheated!"
when 1 then res.first
else "Bad magician!"
end
end
end
def read_input(f)
boards = []
n = f.readline.to_i
(1..n).each do |i|
row1 = f.readline.to_i
board1 = []
board1 << f.readline.chomp.split
board1 << f.readline.chomp.split
board1 << f.readline.chomp.split
board1 << f.readline.chomp.split
row2 = f.readline.to_i
board2 = []
board2 << f.readline.chomp.split
board2 << f.readline.chomp.split
board2 << f.readline.chomp.split
board2 << f.readline.chomp.split
boards << Case.new(i, row1, board1, row2, board2)
end
boards
end
if __FILE__ == $0
read_input($stdin).each do |c|
#pp c
puts c.solve
end
end
<file_sep>/templates/T.py
#!/usr/bin/env python3
import sys
import pprint
import argparse
from operator import attrgetter, methodcaller, itemgetter
debug = False
def log(msg, *args):
global debug
if debug:
print(msg.format(*args))
def parse_args():
parser = argparse.ArgumentParser(description='Google CodeJam Template')
parser.add_argument('-d', '--debug', action='store_true',
help='print debugging messages')
parser.add_argument('-c', '--case', metavar='N', type=int,
help='only run case N (default: run them all)')
args = parser.parse_args()
if args.debug:
global debug
debug = True
return args
class Case:
def __init__(self, i):
self.i = i
def solve(self):
log("Solving: {}", self)
sol = ""
return self.case() + sol
def case(self):
return "Case #{}: ".format(self.i)
def __repr__(self):
return self.case()
def parse_input(stream):
cases = []
T = int(stream.readline())
for i in range(1, T+1):
# parse case input
cases.append(Case(i))
return cases
def main():
options = parse_args()
cases = parse_input(sys.stdin)
for case in cases:
if not options.case or options.case == case.i:
print(case.solve())
sys.stdout.flush()
main()
<file_sep>/2008/1/T.py
#!/usr/bin/env python3
import sys
def solve():
pass
def main():
ifp = sys.stdin
ofp = sys.stdout
N = int(ifp.readline())
for (i,line) in enumerate(ifp, start=1):
sol = solve()
print("Case #{}: {}".format(i, sol), file=ofp)
ofp.flush()
if __name__ == "__main__":
main()
<file_sep>/2014/1A/C.py
#!/usr/bin/env python3
import sys
import pprint
import random
import collections
def pp(d):
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(d)
class Case:
def __init__(self, i, data):
self.i = i
self.data = data
def solve(self, p_good, p_bad):
pg = 0.0
pb = 0.0
for (i, v) in enumerate(self.data):
pg += p_good[(i,v)]
pb += p_bad[(i,v)]
if pg > pb:
sol ="GOOD"
else:
sol ="BAD"
#print(pg, pb)
return "Case #{}: {}".format(self.i, sol)
def __repr__(self):
return "Case #{}: {}".format(self.i, self.data)
def parse_input(stream):
cases = []
N = int(stream.readline())
for i in range(1, N+1):
stream.readline()
data = list(map(int, stream.readline().split()))
cases.append(Case(i, data))
return cases
def main():
cases = parse_input(sys.stdin)
p_good = gen_prob(gen_good)
p_bad = gen_prob(gen_bad)
for case in cases:
print(case.solve(p_good, p_bad))
def gen_prob(gen):
random.seed(0xd00d)
N = 1000
T = 1000
dist_map = {}
for i in range(N):
dist_map[i] = collections.defaultdict(int)
for i in range(T):
a = gen(N)
#print(a)
dist(a, dist_map)
prob_map = collections.defaultdict(float)
for i in range(N):
for v,cnt in dist_map[i].items():
p = cnt/T
prob_map[(i,v)] = p
#print("{}@{}: {}".format(v, i, cnt/T))
#print()
#print("{}: {}".format(i, dist_map[i].items()))
return prob_map
def dist(a,dist_map):
for (i,k) in enumerate(a):
dist_map[i][k] += 1
def gen_good(N):
a = [i for i in range(N)]
for k in range(N):
p = random.randint(k, N-1)
t = a[k]
a[k] = a[p]
a[p] = t
return a
def gen_bad(N):
a = [i for i in range(N)]
for k in range(N):
p = random.randint(0, N-1)
t = a[k]
a[k] = a[p]
a[p] = t
return a
main()
<file_sep>/2014/Q/D.rb
#!/usr/bin/env ruby
#
require 'pp'
class Case
attr_accessor :table
def initialize(i, naomi, ken)
@i = i
@naomi = naomi.sort.reverse
@ken = ken.sort.reverse
@table = {}
end
def best_winning_move(ken, naomi, game)
case game
when :war then
first_ken_win = ken.zip(naomi).find_index {|k,n| n < k}
if first_ken_win and first_ken_win > 0
i = first_ken_win - 1
return 1,ken[0...-1],naomi[0...i]+naomi[i+1..-1]
else
return 0,ken[1..-1],naomi[1..-1]
end
end
end
def best_losing_move(ken, naomi, game)
case game
when :war then
first_ken_win = ken.zip(naomi).find_index {|k,n| n < k}
if first_ken_win
i = first_ken_win
return 0,ken[0...i]+ken[i+1..-1],naomi[0...i]+naomi[i+1..-1]
else
return 1,ken[1..-1],naomi[1..-1]
end
end
end
def best_naomi(ken, naomi, game)
case game
when :war then
return naomi[0],naomi.clone[1..-1]
when :decit
if naomi[0] > ken[0] then
return naomi[0],naomi.clone[1..-1]
else
return ken[0]-0.000001,naomi[0...-1]
end
end
end
def best_n(ken, n)
return n if n > ken[0]
return ken[0]-0.000001
end
def worst_n(ken, n)
i = ken.find_index {|k| k > n}
if i
return ken[i]-0.000001
else
return n
end
end
def worst_naomi(ken, naomi, game)
if naomi[-1] < ken[0]
return ken[0]-0.000001,naomi[0...-1]
else
return naomi[0],naomi.clone[1..-1]
end
end
def kens_move(ken, n)
#puts "#{ken}, #{n}"
return ken[-1],ken[0...-1] if n > ken[0]
i = ken.find_index {|k| k > n}
return ken[i],ken[0...i]+ken[i+1..-1]
end
def best(ken, naomi, game)
#puts "B: #{ken}, #{naomi}"
return 0 if ken.size == 0
#puts "R: #{ken}, #{naomi}"
sub = ken.to_s+naomi.to_s
#return (puts "HIT"; @table[sub]) if @table.has_key?(sub)
return ( @table[sub]) if @table.has_key?(sub)
n,nn = best_naomi(ken, naomi, game)
k,kk = kens_move(ken, n)
win = n > k ? 1 : 0
#puts "W: #{win} N: #{n}, K: #{k}"
val1 = win+best(kk, nn, game)
if game == :decit
val2 = naomi.each_with_index.map do |n,i|
k,kk = kens_move(ken, best_n(ken, n))
((n > k) ? 1 : 0) + best(kk, naomi[0...i]+naomi[(i+1)..-1], game)
end.max
val3 = naomi.each_with_index.map do |n,i|
k,kk = kens_move(ken, worst_n(ken, n))
((n > k) ? 1 : 0) + best(kk, naomi[0...i]+naomi[(i+1)..-1], game)
end.max
val = [val2,val3].max
#max = 0
#maxv = nil
#vals.each do |n,v|
# if v > max
# maxv = n
# max = v
# end
#end
#puts "VALS: #{vals}"
#puts "MAXV: #{maxv} = #{max}"
#val = max
#n2,nn2 = worst_naomi(ken, naomi, game)
#k2,kk2 = kens_move(ken, n2)
#win2 = n2 > k2 ? 1 : 0
##puts "W2: #{win} N2: #{n}, K2: #{k}"
#val2 = win2+best(kk2, nn2, game)
#val = [val1, val2].max
else
val = val1
end
#puts "V: #{val}"
@table[sub] = val
return val
end
def solve
w = best(@ken, @naomi, :war)
@table = {}
#puts :decit
d = best(@ken, @naomi, :decit)
"Case ##{@i}: #{d} #{w}"
end
end
def read_input(f)
cases = []
n = f.readline.to_i
(1..n).each do |i|
f.readline
naomi = f.readline.split.map(&:to_f)
ken = f.readline.split.map(&:to_f)
cases << Case.new(i, naomi, ken)
end
cases
end
if __FILE__ == $0
read_input($stdin).each do |c|
#pp c
puts c.solve
end
end
<file_sep>/2013/Q/A.rb
#!/usr/bin/env ruby
require 'pp'
def winner(row)
if (row.count("X") == 3 and row.count("T") == 1) or
(row.count("X") == 4)
return "X"
elsif (row.count("O") == 3 and row.count("T") == 1) or
(row.count("O") == 4)
return "O"
else
return "D"
end
end
class Board
def initialize(i, board)
@board = board
@N = i
end
def [](i)
return @board[i]
end
def each
yield @board[0]
yield @board[1]
yield @board[2]
yield @board[3]
yield @board.transpose[0]
yield @board.transpose[1]
yield @board.transpose[2]
yield @board.transpose[3]
yield [@board[0][0], @board[1][1], @board[2][2], @board[3][3]]
yield [@board[0][3], @board[1][2], @board[2][1], @board[3][0]]
end
def incomplete
@board.map{|r| r.join.include?(".")}.any?
end
def result
head = "Case ##{@N}:"
each do |row|
w = winner(row)
if w != "D"
return "#{head} #{w} won"
end
end
return "#{head} Game has not completed" if incomplete
return "#{head} Draw"
end
end
def read_input(f)
boards = []
n = f.readline.to_i
(1..n).each do |i|
board = []
board << f.readline.chomp.chars
board << f.readline.chomp.chars
board << f.readline.chomp.chars
board << f.readline.chomp.chars
f.readline
boards << Board.new(i, board)
#pp i
#boards[i-1].each do |row|
# pp row
#end
end
boards
end
if __FILE__ == $0
boards = read_input($stdin)
boards.each do |b|
puts b.result
end
end
<file_sep>/2014/1A/A.py
#!/usr/bin/env python3
import sys
import pprint
def pp(d):
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(d)
def flipv(s):
if s == "0":
return "1"
return "0"
def flip(col):
return [flipv(i) for i in col]
def numify(socket):
return int(socket, 2)
def normalize(sockets):
return sorted(map(numify, sockets))
def apply_flips(flips, sockets):
results = []
for s in sockets:
results.append(s ^ flips)
return results
class Case:
def __init__(self, i, start, goal):
self.i = i
self.start = normalize(start)
self.goal = normalize(goal)
self.sorted_goal = normalize(goal)
self.cached_flips = set()
def is_sol(self,config):
return sorted(config) == self.sorted_goal
def findbest(self):
start = self.start
if self.is_sol(start):
return 0
num_flips = []
for g_row in self.goal:
for s_row in self.start:
flips = []
flips = g_row ^ s_row
if flips in self.cached_flips:
continue
flipped = apply_flips(flips, start)
#print("s: {}, f: {}, fd:{} = {}".format(list(map(bin,start)), flips, list(map(bin,flipped)), sorted(flipped)))
if self.is_sol(flipped):
num_flips.append(bin(flips).count("1"))
self.cached_flips.add(flips)
if len(num_flips) == 0:
return -1
return min(num_flips)
def solve(self):
print(self.i)
s = self.findbest()
if s == -1:
sol="NOT POSSIBLE"
else:
sol = str(s)
return "Case #{}: {}".format(self.i, sol)
def __repr__(self):
return "Case #{}: {} to {}".format(self.i, self.start, self.goal)
def parse_input(stream):
cases = []
N = int(stream.readline())
for i in range(1, N+1):
stream.readline()
start = stream.readline().split()
goal = stream.readline().split()
cases.append(Case(i, start, goal))
return cases
def main():
cases = parse_input(sys.stdin)
#pp(cases)
for case in cases:
print(case.solve())
main()
<file_sep>/2008/1/A.cc
#include <iostream>
using namespace std;
int64_t solve( int64_t *x, int64_t *y, int n) {
sort(x, x+n);
sort(y, y+n, greater<int>());
int64_t dotp = 0;
for(int i = 0; i < n; i++) {
dotp += x[i] * y[i];
}
return dotp;
}
int main(int argc, char** argv) {
int T;
cin >> T;
int64_t x[800];
int64_t y[800];
for(int t = 1; t <= T; t++) {
int n;
cin >> n;
for(int i = 0; i<n; i++) {
cin >> x[i];
}
for(int i = 0; i<n; i++) {
cin >> y[i];
}
int64_t sol = solve(x, y, n);
cout << "Case #" << t << ": " << sol << endl;
}
}
| bfbaf36ec3b3534edffddfb3e183c02568f1c089 | [
"Makefile",
"Python",
"Ruby",
"C++"
]
| 23 | Python | dmpots/codejam | 27a7054adf4239b31d16e4e18053126a27f09741 | 4da427bfcdee36e0abe8203a19559d59ac92a40f |
refs/heads/master | <repo_name>ricardofagodoy/coding-problems-cpp<file_sep>/main.cpp
#include <iostream>
#include <vector>
#include <map>
#include <chrono>
using namespace std;
int find_even_index (const vector<int> numbers) {
int numbersSize = numbers.size();
map<int, vector<int>> sums;
int sumAux = 0;
for(int i = 0; i <= numbersSize - 1; i++)
sums[(sumAux += numbers[i])].push_back(i);
sumAux = 0;
for(int i = numbersSize - 1; i >= 0; i--)
sums[(sumAux += numbers[i])].push_back(i);
for(map<int, vector<int>>::iterator t = sums.begin(); t != sums.end(); ++t) {
vector<int> indexes = t->second;
for(int i = 0; i < indexes.size() -1; i++)
for(int j = i; j <= indexes.size() -1; i++) {
cout << "Summing " << indexes[i] << " and " << indexes[j] << " to be " << numbersSize-1 << endl;
if (indexes[i] + indexes[j] == numbersSize - 1)
return indexes[i];
}
}
return -1;
}
int find_even_index_slow (const vector<int> numbers) {
int numbersSize = numbers.size();
for(int i = 0; i <= numbersSize - 1; i++) {
int sumLeftRight = 0,
sumRightLeft = 0;
for(int l = 0; l < i; l++)
sumLeftRight += numbers[l];
for(int r = numbersSize - 1; r > i; r--)
sumRightLeft += numbers[r];
if (sumLeftRight == sumRightLeft)
return i;
}
return -1;
}
int main(int argc, char** argv) {
int n = 10;
vector<int> v;
for(int i = 1; i <= n; i++) v.push_back(i);
v.push_back(0);
for(int i = 1; i <= n; i++) v.push_back(i);
cout << v.size() << " numbers" << endl;
auto started = std::chrono::high_resolution_clock::now();
cout << "found index: " << find_even_index({1, 2, 3, 4, 3, 2, 1}) << endl;
auto done = std::chrono::high_resolution_clock::now();
cout << "time taken: " << chrono::duration_cast<chrono::milliseconds>(done-started).count() << " ms" << endl;
cout << v[0] << endl;
return 0;
}<file_sep>/Makefile
CC = g++
CFLAGS = -g -std=c++11
OBJS = main.cpp
main: $(OBJS)
$(CC) $(CFLAGS) -o main $(OBJS)
clean:
rm -f *~ *.o main
| 3eb71bb81fa4877b527ee9cc73338d810abbcb38 | [
"Makefile",
"C++"
]
| 2 | C++ | ricardofagodoy/coding-problems-cpp | 17c104daf1990311334e9781aa41ae94c36cbb36 | 83fae71de5bdf54677d25ec406bf07e0984d735c |
refs/heads/main | <file_sep>lipsX=0;
lipsY=0;
function preload() {
}
function setup() {
canvas=createCanvas(650,650);
canvas.position(150,150);
video=createCapture(VIDEO);
video.hide();
canvas.center();
poseNet=ml5.poseNet(video,modelLoaded);
poseNet.on("poseNet",gotResults);
}
function modelLoaded() {
console.log("posenet loaded");
}
function draw() {
image(video,50,60,540,520);
fill(255,0,0);
stroke(255,0,0);
circle(50,50,80);
fill(255,215,0);
stroke(255,215,0);
rect(90,40,500,20);
fill(255,0,0);
circle(600,50,80);
stroke(255,0,0);
fill(255,215,0);
stroke(255,215,0);
rect(590,88,20,500);
fill(255,0,0);
stroke(255,0,0);
circle(600,588,80);
fill(255,215,0);
stroke(255,215,0);
rect(60,584,500,20);
fill(255,0,0);
stroke(255,0,0);
circle(50,584,80);
fill(255,215,0);
stroke(255,215,0);
rect(40,93,20,450);
} | d1847abef61ef5624209a8138e6f20c1d3525008 | [
"JavaScript"
]
| 1 | JavaScript | Bubby123456/filterapp.com | 9e38c3d79de0885afbae1e2e6fb75a0d7d35e6aa | 3d957f232e2574c336be07a4dcc7b6e5ab07df7c |
refs/heads/main | <repo_name>JacobCT/FundiPythonTutorial<file_sep>/README.md
# FundiPythonTutorial
Python hands-on session for the 2021 Fundi tutorials
In this tutorial, we will discuss some of the common and useful packages for analysis of time-domain radio data. All the required software for the tutorial is bundled up into a docker/singularity container. You are free to use either and you will find instructions on how to use it below:
## Use Docker
If you are using docker, note that you will need a docker installation on your laptop as you will likely not have permissions to run docker on the MPIfR machines. Assuming you have a working installation, which you can set up from [here](https://docs.docker.com/get-docker/), the easiest way to use it is to download the image from docker hub by doing:
```
docker pull vivekvenkris/fundi_python_tutorial:latest
```
In case you do not have a good internet connection and wish to build it from scratch, you can clone [this](https://github.com/vivekvenkris/pulsar_folder) repository, `cd` to the repository and run
```
docker build -t fundi_python_tutorial .
```
Once this is done, you can run the container by doing:
```
docker run -it -p <your_port_number>:<your_port_number> -v <repo_location>:/<repo_location> vivekvenkris/fundi_python_tutorial
```
## Use Singularity
If you are using singularity, you can use either your personal machine or one of the MPIfR machines that has singularity installed (E.g: dogmatix0). You can install singularity on your local machine using instructions from [here](https://sylabs.io/guides/3.0/user-guide/installation.html). The singularity image can either be downloaded from google drive [here](https://drive.google.com/drive/folders/1ASX0Qhl7V39wlefxK_FGmo7luV648Chc?usp=sharing) or from the FPRA meerkat partition here: `/fpra/mkat/01/users/vivek/singularity_images/vivekvenkris_fundi_python_tutorial-2021-10-03-5dd4a33d25e1.sif`. Note that not all will have permissions to access this directory, so revert to downloading from Google Drive if you cant download from here.
Once you have downloaded or copied the singularity image, you can run it by doing
```
singularity shell -B <repo_location>:/<repo_location> /fpra/mkat/01/users/vivek/singularity_images/vivekvenkris_fundi_python_tutorial-2021-10-03-5dd4a33d25e1.sif
```
## Using Jupyter notebook
Once you are inside your docker or singularity container, you can start a jupyter notebook by doing the following
```
cd <repo_location>
jupyter lab --port <your_port_number> --no-browser
```
Your port number here and everywhere else can in principle be anything (although needs to be the same everywhere), but since there might be unconscious overlaps, please choose a random number between 10000 and 11000.
If you are running docker, you need to also add `--allow_root --ip 0.0.0.0` to your jupyter lab command.
If you are running singularity, you need to forward the port you are using to your localhost. You can do that by requesting a port forward by doing:
```
ssh <your_user_name>@<your_machine> -J <gateway machine> -L <your_port_number>:localhost:<your_port_number>
```
For instance, `ssh vkrishnan@dogmatix1 -J portal.mpifr-bonn.mpg.de -L 10034:localhost:10034` forwards the port `10034` from `dogmatix1` to my localhost (my laptop) via the `portal` gateway.
<file_sep>/argparse_example.py
#python3 argparse_example.py
import argparse
# help flag provides flag help
# store_true actions stores argument as True
import sys
args = sys.argv
print(args)
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', action='store_true',
help="shows output")
parser.add_argument('-n', '--name', type=str, required=True, help="Your Name")
args = parser.parse_args(args[1:])
out_str = "Hello, {}!".format(args.name)
if args.output:
print(out_str)
<file_sep>/loop.bash
/bin/bash
for i in 1 2 3 4 5;
do
echo 'value of i is now' $i;
sleep 5;
done | 62f6bbab4f2f9e8040f09eda646b5fe3c77082b6 | [
"Markdown",
"Python",
"Shell"
]
| 3 | Markdown | JacobCT/FundiPythonTutorial | 58b426f7f09cbd2b4d8fa438f97e3edeae0fdc0b | c0ab8c57da01b94f0b10dd39e58d3629ce3589ba |
refs/heads/master | <file_sep>setwd("~/Desktop/R_Work")
#source("/Users/David/Desktop/R_Work/compress_news.r")
install.packages("arules")
library(arules)
#install.packages("arulesViz")
#library(arulesViz)
# query used to pull the .psv file:
# select pii_id, gender_full, marriage_groups, age_groups, income_groups, education_groups, race_decode,
# wm_score from davidw.wm_demos where wm_score > -1 and wm_score < 10
data<-read.table("~/Desktop/R_Work/wm_score_demos_analysis.psv", header=F, sep = "|", na.strings = c("","NA"), colClasses=c(rep("character",8)))
# 2,073,331 individuals with wm_scores between 0 and 9 inclusive
##colClasses=c(rep("factor",53),rep("numeric",3)
# copy data to a new dataframe
data_original <- data
# create new column for wm_score bins and populate with bins for wm_score
data$score_bin <- "primary"
# give names to the columns
names(data) <- c("pii_id", "gender", "marital_status", "age_bucket", "income","education","race", "wm_score", "score_bin")
data$score_bin[data$wm_score %in% c(1:3)]<-"occasional"
data$score_bin[data$wm_score %in% c(4:6)]<-"secondary"
data$score_bin[data$wm_score %in% c(0)]<-"1"
data$score_bin <- as.factor(data$score_bin)
data[is.na(data)]<-"Unknown"
# convert columns data types to factors because it's needed for arules
#data$pii_id <- as.factor(data$pii_id)
data$gender <- as.factor(data$gender)
data$marital_status <- as.factor(data$marital_status)
data$age_bucket <- as.factor(data$age_bucket)
data$income <- as.factor(data$income)
data$education <- as.factor(data$education)
data$race <- as.factor(data$race)
#data$wm_score <- as.factor(data$wm_score)
# drop pii_id column and wm_score because they're uninformative
data <- subset(data, select = -c(pii_id, wm_score))
## data$occupation<-as.factor(apply(data,1,compress_occupation))
## choose only a certain number of demo columns
## sub_data <- data[,-c(2,3,4,8,13,14,40,41,42,48,49,50,26,34,37,40,31)]
# coerce sub_data into a class called "transactions"
trans <- as(data,"transactions")
#rule<-apriori(trans,appearance=list(rhs=c("class=Same","class=Decrease","class=Increase"),default="lhs"))
table(data$score_bin)/dim(data)[1] # counts the proportion of the different values in a column
#######################################################
rule.primary <- apriori(trans, parameter = list(minlen = 1, maxlen = 6, supp = 0.02, conf = 0.40), appearance = list(rhs=c("score_bin=primary"), default="lhs"))
rule.primary <- sort(rule.primary, by = "lift")
inspect(rule.primary)
## plot(rule.primary[1:2])
# prune to remove redundant subsets
prune.subset <- is.subset(rule.primary, rule.primary)
prune.subset[lower.tri(prune.subset,diag=T)]<-NA
redundant<-colSums(prune.subset,na.rm=T)>=1
rules.pruned.primary<-rule.primary[!redundant]
inspect(rules.pruned.primary)
#######################################################
rule.secondary <- apriori(trans, parameter = list(minlen = 1, maxlen = 6, supp = 0.02, conf = 0.315), appearance = list(rhs=c("score_bin=secondary"),default="lhs"))
rule.secondary <- sort(rule.secondary, by = "lift")
inspect(rule.secondary)
## plot(rule.secondary[1:2])
# prune to remove redundant subsets
prune.subset <- is.subset(rule.secondary, rule.secondary)
prune.subset[lower.tri(prune.subset,diag=T)]<-NA
redundant<-colSums(prune.subset,na.rm=T)>=1
rules.pruned.secondary <- rule.secondary[!redundant]
inspect(rules.pruned.secondary)
#######################################################
rule.occasional <- apriori(trans, parameter = list(minlen = 1, maxlen = 6, supp = 0.02, conf = 0.315), appearance = list(rhs=c("score_bin=occasional"),default="lhs"))
rule.occasional <- sort(rule.occasional , by = "lift")
inspect(rule.occasional)
## plot(rule.occasional [1:2])
# prune to remove redundant subsets
prune.subset <- is.subset(rule.occasional , rule.occasional )
prune.subset[lower.tri(prune.subset,diag=T)]<-NA
redundant<-colSums(prune.subset,na.rm=T)>=1
rules.pruned.occasional <- rule.occasional [!redundant]
inspect(rules.pruned.occasional)
#######################################################
rule.one <- apriori(trans, parameter = list(minlen = 1, maxlen = 6, supp = 0.015, conf = 0.03), appearance = list(rhs=c("score_bin=1"),default="lhs"))
rule.one <- sort(rule.one , by = "lift")
inspect(rule.one)
## plot(rule.one [1:2])
# prune to remove redundant subsets
prune.subset <- is.subset(rule.one , rule.one )
prune.subset[lower.tri(prune.subset,diag=T)]<-NA
redundant<-colSums(prune.subset,na.rm=T)>=1
rules.pruned.one <- rule.one [!redundant]
inspect(rules.pruned.one)
<file_sep># Workspace for AMG stuff to be uploaded to AMG's Github repo.
| ed21b05478aa3f04b5ac86e15da6b92ed62c91d0 | [
"Markdown",
"R"
]
| 2 | R | dwang818/amg_github | 7aa1993326a05456efa1ae411e122961c6c9fa28 | e3d87d14e4ddd730e79c76a17aafc1cf49c0463a |
refs/heads/master | <repo_name>xjtuwangke/tencent-xg<file_sep>/src/TencentXinge/TagTokenPair.php
<?php
/**
* Created by PhpStorm.
* User: kevin
* Date: 14/10/23
* Time: 00:57
*/
namespace TencentXinge;
class TagTokenPair {
public function __construct($tag, $token)
{
$this->tag = strval($tag);
$this->token = strval($token);
}
public function __destruct(){}
public $tag;
public $token;
}<file_sep>/README.md
腾讯信鸽推送 服务端PHP SDK.
==============
## @see http://developer.xg.qq.com/index.php/PHP_SDK
| 83403c6bd708566d9d18da96cdc6d997f591b014 | [
"Markdown",
"PHP"
]
| 2 | PHP | xjtuwangke/tencent-xg | 0de783a8be30a3c5bff43a692206847a51c3cf9f | 6b4ba092a8f8ba1d099f422a6e8422dfa7bbdd65 |
refs/heads/master | <repo_name>pzhyy/lite-fetch<file_sep>/src/lite-fetch.ts
import 'isomorphic-fetch';
import * as querystring from 'querystring';
import * as pkg from '../package.json';
import {
isEmpty,
mixin,
} from './helper';
export interface Options {
url?: string;
method?: string;
headers?: object;
mode?: string;
cache?: string;
redirect?: string;
credentials?: string;
timeout?: number;
type?: string;
json?: object;
form?: object;
body?: any;
query?: object;
params?: object;
before?: (options: object) => object;
after?: (response: object, resolve: () => void, reject: () => void) => void;
error?: (error: object) => void,
}
const version = (<any>pkg).version;
const methods: string[] = ['HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
const defaultConfig: Options = {
url: '',
method: 'GET',
headers: {
'User-Agent': `Lite-Fetch:${version}`,
},
mode: 'cors', // same-origin, no-cors, cors
cache: 'default', // default, no-store, reload, no-cache, force-cache, only-if-cached
redirect: 'follow', // follow, error, manual
credentials: 'include', // omit, same-origin, include
type: 'raw', // raw, json, text, blob, formData, arrayBuffer
timeout: 0, // disabled
before(options) { return options; },
after(response, resolve, reject) {},
error(error) {},
};
export class LiteFetch {
public config: Options = defaultConfig;
public version: string = version;
constructor(options: Options = {}) {
this.set(options);
this.init();
}
private init() {
methods.forEach((method) => {
this[method.toLocaleLowerCase()] = (url: string, options: Options = {}) => {
options.url = url;
options.method = method;
return this.request(options);
};
});
}
private transform(options: Options) {
const config: any = mixin({}, this.config, options);
if (config.params && !isEmpty(config.params)) {
config.url = config.url.replace(/:([a-z][\w-_]*)/g, (match, key) => {
return options.params[key];
});
}
if (config.query && !isEmpty(config.query)) {
const query: string = querystring.stringify(options.query);
config.url += (config.url.indexOf('?') >= 0 ? '&' : '?') + query;
}
if (config.form && !isEmpty(config.form)) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
config.body = querystring.stringify(config.form);
}
if (config.json && !isEmpty(config.json)) {
config.headers['Content-Type'] = 'application/json; charset=UTF-8';
config.body = JSON.stringify(options.json);
}
return config;
}
private parseBody(type, response) {
if (type === 'json') {
return response.json();
} else if (type === 'text') {
return response.text();
} else if (type === 'blob') {
return response.blob();
} else if (type === 'formData') {
return response.formData();
} else if (type === 'arrayBuffer') {
return response.arrayBuffer();
} else {
return Promise.resolve(response);
}
}
public set(options: Options = {}) {
this.config = mixin({}, this.config, options);
}
public request(options: Options = {}) {
const beforeConfig = this.config.before(options) || options;
const config = this.transform(beforeConfig);
let timer = null;
return new Promise((resolve, reject) => {
if (config.timeout > 0) {
timer = setTimeout(() => {
reject(new Error(`request timeout: ${config.timeout}ms`));
}, config.timeout);
}
fetch(config.url, {
method: config.method,
headers: config.headers,
body: config.body,
mode: config.mode,
cache: config.cache,
redirect: config.redirect,
credentials: config.credentials,
}).then(response => {
clearTimeout(timer);
const next = this.parseBody(config.type, response);
next.then(body => {
const res = {
url: response.url,
method: config.method,
status: response.status,
statusText: response.statusText,
headers: response.headers,
body: body,
};
this.config.after(res, resolve, reject);
if (response.ok) {
resolve(res);
} else {
this.config.error(res);
reject(res);
}
}).catch(error => {
this.config.error(error);
reject(error);
});
return response;
}).catch(error => {
clearTimeout(timer);
this.config.error(error);
reject(error);
});
});
}
}
export default LiteFetch;
<file_sep>/README.md
# lite-fetch
A http client base on Fetch API, make it easy to use.
### Install
```bash
npm install lite-fetch --save
```
### Import
* CommonJS
```javascript
const { LiteFetch } = require('lite-fetch');
```
* ES6
```javascript
import LiteFetch from 'lite-fetch';
```
### Usage
```javascript
import LiteFetch from 'lite-fetch';
const liteFetch = new LiteFetch({
headers: {
Accept: 'application/json',
},
type: 'json',
timeout: 3000,
before(options) {
return options;
},
after(response, resolve, reject) { },
error(error) { }
});
// GET
liteFetch.get('/news', {
query: {
page: 1,
pageSize: 10
},
}).then((response) => {
console.log('response', response);
}).catch((error) => {
console.log('error', error);
});
// POST
liteFetch.post('/news', {
json: {
title: 'Hello world!',
content: 'Good day',
},
}).then((response) => {
console.log('response', response);
}).catch((error) => {
console.log('error', error);
});
// PUT
liteFetch.put('/news/:id', {
params: {
id: 1,
},
json: {
title: 'Hello world!',
content: 'Lucky day',
},
}).then((response) => {
console.log('response', response);
}).catch((error) => {
console.log('error', error);
});
// PATCH
liteFetch.patch('/news/:id', {
params: {
id: 1,
},
json: {
content: 'Tomorrow',
},
}).then((response) => {
console.log('response', response);
}).catch((error) => {
console.log('error', error);
});
// DELETE
liteFetch.delete('/news/:id', {
params: {
id: 1,
},
}).then((response) => {
console.log('response', response);
}).catch((error) => {
console.log('error', error);
});
```
### API
```javascript
liteFetch.set(options);
liteFetch.request(options);
liteFetch.head(url[, options]);
liteFetch.options(url[, options]);
liteFetch.get(url[, options]);
liteFetch.post(url[, options]]);
liteFetch.put(url[, options]]);
liteFetch.patch(url[, options]]);
liteFetch.delete(url[, options]);
```
### Options
```ts
{
url?: string; // default: ''
method?: string; // value: [HEAD, OPTIONS, GET, POST, PUT, PATCH, DELETE]. default: GET
headers?: object; // A key-value object. default: { 'User-Agent': `Lite-Fetch:${version}` }
mode?: string; // value: [same-origin, no-cors, cors]. default: cors
cache?: string; // value: [default, no-store, reload, no-cache, force-cache, only-if-cached]. default: default
redirect?: string; // value: [follow, error, manual]. default: follow
credentials?: string; // value: [omit, same-origin, include]. default: include
timeout?: number; // timeout in ms, 0 to disable. default: 0
type?: string; // response body type, value: [raw, json, text, blob, formData, arrayBuffer]. default: raw
json?: object; // request body, will call `JSON.stringify()` and set to body
form?: object; // request body, will call `querystring.stringify()` and set to body
body?: any; // request body, Fetch's raw body
query?: object; // request query, will call `querystring.stringify()` and concat to url
params?: object; // resquest params, will replace url params by regexp `/:([a-z][\w-_]*)/g`
before?: (options: object) => object; // request before hook, need return `options`
after?: (response: object, resolve: () => void, reject: () => void) => void; // request after hook, need call `resolve()` or `reject()` if change
error?: (error: object) => void; // request error hook
}
```
> Note:
> * If `options.json` are set, `Content-Type: application/json; charset=UTF-8` will be set to headers.
> * If `options.form` are set, `Content-Type: application/x-www-form-urlencoded; charset=UTF-8` will be set to headers.
> * If both `options.json` and `options.form` are set, `options.json` will be used.
### License
MIT<file_sep>/src/helper.ts
export const isEmpty = (obj: object): boolean => {
return !Object.keys(obj).length;
}
export const isObject = (value: any): boolean => {
return Object.prototype.toString.call(value) === '[object Object]';
}
export const mixin = (target: object = {}, ...sources: object[]): object => {
sources.forEach(source => {
Object.keys(source).forEach(key => {
const value = source[key];
if (isObject(value)) {
target[key] = mixin(target[key], value);
} else {
target[key] = value;
}
});
})
return target;
}
| 00f42240dbf8f9210607d6ec891db61726a4dcef | [
"Markdown",
"TypeScript"
]
| 3 | TypeScript | pzhyy/lite-fetch | 4ed2f9f11122d018156ab2accf706aaa414b6ea9 | caa4afd1b15d231241e6073c978207aec6dda78b |
refs/heads/master | <file_sep>
/*Funtion para que el documento esté listo primero*/
/*tooltip de etiquetas*/
$(function () {
$('[data-toggle="popover"]').popover()
})
$(function(){
$("a").click(function(e){
if (this.hash !== ""){
e.preventDefault();
var url = this.hash;
$('html,body').animate({
scrollTop: $(url).offset().top
}, 800, function(){
window.location.hash = url;
});
}
});
});
| 8ca14214331c557086599de9a493898ecec16fd9 | [
"JavaScript"
]
| 1 | JavaScript | catalistt/Portafolio | 1849d01b18493b31341b3ec4e947bf332ab8f503 | 7b41bce4e1a9428e5fd72071f6894038f930101b |
refs/heads/master | <repo_name>Arohak/AHWeather_MVP<file_sep>/app/src/main/java/com/andranikas/weather/data/source/local/WeatherLocalDataSource.java
package com.andranikas.weather.data.source.local;
import android.support.annotation.NonNull;
import com.andranikas.weather.data.entities.Forecast;
import com.andranikas.weather.data.entities.Weather;
import com.andranikas.weather.data.service.DBService;
import com.andranikas.weather.data.source.WeatherDataSource;
import javax.inject.Inject;
import javax.inject.Singleton;
import io.reactivex.Flowable;
import static android.support.v4.util.Preconditions.checkNotNull;
/**
* Created by andranikas on 10/19/2017.
*/
@Singleton
public class WeatherLocalDataSource implements WeatherDataSource {
private final DBService mService;
@Inject
public WeatherLocalDataSource(@NonNull DBService service) {
checkNotNull(service);
mService = service;
}
@Override
public Flowable<Weather> getCurrentWeather(String apiKey, String city, String units) {
return mService.getCurrentWeather(city);
}
@Override
public Flowable<Forecast> getForecast(String apiKey, String city, String units) {
return mService.getForecast();
}
@Override
public void saveCurrentWeather(Weather weather) {
mService.saveCurrentWeather(weather);
}
@Override
public void saveForecast(Forecast forecast, String city) {
mService.saveForecast(forecast, city);
}
}
<file_sep>/app/src/main/java/com/andranikas/weather/app/network/OkHttpGlideModule.java
package com.andranikas.weather.app.network;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.AppGlideModule;
import java.io.InputStream;
/**
* Created by andranikas on 10/24/2017.
*/
@GlideModule
public final class OkHttpGlideModule extends AppGlideModule {
@Override
public void registerComponents(Context context, Glide glide, Registry registry) {
super.registerComponents(context, glide, registry);
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(OkHttpClientFactory.create()));
}
}
<file_sep>/app/src/main/java/com/andranikas/weather/app/network/DBModule.java
package com.andranikas.weather.app.network;
import android.content.Context;
import android.support.annotation.NonNull;
import dagger.Module;
import dagger.Provides;
import io.realm.Realm;
/**
* Created by andranikas on 10/30/2017.
*/
@Module
public abstract class DBModule {
@Provides
@NonNull
static Realm provideRealm(Context context) {
Realm.init(context);
return Realm.getDefaultInstance();
}
}<file_sep>/app/src/main/java/com/andranikas/weather/data/entities/Forecast.java
package com.andranikas.weather.data.entities;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Forecast extends RealmObject {
@PrimaryKey
private String id;
private String name;
@SerializedName("list")
private RealmList<Weather> weathers;
public List<Weather> getWeathers() {
return weathers;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>/app/src/main/java/com/andranikas/weather/data/service/WeatherService.java
package com.andranikas.weather.data.service;
import com.andranikas.weather.data.entities.Forecast;
import com.andranikas.weather.data.entities.Weather;
import io.reactivex.Flowable;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface WeatherService {
@GET("weather")
Flowable<Weather> getWeather(@Query("appid") String apiKey, @Query("q") String city, @Query("units") String units);
@GET("forecast")
Flowable<Forecast> getForecast(@Query("appid") String apiKey, @Query("q") String city, @Query("units") String units);
}
<file_sep>/app/src/main/java/com/andranikas/weather/data/entities/City.java
package com.andranikas.weather.data.entities;
/**
* Created by andranikas on 10/23/2017.
*/
public class City {
private String name;
private String description;
private int temperature;
private String conditionIconPath;
public City(String name, String description, int temperature, String conditionIconPath) {
this.name = name;
this.description = description;
this.temperature = temperature;
this.conditionIconPath = conditionIconPath;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public int getTemperature() {
return temperature;
}
public String getConditionIconPath() {
return conditionIconPath;
}
}
<file_sep>/app/src/main/java/com/andranikas/weather/data/entities/Weather.java
package com.andranikas.weather.data.entities;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Weather extends RealmObject {
@PrimaryKey
private String name;
private Wind wind;
@SerializedName("dt")
private long dateTimeInMillis;
@SerializedName("weather")
private RealmList<WeatherCondition> conditions;
@SerializedName("main")
private Temperature temperature;
@SerializedName("sys")
private Sun sun;
@SerializedName("clouds")
private Cloud cloud;
public String getName() {
return name;
}
public Wind getWind() {
return wind;
}
public long getDateTimeInMillis() {
return dateTimeInMillis;
}
public List<WeatherCondition> getConditions() {
return conditions;
}
public Temperature getTemperature() {
return temperature;
}
public Sun getSun() {
return sun;
}
public Cloud getCloud() {
return cloud;
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'realm-android'
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.7.0'
classpath "io.realm:realm-gradle-plugin:4.1.0"
}
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.andranikas.weather"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Android Support
compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:design:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:percent:$rootProject.ext.supportLibraryVersion"
// Networking
compile "com.squareup.retrofit2:retrofit:$rootProject.ext.retrofitVersion"
compile "com.squareup.retrofit2:converter-gson:$rootProject.ext.retrofitVersion"
compile "com.squareup.retrofit2:adapter-rxjava2:$rootProject.ext.retrofitVersion"
compile "com.squareup.okhttp3:okhttp:$rootProject.ext.okhttpVersion"
debugCompile "com.squareup.okhttp3:logging-interceptor:$rootProject.ext.okhttpVersion"
// RxJava2
compile "io.reactivex.rxjava2:rxandroid:$rootProject.ext.rxAndroidVersion"
compile "io.reactivex.rxjava2:rxjava:$rootProject.ext.rxJavaVersion"
// DI - Dagger2
compile "com.google.dagger:dagger:$rootProject.ext.daggerVersion"
compile "com.google.dagger:dagger-android:$rootProject.ext.daggerVersion"
compile "com.google.dagger:dagger-android-support:$rootProject.ext.daggerVersion"
annotationProcessor "com.google.dagger:dagger-android-processor:$rootProject.ext.daggerVersion"
annotationProcessor "com.google.dagger:dagger-compiler:$rootProject.ext.daggerVersion"
provided 'org.glassfish:javax.annotation:10.0-b28'
// View binding
compile "com.jakewharton:butterknife:$rootProject.ext.butterknifeVersion"
annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.ext.butterknifeVersion"
// Glide
compile "com.github.bumptech.glide:glide:$rootProject.ext.glideVersion"
compile "com.github.bumptech.glide:okhttp3-integration:$rootProject.ext.glideVersion"
annotationProcessor "com.github.bumptech.glide:compiler:$rootProject.ext.glideVersion"
//Joda-Time
compile 'joda-time:joda-time:2.9.9'
// UI test
androidTestCompile("com.android.support.test.espresso:espresso-core:$rootProject.ext.espressoVersion", {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestCompile 'com.google.code.findbugs:jsr305:3.0.2'
// Unit test
testCompile "junit:junit:$rootProject.ext.junitVersion"
}
<file_sep>/app/src/main/java/com/andranikas/weather/app/network/Client.java
package com.andranikas.weather.app.network;
/**
* Created by andranikas on 10/20/2017.
*/
public interface Client {
abstract class Factory {
}
}
<file_sep>/app/src/main/java/com/andranikas/weather/util/UIUtil.java
package com.andranikas.weather.util;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.ImageView;
import com.andranikas.weather.app.network.GlideApp;
/**
* Created by andranikas on 10/23/2017.
*/
public final class UIUtil {
private UIUtil() {
}
public static void displayImageAsynchronously(String imagePath, ImageView into) {
GlideApp.with(into.getContext()).load(imagePath).into(into);
}
public static void showInfo(View view, @StringRes int resId) {
Snackbar.make(view, resId, Snackbar.LENGTH_SHORT).show();
}
}
<file_sep>/app/src/main/java/com/andranikas/weather/data/entities/Sun.java
package com.andranikas.weather.data.entities;
import io.realm.RealmObject;
/**
* Created by andranikas on 10/23/2017.
*/
public class Sun extends RealmObject {
private long sunrise;
private long sunset;
public long getSunrise() {
return sunrise;
}
public long getSunset() {
return sunset;
}
}
<file_sep>/app/src/main/java/com/andranikas/weather/data/source/remote/WeatherRemoteDataSource.java
package com.andranikas.weather.data.source.remote;
import android.support.annotation.NonNull;
import com.andranikas.weather.data.entities.Forecast;
import com.andranikas.weather.data.entities.Weather;
import com.andranikas.weather.data.service.WeatherService;
import com.andranikas.weather.data.source.WeatherDataSource;
import javax.inject.Inject;
import javax.inject.Singleton;
import io.reactivex.Flowable;
import static android.support.v4.util.Preconditions.checkNotNull;
/**
* Created by andranikas on 10/19/2017.
*/
@Singleton
public class WeatherRemoteDataSource implements WeatherDataSource {
private final WeatherService mService;
@Inject
public WeatherRemoteDataSource(@NonNull WeatherService service) {
checkNotNull(service);
mService = service;
}
@Override
public Flowable<Weather> getCurrentWeather(String apiKey, String city, String units) {
return mService.getWeather(apiKey, city, units);
}
@Override
public Flowable<Forecast> getForecast(String apiKey, String city, String units) {
return mService.getForecast(apiKey, city, units);
}
@Override
public void saveCurrentWeather(Weather weather) {
}
@Override
public void saveForecast(Forecast forecast, String city) {
}
}
| ad47ff50fb900ee0020b2ae36ac1dda973c94f65 | [
"Java",
"Gradle"
]
| 12 | Java | Arohak/AHWeather_MVP | b9bee1754ab06f1d3d475aada5398a803bbcd05e | b2bcfdc3fb60b4e59e494851b5b7969e3eae0f0b |
refs/heads/main | <repo_name>kuba-budzynski/Mancala<file_sep>/src/main/kotlin/engine/game/Move.kt
package engine.game
import engine.player.Player
data class Move(
val player: Player,
val bucket: Int,
val stones: Int,
val time: Long,
val wasBonus: Boolean = false,
val steals: Boolean = false
)
<file_sep>/src/main/kotlin/engine/player/Player.kt
package engine.player
enum class Player(index: Int) {
MAX(0),
MIN(1);
companion object{
fun swap(p: Player): Player{
return when(p){
Player.MAX -> Player.MIN
Player.MIN -> Player.MAX
}
}
}
}<file_sep>/src/main/kotlin/engine/game/Settings.kt
package engine.game
import engine.algorithms.Algo
import engine.algorithms.Minimax
import engine.algorithms.MinimaxWithAlphaBeta
import engine.heuristics.BoardValue
import engine.heuristics.Heuristic
import engine.player.AI
import engine.player.ConsolePlayer
import engine.player.Player
import engine.player.PlayerInterface
data class Settings(
var heuristic: Heuristic = BoardValue(),
var heuristics: List<Heuristic> = listOf(),
var algo: Algo = Minimax(),
var depth: Int = 4,
var algoList: MutableList<String> = mutableListOf("Minimax", "Alpha beta"),
var playersList: MutableList<String> = mutableListOf("Player", "AI"),
var maxDepth: Int = 12,
var ai: PlayerInterface = AI(algo)
){
fun setAlgo(a: String){
algo = when(a){
"Minimax" -> Minimax()
"Alpha beta" -> MinimaxWithAlphaBeta()
else -> Minimax()
}
}
fun ai(): PlayerInterface{
return AI(algo)
}
fun player(): PlayerInterface{
return ConsolePlayer(algo)
}
}<file_sep>/src/main/kotlin/engine/heuristics/combo/BoardState.kt
package engine.heuristics.combo
import engine.game.Board
import engine.heuristics.*
class BoardState: Heuristic {
private val steals = Steals()
private val bonuses = BonusMoves()
private val stones = StonesOnBoard()
private val wells = WellDifference()
override fun apply(board: Board): Double {
return (2.9 * wells.apply(board)) + (2.1 * stones.apply(board)) + (1.7 * steals.apply(board)) + (0.9 * bonuses.apply(board))
}
override fun name(): List<String> {
return wells.name() + steals.name() + bonuses.name() + stones.name()
}
}<file_sep>/src/main/kotlin/engine/player/AI.kt
package engine.player
import engine.algorithms.Algo
import engine.game.Board
import engine.game.GameRules
import engine.heuristics.Heuristic
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class AI(private val algo: Algo): PlayerInterface, KoinComponent {
private val gameRules by inject<GameRules>()
private lateinit var player: Player
override fun nextMove(board: Board, fakeMove: Boolean): Int {
return algo.run(board, player, board.children(player, fakeMove)).second
}
override fun setPlayer(player: Player) {
this.player = player
}
override fun getPlayerType(): Player {
return player
}
}<file_sep>/src/main/kotlin/engine/heuristics/StonesOnBoard.kt
package engine.heuristics
import engine.game.Board
import engine.player.Player
class StonesOnBoard: Heuristic {
override fun apply(board: Board): Double {
val playerOneStones = board.getSide(Player.MAX).getBuckets().stream().reduce { t, u -> u + t }.get()
val playerTwoStones = board.getSide(Player.MIN).getBuckets().stream().reduce { t, u -> u + t }.get()
val playerOneZeros = board.getSide(Player.MAX).getBuckets().count { it == 0 }
val playerTwoZeros = board.getSide(Player.MIN).getBuckets().count { it == 0}
return (playerOneStones.div(playerOneZeros.coerceAtLeast(1))).toDouble()
.minus(playerTwoStones.div(playerTwoZeros.coerceAtLeast(1)))
}
override fun name(): List<String> {
return listOf("Stones on board")
}
}<file_sep>/src/main/kotlin/engine/algorithms/Algo.kt
package engine.algorithms
import engine.game.Board
import engine.player.Player
interface Algo {
fun run(board: Board, player: Player, children: List<Pair<Int,Board>>): Pair<Double, Int>
fun name(): String
}<file_sep>/src/main/kotlin/Main.kt
import engine.algorithms.Minimax
import engine.algorithms.MinimaxWithAlphaBeta
import engine.controllers.GameController
import engine.controllers.Silent
import engine.excel.Results
import engine.game.*
import engine.heuristics.BoardValue
import engine.heuristics.BonusMoves
import engine.heuristics.Steals
import engine.heuristics.combo.BoardState
import mu.KotlinLogging
import org.koin.core.context.startKoin
import org.koin.dsl.module
import engine.player.AI
import engine.player.ConsolePlayer
import engine.player.Moves
import engine.player.Player
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
val logger = KotlinLogging.logger{}
val modules = module{
single { GameRules() }
single { Settings() }
single { Moves() }
single { Results() }
}
fun main(){
logger.debug { "App has been started" }
startKoin{
modules(modules)
}
val gr = GameSettings()
gr.settings.heuristic = BoardState()
val depth1 = 6
val algo1 = MinimaxWithAlphaBeta(depth1)
val depth2 = 6
val algo2 = MinimaxWithAlphaBeta(depth2)
val player1 = AI(algo1)
val player2 = AI(algo2)
// Generate statistics for n-games
val n = 20
for(i in 1..n){
val board = Board()
val game = GameController(player1, player2, notifier = Silent(), verbose = false)
val stats = game.play(board)
gr.excel.addStat(stats)
println(stats)
logger.info {
"Test ${gr.gameRules.playerMax + i + gr.gameRules.reset}/${n} \t Time: ${stats.toSeconds(stats.totalTime)} s"
}
}
gr.excel.generateResults(
listOf(
Triple(depth1, algo1.name(), gr.settings.heuristic.name()),
Triple(depth2, algo2.name(), gr.settings.heuristic.name())
)
)
logger.debug { "Excel file has been generated" }
// val game = GameController(player1, player2)
// game.play(Board())
}
class GameSettings: KoinComponent{
val settings by inject<Settings>()
val excel by inject<Results>()
val gameRules by inject<GameRules>()
}
<file_sep>/src/main/kotlin/engine/controllers/ConsoleNotifier.kt
package engine.controllers
import engine.game.Board
import engine.player.PlayerInterface
class ConsoleNotifier: Notifier {
override fun notifyNewMove(board: Board, move: Int, player: PlayerInterface, moveCount: String) {
print("\n------------| move: $moveCount |------------")
print("\nPlayer: " + board.getSide(player.getPlayerType()).printColor(player.getPlayerType().name) + " chose bucket -> " + move)
print(board)
print("\n\n")
}
override fun notifyGameEnd(board: Board, winner: PlayerInterface, score: Double) {
print("\n------------| FINAL BOARD |------------")
print(board)
print(board.getSide(winner.getPlayerType()).printColor("The winner is ${winner.getPlayerType()} with score: $score"))
print("\n\n")
}
override fun notifyScore(board: Board, score: Double, winner: PlayerInterface) {
print(board.getSide(winner.getPlayerType()).printColor("The winner is ${winner.getPlayerType()} with score: $score"))
}
override fun notifyStart(board: Board, playerOne: PlayerInterface, playerTwo: PlayerInterface) {
print("\n------------| STARTING BOARD |------------")
print(board)
print("\n")
}
}<file_sep>/src/main/kotlin/engine/game/Board.kt
package engine.game
import mu.KotlinLogging
import org.apache.commons.lang3.StringUtils
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import engine.player.Player
class Board(): KoinComponent {
private val logger = KotlinLogging.logger{}
private val gameRules by inject<GameRules>()
private var sides = mutableMapOf(Player.MAX to Side(Player.MAX), Player.MIN to Side(Player.MIN))
constructor(other: Board) : this() {
sides.clear()
sides = mutableMapOf()
val copyPlayerOne = other.getSide(Player.MAX).getBuckets().toCollection(mutableListOf())
val copyPlayerTwo = other.getSide(Player.MIN).getBuckets().toCollection(mutableListOf())
val newSidePlayerOne = Side(Player.MAX)
newSidePlayerOne.setBuckets(copyPlayerOne)
newSidePlayerOne.setWell(other.getSide(Player.MAX).getWell())
val newSidePlayerTwo = Side(Player.MIN)
newSidePlayerTwo.setBuckets(copyPlayerTwo)
newSidePlayerTwo.setWell(other.getSide(Player.MIN).getWell())
sides[Player.MAX] = newSidePlayerOne
sides[Player.MIN] = newSidePlayerTwo
}
fun getSide(player: Player): Side{
return sides[player]!!
}
fun children(player: Player, fakeMove: Boolean = false): MutableList<Pair<Int, Board>>{
if(fakeMove) return mutableListOf(Pair(-1, this))
val list = mutableListOf<Pair<Int, Board>>()
val moves = getSide(player).allNotEmpty()
for (move in moves) {
val copy = Board(this)
copy.makeMove(player, move)
list.add(Pair(move, copy))
}
return list
}
fun isInFinalState(): Boolean{
val res1 = sides[Player.MAX]?.getBuckets()?.all { it -> it == 0 }!!
val res2 = sides[Player.MIN]?.getBuckets()?.all { it -> it == 0 }!!
return res1.or(res2)
}
fun makeMove(player: Player, bucket: Int, fakeMove: Boolean = false): Pair<Boolean, Boolean>{
if(!sides[player]?.allNotEmpty()?.contains(bucket)!!)
return Pair(false, second = false)
val stonesInBucket = sides[player]?.getBuckets()?.get(bucket)!!
sides[player]?.getBuckets()?.set(bucket, 0)
return distribute(stonesInBucket, bucket, player)
}
private fun distribute(stones: Int, start: Int, player: Player): Pair<Boolean, Boolean>{
var toPass = stones
var wasStolen = false
var anotherOne = false
var morePasses = false
while (toPass > 0){
val x = getSide(player).deposit(toPass, if(morePasses) -1 else start)
anotherOne = anotherOne.or(x.third) // Last one in my well = bonus move
// Stealing
if(x.second != -1){
val stolen = getSide(Player.swap(player)).getBuckets()[gameRules.buckets -1 - x.second]
if(stolen != 0){
anotherOne = false // Stealing always ends round for that engine.player
getSide(player).getBuckets()[x.second] = 0
getSide(Player.swap(player)).getBuckets()[gameRules.buckets - 1 - x.second] = 0
getSide(player).setWell(getSide(player).getWell() + stolen + 1)
wasStolen = true
}
}
toPass = getSide(Player.swap(player)).deposit(x.first, -1, false).first
morePasses = true
}
return Pair(anotherOne, wasStolen)
}
fun moveRemaining(player: Player){
var other = 0
getSide(player).allNotEmpty().forEach{
other += getSide(player).getBuckets()[it]
getSide(player).getBuckets()[it] = 0
}
getSide(player).setWell(getSide(player).getWell() + other)
}
fun score(): Double{
return getSide(Player.MAX).getWell().toDouble() - getSide(Player.MIN).getWell().toDouble()
}
override fun toString(): String {
val max = sides[Player.MAX]?.printRow()?.length?.coerceAtLeast(sides[Player.MIN]?.printRow()?.length!!)
val firstWell = " | ${sides[Player.MAX]?.printColor(sides[Player.MAX]?.getWell().toString())} | "
val secondWell = " | ${sides[Player.MIN]?.printColor(sides[Player.MIN]?.getWell().toString())} | "
val firstWellLength = " | ${sides[Player.MAX]?.getWell()} | "
val secondWellLength = " | ${sides[Player.MIN]?.getWell()} | "
val length = max!! + firstWellLength.length + secondWellLength.length;
val builder = StringBuilder()
builder.append("\nPlayer: " + sides[Player.MAX]?.printColor("MAX") + " Player: " + sides[Player.MIN]?.printColor("MIN") + " \n")
builder.append(StringUtils.center("-".repeat(max), length))
builder.append("\n")
builder.append(StringUtils.center(sides[Player.MIN]?.printRowReverse(), length))
builder.append("\n")
builder.append(StringUtils.center(secondWell + "-".repeat(max) + firstWell, length))
builder.append("\n")
builder.append(StringUtils.center(sides[Player.MAX]?.printRow(), length))
builder.append("\n")
builder.append(StringUtils.center("-".repeat(max), length))
builder.append("\n")
return builder.toString()
}
}<file_sep>/src/main/resources/log4j.properties
log4j.rootLogger=DEBUG, STDOUT
log4j.logger.deng=INFO
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1} - %m%n<file_sep>/src/main/kotlin/engine/algorithms/MinimaxWithAlphaBeta.kt
package engine.algorithms
import engine.game.Board
import engine.game.Settings
import engine.heuristics.Heuristic
import mu.KotlinLogging
import engine.player.Player
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class MinimaxWithAlphaBeta(private val depth: Int = 8): Algo, KoinComponent {
private val logger = KotlinLogging.logger{}
private val settings by inject<Settings>()
override fun run(board: Board, player: Player, children: List<Pair<Int,Board>>): Pair<Double, Int> {
return minimaxalphabeta(board, depth, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, player, children)
}
private fun minimaxalphabeta(board: Board, depth: Int, alpha: Double, beta: Double, player: Player, children: List<Pair<Int,Board>>): Pair<Double, Int>{
if(board.isInFinalState() || depth <= 0){
return Pair(settings.heuristic.apply(board), -1)
}
var bestScore = if(player == Player.MAX) Double.NEGATIVE_INFINITY else Double.POSITIVE_INFINITY
val shouldReplace: (Double) -> Boolean = if(player == Player.MAX) { x -> x > bestScore} else { x -> x < bestScore}
var moveForBestScore = -1
var innerAlpha = alpha
var innerBeta = beta
for(child in children){
val res = minimaxalphabeta(child.second, depth - 1, innerAlpha, innerBeta, Player.swap(player), child.second.children(Player.swap(player), false))
if(player == Player.MAX) innerAlpha = alpha.coerceAtLeast(res.first)
else if(player == Player.MIN) innerBeta = beta.coerceAtMost(res.first)
if(shouldReplace(res.first)){
bestScore = res.first
moveForBestScore = child.first
}
if(innerBeta <= innerAlpha) break
}
return Pair(bestScore, moveForBestScore)
}
override fun name(): String {
return "Alpha beta"
}
}<file_sep>/settings.gradle.kts
rootProject.name = "MankalaGame"
<file_sep>/src/main/kotlin/engine/controllers/Notifier.kt
package engine.controllers
import engine.game.Board
import engine.player.PlayerInterface
interface Notifier {
fun notifyNewMove(board: Board, move: Int, player: PlayerInterface, moveCount: String = "0")
fun notifyGameEnd(board: Board, winner: PlayerInterface, score: Double)
fun notifyScore(board: Board, score: Double, winner: PlayerInterface)
fun notifyStart(board: Board, playerOne: PlayerInterface, playerTwo: PlayerInterface)
}<file_sep>/src/main/kotlin/engine/game/Side.kt
package engine.game
import mu.KotlinLogging
import org.apache.commons.lang3.StringUtils
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import engine.player.Player
import java.lang.StringBuilder
class Side(private val player: Player): KoinComponent, Cloneable {
private val logger = KotlinLogging.logger{}
private val gameRules by inject<GameRules>()
private var buckets = MutableList(gameRules.buckets){ _ -> gameRules.stones}
private var well: Int = 0
fun allNotEmpty(): List<Int>{
return buckets.mapIndexed{ index, value -> if(value != 0) index else null}.filterNotNull()
}
fun deposit(stones: Int, start: Int = 0, mySide: Boolean = true): Triple<Int, Int, Boolean>{ // <Leftovers, Index to steal, Bonus move>
if(stones <= 0) return Triple(0, -1, false)
var stealStones = false
if(mySide && (start + stones) < gameRules.buckets){
if(buckets[start + stones] == 0) stealStones = true
}
var innerStones = stones
if(start == buckets.size-1){
well++
return Triple(innerStones - 1, if(stealStones) start + 1 + stones else -1, stones == 1)
}
var i = start
for(bucket in buckets.subList(start + 1 , (buckets.size).coerceAtMost(start + 1 + innerStones))){
buckets[++i] = bucket + 1
innerStones--
}
return if(innerStones > 0 && mySide){
well++
Triple(innerStones - 1, if(stealStones) i else -1, innerStones == 1)
} else Triple(innerStones, if(stealStones) i else -1, false)
}
fun getBuckets(): MutableList<Int>{
return buckets
}
fun getWell(): Int{
return well
}
fun setBuckets(new: MutableList<Int>){
buckets = new
}
fun setWell(stones: Int){
well = stones
}
fun hasNextMove(): Boolean{
return buckets.any { it -> it != 0 }
}
fun printRow(): String{
val builder = StringBuilder()
for(h in buckets){
builder.append("|${StringUtils.center("$h", 5)}")
}
builder.append("|")
return builder.toString()
}
fun printRowReverse(): String{
val builder = StringBuilder()
builder.append("|")
for(h in buckets.reversed()) {
builder.append("${StringUtils.center("$h", 5)}|")
}
return builder.toString()
}
fun printColor(msg: String): String{
return when(player){
Player.MAX -> gameRules.playerMax + msg + gameRules.reset
Player.MIN -> gameRules.playerMin + msg + gameRules.reset
}
}
}<file_sep>/src/main/kotlin/engine/algorithms/Minimax.kt
package engine.algorithms
import engine.game.Board
import engine.game.Settings
import engine.heuristics.Heuristic
import mu.KotlinLogging
import engine.player.Player
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class Minimax (private val depth: Int = 8): Algo, KoinComponent {
private val logger = KotlinLogging.logger{}
private val settings by inject<Settings>()
override fun run(board: Board, player: Player, children: List<Pair<Int,Board>>): Pair<Double, Int> {
return minimax(board, depth, player, children)
}
private fun minimax(board: Board, depth: Int, player: Player, children: List<Pair<Int,Board>>): Pair<Double, Int>{
if(board.isInFinalState() || depth <= 0){
return Pair(settings.heuristic.apply(board), -1)
}
var bestScore = if(player == Player.MAX) Double.NEGATIVE_INFINITY else Double.POSITIVE_INFINITY
val shouldReplace: (Double) -> Boolean = if(player == Player.MAX) { x -> x > bestScore} else { x -> x < bestScore}
var moveForBestScore = -1
for(child in children){
val res = minimax(child.second, depth - 1, Player.swap(player), child.second.children(Player.swap(player), false))
if(shouldReplace(res.first)){
bestScore = res.first
moveForBestScore = child.first
}
}
return Pair(bestScore, moveForBestScore)
}
override fun name(): String {
return "Minimax"
}
}<file_sep>/src/main/kotlin/engine/heuristics/Steals.kt
package engine.heuristics
import engine.game.Board
import engine.game.GameRules
import engine.player.Player
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class Steals : Heuristic, KoinComponent {
private val gameOptions by inject<GameRules>()
override fun apply(board: Board): Double {
val maxSide = board.getSide(Player.MAX)
val minSide = board.getSide(Player.MIN)
var maxPossibleSteals = 0
var maxStonesSteals = 0
for(i in 0 until maxSide.getBuckets().size){
val stones = maxSide.getBuckets()[i]
val nextIndex = i + stones
if(nextIndex < gameOptions.buckets){
if(maxSide.getBuckets()[nextIndex] == 0 && minSide.getBuckets()[gameOptions.buckets - 1 - nextIndex] != 0){
maxPossibleSteals++
maxStonesSteals += minSide.getBuckets()[gameOptions.buckets - 1 - nextIndex]
}
}
}
var minPossibleSteals = 0
var minStonesSteals = 0
for(i in 0 until minSide.getBuckets().size){
val stones = minSide.getBuckets()[i]
val nextIndex = i + stones
if(nextIndex < gameOptions.buckets){
if(minSide.getBuckets()[nextIndex] == 0 && maxSide.getBuckets()[gameOptions.buckets - 1 - nextIndex] != 0){
minPossibleSteals++
minStonesSteals += maxSide.getBuckets()[gameOptions.buckets - 1 - nextIndex]
}
}
}
val max = if(maxPossibleSteals <= 0) 0.0 else (maxStonesSteals / maxPossibleSteals.toDouble())
val min = if(minPossibleSteals <= 0) 0.0 else (minStonesSteals / minPossibleSteals.toDouble())
return maxPossibleSteals.toDouble() - minPossibleSteals.toDouble()
}
override fun name(): List<String> {
return listOf("Possible steals")
}
}<file_sep>/src/main/kotlin/engine/heuristics/BoardValue.kt
package engine.heuristics
import engine.game.Board
import engine.player.Player
class BoardValue: Heuristic {
override fun apply(board: Board): Double {
val playerOneStones = board.getSide(Player.MAX).getBuckets().stream().reduce { t, u -> u + t }
val playerTwoStones = board.getSide(Player.MIN).getBuckets().stream().reduce { t, u -> u + t }
val playerOneZeros = board.getSide(Player.MAX).getBuckets().count { it -> it == 0 }
val playerTwoZeros = board.getSide(Player.MIN).getBuckets().count { it -> it == 0}
val playerOneWell = board.getSide(Player.MAX).getWell()
val playerTwoWell = board.getSide(Player.MIN).getWell()
return (playerOneStones.get() + (playerOneWell * 2.2) + (playerTwoZeros * 1.35)).minus(
(playerTwoStones.get() + (playerTwoWell * 2.2) + (playerOneZeros * 1.35))
)
}
override fun name(): List<String> {
return listOf("Board value")
}
}<file_sep>/src/main/kotlin/engine/game/Stats.kt
package engine.game
import engine.player.Player
import java.math.BigDecimal
import java.math.BigInteger
data class Stats(
var player: String = "MAX",
var totalMoves: Int = 0,
var totalTime: BigInteger = BigInteger.ZERO,
var bonusMoves: Int = 0,
var steals: Int = 0,
var movesToFirstBonus: Int = 0,
var timeToFirstBonus: BigInteger = BigInteger.ZERO,
var movesToFirstSteal: Int = 0,
var timeToFirstSteal: BigInteger = BigInteger.ZERO,
var score: Double = 0.0
){
fun toSeconds(time: BigInteger): Double{
return time.toBigDecimal().divide(BigDecimal.valueOf(1000)).toDouble()
}
}
<file_sep>/src/main/kotlin/engine/heuristics/Heuristic.kt
package engine.heuristics
import engine.game.Board
interface Heuristic {
fun apply(board: Board): Double
fun name(): List<String>
}<file_sep>/src/main/kotlin/engine/player/ConsolePlayer.kt
package engine.player
import engine.algorithms.Algo
import engine.game.Board
import engine.game.GameRules
import engine.heuristics.Heuristic
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.util.*
class ConsolePlayer(private val algo: Algo): PlayerInterface, KoinComponent {
private val gameRules by inject<GameRules>()
private lateinit var player: Player
private val input = Scanner(System.`in`)
override fun nextMove(board: Board, fakeMove: Boolean): Int {
return if(!fakeMove){
val moves = board.getSide(player).allNotEmpty()
print("${board.getSide(player).printColor(player.name)} can make moves to ($moves): ")
var move = input.nextInt()
while(move !in moves){
println("Bucket $move is not a valid option")
print("${board.getSide(player).printColor(player.name)} make move ($moves): ")
move = input.nextInt()
}
move
} else -1
}
override fun setPlayer(player: Player) {
this.player = player
}
override fun getPlayerType(): Player {
return player
}
}<file_sep>/src/main/kotlin/engine/heuristics/WellDifference.kt
package engine.heuristics
import engine.game.Board
import engine.player.Player
class WellDifference: Heuristic {
override fun apply(board: Board): Double {
return board.getSide(Player.MAX).getWell().toDouble() - board.getSide(Player.MIN).getWell().toDouble()
}
override fun name(): List<String> {
return listOf("Well difference")
}
}<file_sep>/src/main/kotlin/engine/controllers/Controller.kt
package engine.controllers
import engine.game.Board
import engine.game.Stats
interface Controller {
fun play(initialBoard: Board): Stats
}<file_sep>/src/main/kotlin/engine/player/PlayerInterface.kt
package engine.player
import engine.game.Board
interface PlayerInterface {
fun nextMove(board: Board, fakeMove: Boolean = false): Int
fun setPlayer(player: Player)
fun getPlayerType(): Player
}<file_sep>/src/main/kotlin/engine/controllers/GameController.kt
package engine.controllers
import engine.excel.Results
import engine.game.Board
import engine.game.Move
import engine.game.Stats
import mu.KotlinLogging
import engine.player.AI
import engine.player.Moves
import engine.player.Player
import engine.player.PlayerInterface
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.math.BigInteger
import java.util.*
import kotlin.system.measureTimeMillis
class GameController(private val player1: PlayerInterface,
private val player2: PlayerInterface,
private val notifier: Notifier = ConsoleNotifier(),
private val randomFirstMoveIfAI: Boolean = true,
private val verbose: Boolean = true)
: Controller, KoinComponent {
private val logger = KotlinLogging.logger{}
private val random = Random()
private val moves by inject<Moves>()
private val excel by inject<Results>()
override fun play(initialBoard: Board): Stats {
val stats = mutableMapOf(Player.MAX to Stats(player = Player.MAX.name), Player.MIN to Stats(player = Player.MIN.name))
var move = 1
val players = mutableMapOf(Player.MAX to player1, Player.MIN to player2)
player1.setPlayer(Player.MAX)
player2.setPlayer(Player.MIN)
var current = Player.MAX
val playersFirstBonus = mutableMapOf(Player.MAX to false, Player.MIN to false)
val playersFirstSteal = mutableMapOf(Player.MAX to false, Player.MIN to false)
notifier.notifyStart(initialBoard, player1, player2)
if(players[current]!! is AI && randomFirstMoveIfAI){
var randomFirstMove: Int
val firstMove: Pair<Boolean, Boolean>
var stones: Int
val time = measureTimeMillis {
randomFirstMove = random.nextInt(initialBoard.getSide(current).allNotEmpty().size)
stones = initialBoard.getSide(current).getBuckets()[randomFirstMove]
firstMove = initialBoard.makeMove(current, randomFirstMove)
}
stats[current]!!.totalTime += BigInteger.valueOf(time)
stats[current]!!.totalMoves += 1
excel.addMove(gameIndex, Move(current, randomFirstMove, stones, time, firstMove.first, false))
notifier.notifyNewMove(initialBoard, randomFirstMove, players[current]!!, move.toString())
moves.makeMove(current, randomFirstMove, initialBoard.getSide(current).getBuckets()[randomFirstMove])
move++
if(!firstMove.first){
current = Player.swap(current)
}
else{
stats[current]!!.bonusMoves += 1
}
}
while (!initialBoard.isInFinalState()) {
val moveMade: Pair<Boolean, Boolean>
var res: Int
var stones: Int
val time = measureTimeMillis {
res = players[current]?.nextMove(initialBoard)!!
stones = initialBoard.getSide(current).getBuckets()[res]
moveMade = initialBoard.makeMove(current, res)
}
stats[current]!!.totalTime += BigInteger.valueOf(time)
stats[current]!!.totalMoves += 1
notifier.notifyNewMove(initialBoard, res, players[current]!!, move.toString())
moves.makeMove(current, res, initialBoard.getSide(current).getBuckets()[res])
excel.addMove(gameIndex, Move(current, res, stones, time, moveMade.first, moveMade.second))
move++
if(moveMade.second){
stats[current]!!.steals += 1
if(!playersFirstSteal[current]!!){
stats[current]!!.movesToFirstSteal = stats[current]!!.totalMoves
stats[current]!!.timeToFirstSteal = stats[current]!!.totalTime
playersFirstSteal[current] = true
}
}
if(moveMade.first){
if(verbose) logger.debug { "${initialBoard.getSide(current).printColor(current.name)} gets another move" }
players[Player.swap(current)]?.nextMove(initialBoard, true) // Mock a move to keep alternating min-max structure
stats[current]!!.bonusMoves += 1
if(!playersFirstBonus[current]!!){
stats[current]!!.movesToFirstBonus = stats[current]!!.totalMoves
stats[current]!!.timeToFirstBonus = stats[current]!!.totalTime
playersFirstBonus[current] = true
}
}
else current = Player.swap(current)
}
initialBoard.moveRemaining(
if(initialBoard.getSide(current).getBuckets().all { it -> it == 0 }) Player.swap(current) else current
)
val winner = if (initialBoard.score() > 0) Player.MAX else Player.MIN
notifier.notifyGameEnd(initialBoard, players[winner]!!, initialBoard.score())
stats[winner]!!.score = initialBoard.score()
if(initialBoard.score() != 0.0){
if(verbose) logger.info {"WINNER: ${initialBoard.getSide(winner).printColor(winner.name)}"}
if(verbose) logger.debug { "FINAL SCORE: ${initialBoard.score()}" }
}
else{
if(verbose) logger.info { "TIE with score ${initialBoard.score()}" }
stats[Player.MIN]!!.player = "TIE"
stats[Player.MAX]!!.player = "TIE"
}
gameIndex++;
return stats[winner]!!
}
companion object{
var gameIndex = 0
}
}<file_sep>/src/main/kotlin/engine/player/Moves.kt
package engine.player
data class Moves(var moves: MutableList<String> = mutableListOf()) {
fun makeMove(player: Player, bucket: Int, stones: Int){
moves.add("${player.name} has chosen $bucket with $stones stones")
// moves = moves().toMutableList()
moves = moves().toMutableList()
}
fun moves(): MutableList<String>{
return moves.reversed().toMutableList();
}
}<file_sep>/src/main/kotlin/engine/excel/Results.kt
package engine.excel
import engine.game.Move
import engine.game.Stats
import org.apache.poi.ss.usermodel.IndexedColors
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.FileOutputStream
class Results() {
private val workbook = XSSFWorkbook()
private val createHelper = workbook.creationHelper
private val headerFont = workbook.createFont()
private val headerCellStyle = workbook.createCellStyle()
private val games = mutableMapOf<Int, MutableList<Move>>()
public val stats = mutableListOf<Stats>()
private val columns = listOf("N", "Winner", "Total time", "Total moves", "Steals", "Moves", "Time to first steal",
"Moves to first steal", "Time to first bonus", "Moves to first bonus", "Score")
private val gameColumns = listOf("N", "Player", "Bucket", "Stones", "Time", "Was a bonus move", "Has stones been stolen")
fun generateResults(config: List<Triple<Int, String, List<String>>>, fileName: String = "res.xlsx"){
var sheet = workbook.createSheet("Results")
headerFont.boldweight
headerFont.color = IndexedColors.RED.index
headerCellStyle.setFont(headerFont)
var headerRow = sheet.createRow(0)
for(col in columns.indices){
val cell = headerRow.createCell(col)
cell.setCellValue(columns[col])
cell.cellStyle = headerCellStyle
}
var rowIdx = 1
for(stat in stats){
val row = sheet.createRow(rowIdx)
row.createCell(0).setCellValue(rowIdx.toDouble())
row.createCell(1).setCellValue(stat.player)
row.createCell(2).setCellValue(stat.totalTime.toDouble())
row.createCell(3).setCellValue(stat.totalMoves.toDouble())
row.createCell(4).setCellValue(stat.steals.toDouble())
row.createCell(5).setCellValue(stat.bonusMoves.toDouble())
row.createCell(6).setCellValue(stat.timeToFirstSteal.toDouble())
row.createCell(7).setCellValue(stat.movesToFirstSteal.toDouble())
row.createCell(8).setCellValue(stat.timeToFirstBonus.toDouble())
row.createCell(9).setCellValue(stat.movesToFirstBonus.toDouble())
row.createCell(10).setCellValue(stat.score)
rowIdx++
}
for(column in columns.indices){
sheet.autoSizeColumn(column)
}
var starting = 12
val table = listOf("Depth", "Method", "Heuristic")
for(t in config.indices){
starting += t
for(tab in table.indices){
val cell = sheet.getRow(0).createCell(starting++)
cell.setCellValue(table[tab] + "-${t+1}")
cell.cellStyle = headerCellStyle
}
}
sheet.getRow(1).createCell(12).setCellValue(config[0].first.toDouble())
sheet.getRow(1).createCell(13).setCellValue(config[0].second)
sheet.getRow(1).createCell(16).setCellValue(config[1].first.toDouble())
sheet.getRow(1).createCell(17).setCellValue(config[1].second)
val heuristics = listOf(14,18)
for(t in heuristics.indices){
var start = 1
for(h in config[t].third){
sheet.getRow(start++).createCell(heuristics[t]).setCellValue(h)
}
}
starting = 12
for(t in config.indices){
starting += t
for(tab in table.indices){
sheet.autoSizeColumn(starting++)
}
}
for(game in games.keys){
sheet = workbook.createSheet("Game-${game+1}");
headerRow = sheet.createRow(0)
// Columns
for(col in gameColumns.indices){
val cell = headerRow.createCell(col)
cell.setCellValue(gameColumns[col])
cell.cellStyle = headerCellStyle
}
// Rows
rowIdx = 1
for(move in games[game]!!){
val row = sheet.createRow(rowIdx)
row.createCell(0).setCellValue(rowIdx.toDouble())
row.createCell(1).setCellValue(move.player.name)
row.createCell(2).setCellValue(move.bucket.toDouble())
row.createCell(3).setCellValue(move.stones.toDouble())
row.createCell(4).setCellValue(move.time.toDouble())
row.createCell(5).setCellValue(move.wasBonus)
row.createCell(6).setCellValue(move.steals)
rowIdx++
}
for(column in gameColumns.indices){
sheet.autoSizeColumn(column)
}
}
val fileOut = FileOutputStream(fileName)
workbook.write(fileOut)
fileOut.close()
}
fun addMove(i: Int, move: Move){
val g = games.getOrDefault(i, mutableListOf())
g.add(move)
games[i] = g
}
fun addStat(stat: Stats){
stats.add(stat)
}
}<file_sep>/src/main/kotlin/engine/heuristics/BonusMoves.kt
package engine.heuristics
import engine.game.Board
import engine.game.GameRules
import engine.player.Player
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class BonusMoves: Heuristic, KoinComponent {
private val gameOptions by inject<GameRules>()
override fun apply(board: Board): Double {
val maxSide = board.getSide(Player.MAX)
val minSide = board.getSide(Player.MIN)
var maxPossibleBonuses = 0
for(i in 0 until maxSide.getBuckets().size){
val stones = maxSide.getBuckets()[i]
val nextIndex = i + stones
if(nextIndex == gameOptions.buckets) maxPossibleBonuses++
}
var minPossibleBonuses = 0
for(i in 0 until minSide.getBuckets().size){
val stones = minSide.getBuckets()[i]
val nextIndex = i + stones
if(nextIndex == gameOptions.buckets) minPossibleBonuses++
}
return maxPossibleBonuses.toDouble() - minPossibleBonuses.toDouble()
}
override fun name(): List<String> {
return listOf("Bonus moves")
}
}<file_sep>/README.md
# Mancala Game
## Game AI using Minimax and Minimax with alpha-beta pruning
For colors in IntelliJ use Grep console plugin
</br></br>






<file_sep>/build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.4.31"
application
}
group = "com"
version = "1.0"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib"))
implementation("io.github.microutils:kotlin-logging-jvm:2.0.6")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0-RC")
implementation("org.apache.commons","commons-lang3", "3.0")
implementation("org.apache.commons","commons-collections4", "4.4")
implementation("org.apache.commons","commons-text", "1.9")
implementation("org.apache.commons","commons-math3", "3.6.1")
implementation("org.apache.poi","poi", "3.9")
implementation("org.apache.poi", "poi-ooxml", "3.9")
compile("org.slf4j:slf4j-api:1.7.25")
implementation("org.slf4j:slf4j-api:1.7.25")
compile("org.slf4j","slf4j-log4j12", "1.7.25")
implementation("io.insert-koin:koin-core:3.0.1")
testImplementation("io.insert-koin:koin-test-junit5:3.0.1")
implementation("io.insert-koin:koin-core-ext:3.0.1")
testImplementation("io.insert-koin:koin-test-junit4:3.0.1")
testImplementation("io.insert-koin:koin-test-junit5:3.0.1")
}
tasks.withType<KotlinCompile>() {
kotlinOptions.jvmTarget = "13"
}
application {
mainClassName = "MainKt"
}<file_sep>/src/main/kotlin/engine/controllers/Silent.kt
package engine.controllers
import engine.game.Board
import engine.player.PlayerInterface
class Silent: Notifier {
override fun notifyNewMove(board: Board, move: Int, player: PlayerInterface, moveCount: String) {
}
override fun notifyGameEnd(board: Board, winner: PlayerInterface, score: Double) {
}
override fun notifyScore(board: Board, score: Double, winner: PlayerInterface) {
}
override fun notifyStart(board: Board, playerOne: PlayerInterface, playerTwo: PlayerInterface) {
}
}<file_sep>/src/main/kotlin/engine/game/GameRules.kt
package engine.game
class GameRules() {
val stones = 4
val buckets = 6
val playerMax = "\u001B[32m"
val playerMin = "\u001B[36m"
val reset = "\u001B[0m"
} | 989109ad7d7fd14b3784a4f6150fe7c910e28418 | [
"Markdown",
"Kotlin",
"INI"
]
| 32 | Kotlin | kuba-budzynski/Mancala | 479eb39ab2da370ad8cb1487fd4a2be563a44f80 | a114af415e656078e32f11929738bcb014aba2dd |
refs/heads/master | <file_sep>var main = function() {
document.getElementsByClassName("skillsbox")[0].onmouseover = function() {
var teller = 0;
while (teller < document.getElementsByClassName("bar").length){
document.getElementsByClassName("bar")[teller].style.width = document.getElementsByClassName("skill")[teller].getAttribute("data-percent");
teller++;
}
}
setInterval(slider, 3000);
function slider(){
//Array aanmaken met alle image-elementen in
var albumLijst = document.getElementsByClassName("portfoliofoto");
//Lege array maken waar de source attributen van de image-elementen in opslaan
var mijnArray = [];
//While aanmaken die alle src attributen van de image-elementen gaat opslaan in de lege array
var teller = 0;
while (teller < albumLijst.length){
mijnArray[teller] = albumLijst[teller].getAttribute("src");
teller++;
}
//Eerste element verwijderen dmv shift en opslaan in een variabele om achteraan te plaatsen dmv push
var eersteElement = mijnArray.shift();
mijnArray.push(eersteElement);
/*While aanmaken die de src attributen, opgeslagen in de eerst nog lege array, in de nieuwe volgorde opslaan
in de src attributen van de image-elementen. Dus met andere woorden de scr-attributen veranderen*/
var teller1 = 0;
while (teller1 < mijnArray.length){
albumLijst[teller1].setAttribute("src", mijnArray[teller1]);
teller1++;
}
}
}
window.onload = function() {
main();
}
window.onscroll = function() {
if (document.body.scrollTop === 0) {
document.getElementsByTagName("header")[0].classList.remove("shrinked");
} else {
document.getElementsByTagName("header")[0].classList.add("shrinked");
}
};
| 30d012512237c060d431713b4eeae17d1563c673 | [
"JavaScript"
]
| 1 | JavaScript | BenVaes/it-mijnsiteonline | 6563d31af860857711d10f590fab735d679af73d | 762b1289feb871b26109d3c75e423c1e48c3bda7 |
refs/heads/master | <repo_name>ch3ll0v3k/mate-python-applets<file_sep>/example-2-button/testapplet.py
#!/usr/bin/env python
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import gi
gi.require_version("Gtk", "3.0")
gi.require_version('MatePanelApplet', '4.0')
from gi.repository import Gtk
from gi.repository import MatePanelApplet
def show_dialog(widget, event=None):
win = Gtk.Window()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()
def applet_fill(applet):
button = Gtk.Button(label="My Button")
button.connect('clicked', show_dialog)
applet.add(button)
applet.show_all()
def applet_factory(applet, iid, data):
if iid != "TestApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("TestAppletFactory", True,
MatePanelApplet.Applet.__gtype__,
applet_factory, None)
<file_sep>/example-1-label/testapplet.py
#!/usr/bin/env python
# now Ctrl+C will break program if you run it in terminal
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
#--------------------------------------------------------
import gi
gi.require_version("Gtk", "3.0")
gi.require_version('MatePanelApplet', '4.0')
from gi.repository import Gtk
from gi.repository import MatePanelApplet
def applet_fill(applet):
label = Gtk.Label(label="My Label")
applet.add(label)
applet.show_all()
append_menu(applet)
def applet_factory(applet, iid, data):
if iid != "TestApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("TestAppletFactory", True,
MatePanelApplet.Applet.__gtype__,
applet_factory, None)
<file_sep>/example-2-button/install.sh
#!/bin/bash
NAME=TestApplet
# SRC = SOURCE, DST = DESTINATION
SRC_FOLDER=.
SRC_NAME1=${NAME}.mate-panel-applet
DST_NAME1=${NAME}.mate-panel-applet
#DST_NAME1=org.mate.panel.${NAME}.mate-panel-applet
SRC_NAME2=${NAME}Factory.service
DST_NAME2=${NAME}Factory.service
#DST_NAME2=org.mate.panel.applet.${NAME}Factory.service
cp ${SRC_FOLDER}/${SRC_NAME1} /usr/share/mate-panel/applets/${DST_NAME1}
cp ${SRC_FOLDER}/${SRC_NAME2} /usr/share/dbus-1/services/${DST_NAME2}
<file_sep>/other-my-applets/README.md
### minimal-panel
It shows current time using `GLib.timeout_add(1000, update_label)`
### panel-panel
It shows `Label`, `Button` which open `Dialog`, `Button` which quit main loop (`Gtk.main_quit()`)
It also add two items to menu (right mouse button)
<file_sep>/other-not-my-applets/indicator/main.py
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myappindicator'
def main():
indicator = appindicator.Indicator.new(APPINDICATOR_ID, 'whatever', appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
indicator.set_menu(gtk.Menu())
gtk.main()
if __name__ == '__main__':
main()
<file_sep>/other-my-applets/jez-applet/applet-copy.py
#!/usr/bin/env python
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
#-------------------------------------------------------------------------------
import os
import sys
import logging
import datetime
#-------------------------------------------------------------------------------
def exception_handler(type, value, traceback):
logging.exception("Uncaught exception occurred: {}".format(value))
logger = logging.getLogger("JezAppletLog")
#logger.setLevel(logging.WARNING)
logger.setLevel(logging.DEBUG)
sys.excepthook = exception_handler
#file_handler = logging.FileHandler(os.path.expanduser("~/.jezapplet.log"))
file_handler = logging.FileHandler(os.path.expanduser("/home/furas/projekty/python/__MATE__/jez-applet/applet.log"))
file_handler.setFormatter(
logging.Formatter('[%(levelname)s] %(asctime)s: %(message)s', "%Y-%m-%d %H:%M:%S")
)
logger.addHandler(file_handler)
#-------------------------------------------------------------------------------
import gi
gi.require_version("Gtk", "3.0")
gi.require_version('MatePanelApplet', '4.0')
from gi.repository import Gtk
from gi.repository import MatePanelApplet
from gi.repository import GLib # timeout_add
def applet_fill(applet):
global label
# you can use this path with gio/gsettings
#settings_path = applet.get_preferences_path()
#logger.debug(settings_path)
box = Gtk.Box()
applet.add(box)
label = Gtk.Label()
box.add(label)
applet.show_all()
# show first time
update_label()
# show again after 1000ms
GLib.timeout_add(1000, update_label)
#return True
def update_label():
text = '[JEŻ: ???]'
label.set_text(text)
return True
def applet_factory(applet, iid, data):
print(iid)
logger.debug(str(iid))
if iid != "JezApplet":
return False
applet_fill(applet)
return True
print('x')
MatePanelApplet.Applet.factory_main("JezAppletFactory", True,
MatePanelApplet.Applet.__gtype__,
applet_factory, None)
<file_sep>/other-not-my-applets/indicator/main-applet-1.py
#!/usr/bin/env python3
#
# https://ubuntu-mate.community/t/developing-a-panel-applet/3593/8
# https://ubuntu-mate.community/t/python-menu-panel-applet/9376/2
# https://wiki.mate-desktop.org/docs:devel:mate-panel
#
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("MatePanelApplet", "4.0")
from gi.repository import Gtk
from gi.repository import MatePanelApplet
# create the applet
def applet_fill(applet):
Button = Gtk.ToggleButton("Button on panel")
applet.add(Button)
applet.show_all()
# this is called by mate-panel on applet creation
def applet_factory(applet, iid, data):
if iid != "MateUserMenuApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main(
"MateUserMenuAppletFactory",
True,
MatePanelApplet.Applet.__gtype__,
applet_factory,
None
)
<file_sep>/other-not-my-applets/indicator/README.md
https://wiki.mate-desktop.org/docs:devel:mate-panel
Wymagane trzy pliku:
/home/user/applet/testapplet.py
/usr/share/mate-panel/applets/org.mate.panel.TestApplet.mate-panel-applet
/usr/share/dbus-1/services/org.mate.panel.applet.TestAppletFactory.service
<file_sep>/example-3-many-widgets/testapplet.py
#!/usr/bin/env python
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import gi
gi.require_version("Gtk", "3.0")
gi.require_version('MatePanelApplet', '4.0')
from gi.repository import Gtk
from gi.repository import MatePanelApplet
def applet_fill(applet):
# you can use this path with gio/gsettings
settings_path = applet.get_preferences_path()
box = Gtk.Box()
applet.add(box)
label = Gtk.Label(label="TestApplet")
box.add(label)
button = Gtk.Button(label="QUIT")
button.connect('clicked', Gtk.main_quit)
box.add(button)
applet.show_all()
def applet_factory(applet, iid, data):
if iid != "TestApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("TestAppletFactory", True,
MatePanelApplet.Applet.__gtype__,
applet_factory, None)
<file_sep>/other-my-applets/minimal-applet/applet-functions.py
#!/usr/bin/env python
# https://www.systutorials.com/docs/linux/man/1-mate-panel-test-applets/
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
# https://github.com/city41/mate-i3-applet/blob/master/log.py
#-------------------------------------------------------------------------------
import os
import sys
import logging
import datetime
#-------------------------------------------------------------------------------
def exception_handler(type, value, traceback):
logging.exception("Uncaught exception occurred: {}".format(value))
logger = logging.getLogger("MinimalAppletLog")
#logger.setLevel(logging.WARNING)
logger.setLevel(logging.DEBUG)
sys.excepthook = exception_handler
#file_handler = logging.FileHandler(os.path.expanduser("~/.minimalapplet.log"))
file_handler = logging.FileHandler(os.path.expanduser("/home/furas/projekty/python/__MATE__/minimal-applet/applet.log"))
file_handler.setFormatter(
logging.Formatter('[%(levelname)s] %(asctime)s: %(message)s', "%Y-%m-%d %H:%M:%S")
)
logger.addHandler(file_handler)
#-------------------------------------------------------------------------------
import gi
gi.require_version("Gtk", "3.0")
gi.require_version('MatePanelApplet', '4.0')
from gi.repository import Gtk
from gi.repository import MatePanelApplet
from gi.repository import GLib # timeout_add
def applet_fill(applet):
global label
#logger.debug(str(applet))
# you can use this path with gio/gsettings
#settings_path = applet.get_preferences_path()
#logger.debug(settings_path)
box = Gtk.Box()
applet.add(box)
label = Gtk.Label()
box.add(label)
applet.show_all()
# show first time
update_label()
# show again after 1000ms
GLib.timeout_add(1000, update_label)
# Gtk.timeout_add(1000, update_label) # doesn't work in new Gtk
def update_label():
text = datetime.datetime.now().strftime('[ %Y.%m.%d | %H:%M:%S ]')
label.set_text(text)
return True
def applet_factory(applet, iid, data):
if iid != "MinimalApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("MinimalAppletFactory", True,
MatePanelApplet.Applet.__gtype__,
applet_factory, None)
<file_sep>/example-4-extend-right-menu/testapplet.py
#!/usr/bin/env python
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import gi
gi.require_version("Gtk", "3.0")
gi.require_version('MatePanelApplet', '4.0')
from gi.repository import Gtk
from gi.repository import MatePanelApplet
def show_dialog(widget, event=None):
win = Gtk.Window()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()
def append_menu(applet):
menu_xml="""
<menuitem item="Item 1" action="AboutAction"/>
<menuitem item="Item 2" action="QuitAction"/>
"""
actions = [
('AboutAction', None, 'About Test Applet', None, None, show_dialog),
('QuitAction', None, 'Quit Test Applet', None, None, Gtk.main_quit),
]
action_group = Gtk.ActionGroup("TestApplet")
action_group.add_actions(actions, applet)
applet.setup_menu(menu_xml, action_group)
def applet_fill(applet):
label = Gtk.Label(label="Label")
applet.add(label)
applet.show_all()
append_menu(applet)
def applet_factory(applet, iid, data):
if iid != "TestApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("TestAppletFactory", True,
MatePanelApplet.Applet.__gtype__,
applet_factory, None)
<file_sep>/README.md
I wanted to create applet for MATE.
I started digging and checking tutorials, forums, source codes on github.
Finally I decided to write it to remeber it.
---
https://wiki.mate-desktop.org/docs:devel:mate-panel
Applet requires three files:
```
your-folder/TestApplet.py
/usr/share/mate-panel/applets/TestApplet.mate-panel-applet
/usr/share/dbus-1/services/TestAppletFactory.service
```
Some examples on internet use names with prefix `org.mate.panel.` and `org.mate.panel.applet.` but it works without those prefixes.
They are rather for uniq names - so you can install two applets with name `TestApplet`.
```
/usr/share/mate-panel/applets/org.mate.panel.TestApplet.mate-panel-applet
/usr/share/dbus-1/services/org.mate.panel.applet.TestAppletFactory.service
```
You can install `.mate-panel-applet` and `.service` once. Inside these files you have to change path to your `.py`.
I created `install.sh` to (re)install these files. You may have to edit it if you don't use name `TestApplet.py`.
## Debugging
Applet will NOT display `print()` because it has no access to terminal.
But first you can run applet in terminal to see any errors/typos in code.
You can add and remove applet ro panel to test it OR you can use [mate-panel-test-applets](https://www.systutorials.com/docs/linux/man/1-mate-panel-test-applets/)
to run it from terminal without installing. But applet still will not display `print()`.
I don't know how to start it with parameter `--iid` to run
To see any debug messages you can use module `logging` and save messages in file to see them after stoping applet.
I took this part from [mate-i3-applet](https://github.com/city41/mate-i3-applet/blob/master/matei3applet.py)
---
## Refresh text on label
It needs
GLib.timeout_add(1000, update_label)
instead of
Gtk.timeout_add(1000, update_label)
---
## Class Applet
https://saravananthirumuruganathan.wordpress.com/2010/01/15/creating-gnome-panel-applets-in-python/
---
### Some applets which I previewed to learn it
https://github.com/search?l=Python&q=mate+applet&type=Repositories
logging: https://github.com/city41/mate-i3-applet/blob/master/matei3applet.py
https://github.com/linuxmint/mintmenu-vala/blob/master/mintmenu.vala
https://github.com/ubuntu-mate/mate-optimus/blob/master/usr/lib/mate-optimus/mate-optimus-applet
https://github.com/benpicco/mate-panel-python-applet-example/blob/master/mateAppletExample.py
https://github.com/robint99/mate-dock-applet/blob/master/src/dock_applet.in
https://github.com/projecthamster/hamster/blob/gnome_2x/src/hamster-applet
---
### Examples how to extends right menu with ActionGroup
https://github.com/mate-desktop/mate-applets/blob/master/mateweather/mateweather-applet.c
https://github.com/mate-desktop/mate-applets
---
### Other links
https://stackoverflow.com/questions/49498316/auto-refreshing-mate-panel-applet?rq=1
https://ubuntu-mate.community/t/python-menu-panel-applet/9376/2
https://askubuntu.com/questions/751608/how-can-i-write-a-dynamically-updated-panel-app-indicator
---
### All started with this
https://wiki.mate-desktop.org/docs:devel:mate-panel
http://candidtim.github.io/appindicator/2014/09/13/ubuntu-appindicator-step-by-step.html
https://askubuntu.com/questions/750815/fuzzy-clock-for-ubuntu/752675#752675
---
### Tool(s) to run applet without installing it manually (again and again)
https://askubuntu.com/questions/229511/how-can-i-add-an-applet-to-mate-from-the-terminal
/usr/lib/gnome-panel/mate-panel-add --applet=OAFIID:MATE_DockBarXApplet --panel=top_panel_screen0 --position=500
mateconftool-2 --all-dirs /apps/panel/toplevels
https://saravananthirumuruganathan.wordpress.com/2010/01/15/creating-gnome-panel-applets-in-python/
<file_sep>/other-my-applets/panel-applet/testapplet.py
#!/usr/bin/env python
# https://www.systutorials.com/docs/linux/man/1-mate-panel-test-applets/
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
# https://github.com/city41/mate-i3-applet/blob/master/log.py
import os
import sys
import logging
def exception_handler(type, value, traceback):
logging.exception("Uncaught exception occurred: {}".format(value))
logger = logging.getLogger("TestAppletLog")
#logger.setLevel(logging.WARNING)
logger.setLevel(logging.DEBUG)
sys.excepthook = exception_handler
file_handler = logging.FileHandler(os.path.expanduser("~/.testapplet.log"))
file_handler.setFormatter(
logging.Formatter('[%(levelname)s] %(asctime)s: %(message)s', "%Y-%m-%d %H:%M:%S")
)
logger.addHandler(file_handler)
#-------------------------------------------------------------------------------
import gi
gi.require_version("Gtk", "3.0")
gi.require_version('MatePanelApplet', '4.0')
from gi.repository import Gtk
from gi.repository import MatePanelApplet
from gi.repository import Gdk
def applet_fill(applet):
#logger.debug("applet_fill")
#logger.debug(str(applet))
# you can use this path with gio/gsettings
settings_path = applet.get_preferences_path()
box = Gtk.Box()
applet.add(box)
label = Gtk.Label(label="Label")
box.add(label)
#button = Gtk.Button(label="Dialog")
#button.connect('clicked', show_dialog)
#button.connect('clicked', create_menu, applet)
#button.connect("button-press-event", showMenu, applet)
#button.connect("clicked", showMenu, applet)
#box.add(button)
#button = Gtk.Button(label="Quit")
#button.connect('clicked', Gtk.main_quit)
#box.add(button)
#applet.add_menu(build_menu())
applet.show_all()
append_menu(applet)
#def create_menu(widget, event, applet):
# f = open('log', 'w')
# f.write(str(widget)+'\n')
# f.write(str(event)+'\n')
# f.write(str(applet)+'\n')
# f.close()
# menu_xml='<popup name="button3"><menuitem verb="About" label="AKUKU"/></popup>'
# menu_xml='''<popup name="button3">
# <menuitem name="Item 3" verb="About" label="_About" pixtype="stock" pixname="Gtk-about"/>
# </popup>'''
# verbs = [("About", showAboutDialog)]
# applet.setup_menu(menu_xml, verbs, None)
def show_menu(widget, event, applet):
# https://developer.gnome.org/gdk3/stable/gdk3-Event-Structures.html#GdkEventButton
logging.debug("show_menu")
#if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
if event.button == 1:
logging.debug("show_menu - button 1")
#showMainDialog()
#show_dialog(widget)
create_menu(applet)
#if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
# elif event.button == 3:
# logging.debug("show_menu - button 3")
# widget.emit_stop_by_name("button-press-event")
# create_menu(applet)
def append_menu(applet):
logging.debug("append_menu")
#propxml="""<popup name="button3">
# <menuitem name="Item 3" action="AboutAction" label="_About"/>
# </popup>"""
# https://github.com/mate-desktop/mate-applets/blob/master/mateweather/mateweather-applet.c
# https://github.com/mate-desktop/mate-applets/blob/master/mateweather/mateweather-applet-menu.xml
menu_xml="""
<menuitem item="Item 1" action="AboutAction"/>
<menuitem item="Item 2" action="QuitAction"/>
"""
actions = [
('AboutAction', None, 'About Test Applet', None, None, show_dialog),
('QuitAction', None, 'Quit Test Applet', None, None, Gtk.main_quit),
]
action_group = Gtk.ActionGroup("TestApplet")
action_group.add_actions(actions, applet)
applet.setup_menu(menu_xml, action_group)
def show_dialog(widget, event=None):
logging.debug("show_dialog")
logging.debug(str(widget))
logging.debug(str(event))
win = Gtk.Window()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()
def applet_factory(applet, iid, data):
if iid != "TestApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("TestAppletFactory", True,
MatePanelApplet.Applet.__gtype__,
applet_factory, None)
<file_sep>/other-not-my-applets/indicator/main-2.py
#!/usr/bin/env python3
#
# http://candidtim.github.io/appindicator/2014/09/13/ubuntu-appindicator-step-by-step.html
#
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myappindicator'
ICON = 'whatever'
#ICON = gtk.STOCK_INFO
def main():
#indicator = appindicator.Indicator.new(APPINDICATOR_ID, ICON, appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator = appindicator.Indicator.new(APPINDICATOR_ID, ICON, appindicator.IndicatorCategory.OTHER)
indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
#indicator.set_menu(gtk.Menu())
indicator.set_label("Hello World!", APPINDICATOR_ID)
indicator.set_menu(build_menu())
gtk.main()
def build_menu():
menu = gtk.Menu()
item = gtk.MenuItem(label='Quit')
item.connect('activate', gtk.main_quit)
menu.append(item)
menu.show_all()
return menu
if __name__ == '__main__':
main()
| b77416639a466cd4bcfa0c750a18c0213eb7b04c | [
"Markdown",
"Python",
"Shell"
]
| 14 | Python | ch3ll0v3k/mate-python-applets | 8b2c0d5dc2db5a364f35acd604fbde46e4ec749e | 2ceb1f9abd5bc2f63c76b45f040be9f46a4eb140 |
refs/heads/master | <file_sep>---
---
# Header
# Another {MD025}
<file_sep>---
front: matter
---
# Header 1
## Header 2
<file_sep>Text text text
---
layout: post
hard: tab {MD010}
title: embedded
---
Text text text
<file_sep>---
layout: post
title: Title with ---
tags: front matter
---
## Header {MD002}
---
Hard tab {MD010}
<file_sep><!-- markdownlint-disable MD003 -->
* list
* list
# Header 1
* list
* list
# Header 2 #
* list
* list
Header 3
========
* list
* list
<file_sep>"use strict";
var fs = require("fs");
var md = require("markdown-it")({ "html": true });
var rules = require("./rules");
var shared = require("./shared");
// Mappings from rule to description and tag to rules
var allRuleNames = [];
var ruleNameToRule = {};
var idUpperToRuleNames = {};
rules.forEach(function forRule(rule) {
allRuleNames.push(rule.name);
ruleNameToRule[rule.name] = rule;
// The following is useful for updating README.md
// console.log("* **" + rule.name + "** *" +
// rule.aliases.join(", ") + "* - " + rule.desc);
rule.tags.forEach(function forTag(tag) {
var tagUpper = tag.toUpperCase();
var ruleNames = idUpperToRuleNames[tagUpper] || [];
ruleNames.push(rule.name);
idUpperToRuleNames[tagUpper] = ruleNames;
});
rule.aliases.forEach(function forAlias(alias) {
var aliasUpper = alias.toUpperCase();
idUpperToRuleNames[aliasUpper] = [ rule.name ];
});
});
// The following is useful for updating README.md
// Object.keys(idUpperToRuleNames).sort().forEach(function forTag(tag) {
// console.log("* **" + tag + "** - " + idUpperToRuleNames[tag].join(", "));
// });
// Class for results with toString for pretty display
function Results() { }
Results.prototype.toString = function resultsToString(useAlias) {
var that = this;
var results = [];
Object.keys(that).forEach(function forFile(file) {
var fileResults = that[file];
Object.keys(fileResults).forEach(function forRule(ruleName) {
var rule = ruleNameToRule[ruleName];
var ruleResults = fileResults[ruleName];
ruleResults.forEach(function forLine(lineNumber) {
var result =
file + ": " +
lineNumber + ": " +
(useAlias ? rule.aliases[0] : rule.name) + " " +
rule.desc;
results.push(result);
});
});
});
return results.join("\n");
};
// Array.sort comparison for number objects
function numberComparison(a, b) {
return a - b;
}
// Function to return unique values from a sorted array
function uniqueFilterForSorted(value, index, array) {
return (index === 0) || (value > array[index - 1]);
}
// Lints a single string
function lintContent(content, config, frontMatter) { // eslint-disable-line
// Remove front matter (if present at beginning of content)
var frontMatterLines = 0;
if (frontMatter) {
var frontMatterMatch = content.match(frontMatter);
if (frontMatterMatch && !frontMatterMatch.index) {
var contentMatched = frontMatterMatch[0];
content = content.slice(contentMatched.length);
frontMatterLines = contentMatched.split(shared.newLineRe).length - 1;
}
}
// Parse content into tokens and lines
var tokens = md.parse(content, {});
var lines = content.split(shared.newLineRe);
var tokenLists = {};
var tbodyMap = null;
// Annotate tokens with line/lineNumber
tokens.forEach(function forToken(token) {
// Handle missing maps for table body
if (token.type === "tbody_open") {
tbodyMap = token.map.slice();
} else if ((token.type === "tr_close") && tbodyMap) {
tbodyMap[0]++;
} else if (token.type === "tbody_close") {
tbodyMap = null;
}
if (tbodyMap && !token.map) {
token.map = tbodyMap.slice();
}
// Update token metadata
if (token.map) {
token.line = lines[token.map[0]];
token.lineNumber = token.map[0] + 1;
// Trim bottom of token to exclude whitespace lines
while (token.map[1] && !(lines[token.map[1] - 1].trim())) {
token.map[1]--;
}
// Annotate children with lineNumber
var lineNumber = token.lineNumber;
(token.children || []).forEach(function forChild(child) {
child.lineNumber = lineNumber;
if ((child.type === "softbreak") || (child.type === "hardbreak")) {
lineNumber++;
}
});
}
if (!tokenLists[token.type]) {
tokenLists[token.type] = [];
}
tokenLists[token.type].push(token);
});
// Merge rules/tags and sanitize config
var defaultKey = Object.keys(config).filter(function forKey(key) {
return key.toUpperCase() === "DEFAULT";
});
var ruleDefault = (defaultKey.length === 0) || !!config[defaultKey[0]];
var mergedRules = {};
rules.forEach(function forRule(rule) {
mergedRules[rule.name] = ruleDefault;
});
Object.keys(config).forEach(function forKey(key) {
var value = config[key];
if (value) {
if (!(value instanceof Object)) {
value = {};
}
} else {
value = false;
}
var keyUpper = key.toUpperCase();
if (ruleNameToRule[keyUpper]) {
mergedRules[keyUpper] = value;
} else if (idUpperToRuleNames[keyUpper]) {
idUpperToRuleNames[keyUpper].forEach(function forRule(ruleName) {
mergedRules[ruleName] = value;
});
}
});
// Create mapping of enabled rules per line
var enabledRules = {};
rules.forEach(function forRule(rule) {
enabledRules[rule.name] = !!mergedRules[rule.name];
});
function forMatch(match) {
var enabled = match[1].toUpperCase() === "EN";
var items = match[2] ?
match[2].trim().toUpperCase().split(/\s+/) :
allRuleNames;
items.forEach(function forItem(nameUpper) {
if (ruleNameToRule[nameUpper]) {
enabledRules[nameUpper] = enabled;
} else if (idUpperToRuleNames[nameUpper]) {
idUpperToRuleNames[nameUpper].forEach(function forRule(ruleName) {
enabledRules[ruleName] = enabled;
});
}
});
}
var enabledRulesPerLineNumber = [ null ];
lines.forEach(function forLine(line) {
var match = shared.inlineCommentRe.exec(line);
if (match) {
enabledRules = shared.clone(enabledRules);
while (match) {
forMatch(match);
match = shared.inlineCommentRe.exec(line);
}
}
enabledRulesPerLineNumber.push(enabledRules);
});
// Create parameters for rules
var params = {
"tokens": tokens,
"tokenLists": tokenLists,
"lines": lines
};
// Run each rule
var result = {};
rules.forEach(function forRule(rule) {
// Configure rule
params.options = mergedRules[rule.name];
var errors = [];
rule.func(params, errors);
// Record any errors (significant performance benefit from length check)
if (errors.length) {
errors.sort(numberComparison);
var filteredErrors = errors
.filter(uniqueFilterForSorted)
.filter(function removeDisabledRules(lineNumber) {
return enabledRulesPerLineNumber[lineNumber][rule.name];
})
.map(function adjustLineNumbers(error) {
return error + frontMatterLines;
});
if (filteredErrors.length) {
result[rule.name] = filteredErrors;
}
}
});
return result;
}
// Lints a single file
function lintFile(file, config, frontMatter, synchronous, callback) {
function lintContentWrapper(err, content) {
if (err) {
return callback(err);
}
var result = lintContent(content, config, frontMatter);
callback(null, result);
}
// Make a/synchronous call to read file
if (synchronous) {
lintContentWrapper(null, fs.readFileSync(file, shared.utf8Encoding));
} else {
fs.readFile(file, shared.utf8Encoding, lintContentWrapper);
}
}
// Callback used as a sentinel by markdownlintSync
function markdownlintSynchronousCallback() {
// Unreachable; no code path in the synchronous case passes err
// if (err) {
// throw err; // Synchronous APIs throw
// }
}
/**
* Lint specified Markdown files according to configurable rules.
*
* @param {Object} options Configuration options.
* @param {Function} callback Callback (err, result) function.
* @returns {void}
*/
function markdownlint(options, callback) {
// Normalize inputs
options = options || {};
callback = callback || function noop() {};
var files = [];
if (Array.isArray(options.files)) {
files = options.files.slice();
} else if (options.files) {
files = [ String(options.files) ];
}
var strings = options.strings || {};
var frontMatter = (options.frontMatter === undefined) ?
shared.frontMatterRe : options.frontMatter;
var config = options.config || { "default": true };
var synchronous = (callback === markdownlintSynchronousCallback);
var results = new Results();
// Helper to lint the next file in the array
function lintFilesArray() {
var file = files.shift();
if (file) {
lintFile(file, config, frontMatter, synchronous,
function lintedFile(err, result) {
if (err) {
return callback(err);
}
// Record errors and lint next file
results[file] = result;
lintFilesArray();
});
} else {
callback(null, results);
}
}
// Lint strings
Object.keys(strings).forEach(function forKey(key) {
var result = lintContent(strings[key] || "", config, frontMatter);
results[key] = result;
});
// Lint files
lintFilesArray();
// Return results
if (synchronous) {
return results;
}
}
/**
* Lint specified Markdown files according to configurable rules.
*
* @param {Object} options Configuration options.
* @returns {Object} Result object.
*/
function markdownlintSync(options) {
return markdownlint(options, markdownlintSynchronousCallback);
}
// Export a/synchronous APIs
module.exports = markdownlint;
module.exports.sync = markdownlintSync;
<file_sep># Header 1
## Header 2 {MD022}
Some text
## Header 3 {MD022}
Some text
## Header 4 {MD022}
## Header 5<file_sep>"use strict";
// Polyfills for browsers that do not support String.trimLeft/Right
function trimLeftPolyfill() {
return this.replace(/^\s*/, "");
}
/* istanbul ignore if */
if (!String.prototype.trimLeft) {
String.prototype.trimLeft = trimLeftPolyfill;
}
function trimRightPolyfill() {
return this.replace(/\s*$/, "");
}
/* istanbul ignore if */
if (!String.prototype.trimRight) {
String.prototype.trimRight = trimRightPolyfill;
}
// Export for testing
/* istanbul ignore else */
if ((typeof module !== "undefined") && module.exports) {
module.exports = {
"trimLeftPolyfill": trimLeftPolyfill,
"trimRightPolyfill": trimRightPolyfill
};
}
| 4ddda923a5cacc927e2322bfbb5bf507ad948d3b | [
"Markdown",
"JavaScript"
]
| 8 | Markdown | igorshubovych/markdownlint | c02af9683681c0fd545c39f47eedbcb10eb0af26 | 0980b7ca8a88283c6cf4f255575107b4b857f763 |
refs/heads/master | <file_sep>require 'net/http'
require 'open-uri'
namespace :load_maps do
desc "Load MARC geo codes by screen-scraping LC"
task :marc_geographic do
begin
require 'nokogiri'
rescue LoadError => e
$stderr.puts "\n load_maps:marc_geographic task requires nokogiri"
$stderr.puts " Try `gem install nokogiri` and try again. Exiting...\n\n"
exit 1
end
source_url = "http://www.loc.gov/marc/geoareas/gacs_code.html"
filename = ENV["OUTPUT_TO"] || File.expand_path("../../translation_maps/marc_geographic.yaml", __FILE__)
file = File.open( filename, "w:utf-8" )
$stderr.puts "Writing to `#{filename}` ..."
html = Nokogiri::HTML(open(source_url).read)
file.puts "# Translation map for marc geographic codes constructed by `rake load_maps:marc_geographic` task"
file.puts "# Scraped from #{source_url} at #{Time.now}"
file.puts "# Intentionally includes discontinued codes."
file.puts "\n"
html.css("tr").each do |line|
code = line.css("td.code").inner_text.strip
unless code.nil? || code.empty?
code.gsub!(/^\-/, '') # treat discontinued code like any other
label = line.css("td[2]").inner_text.strip
label.gsub!(/\n */, ' ') # get rid of newlines that file now sometimes contains, bah.
label.gsub!("'", "''") # yaml escapes single-quotes by doubling them, weird but true.
file.puts "'#{code}': '#{label}'"
end
end
$stderr.puts "Done."
end
end
<file_sep>source 'https://rubygems.org'
# Specify your gem's dependencies in traject.gemspec
gemspec
group :development do
gem "webmock", "~> 3.4"
end
group :debug do
gem "ruby-debug", :platform => "jruby"
gem "byebug", :platform => "mri"
end
| f0fff198f0b0d0502af34e22f1082aee9d6250b9 | [
"Ruby"
]
| 2 | Ruby | jkeck/traject | ac0c5372cb76705f9b70c9b321ca100d7f852506 | ea646b70f2538cd567bbd9bc25efdc21747c3be1 |
refs/heads/master | <file_sep># otalk-media-controller
A module for tracking all media streams in an app, both local and remote.
## Properties
- `useAudioWhenAvailable` - `{Boolean}`
- `useVideoWhenAvailable` - `{Boolean}`
- `detectSpeaking` - `{Boolean}`
- `capturingAudio` - `{Boolean}`
- `capturingVideo` - `{Boolean}`
- `capturingScreen` - `{Boolean}`
- `localStreams` - `{Collection}`
- `localScreens` - `{Collection}`
- `localVideoStreams` - `{Collection}`
- `localAudioOnlyStreams` - `{Collection}`
- `remoteStreams` - `{Collection}`
- `remoteVideoStreams` - `{Collection}`
- `remoteAudioOnlyStreams` - `{Collection}`
- `claimedRemoteStreams` - `{Collection}`
- `claimedRemoteVideoStreams` - `{Collection}`
- `claimedRemoteAudioOnlyStreams` - `{Collection}`
- `streams` - `{Collection}`
- `preview` - `{Stream}`
- `defaultOptionalAudioConstraints` - `{Array}`
- `defaultOptionalVideoConstraints` - `{Array}`
## Methods
- `addLocalStream(stream, isScreen, opts)`
- `addRemoteStream(stream, opts)`
- `start(constraints, cb)`
- `startScreenShare([constraints,] cb)`
- `startPreview(constraints, cb)`
- `stop(stream)`
- `stopScreenShare(stream)`
- `stopPreview()`
- `acceptPreview()`
- `muteAudio()`
- `muteVideo()`
- `playAudio()`
- `playVideo()`
- `ensureLocalStreams(constraints, cb)`
<file_sep>var WebRTC = require('webrtcsupport');
var getUserMedia = require('getusermedia');
var getScreenMedia = require('getscreenmedia');
var State = require('ampersand-state');
var LodashMixin = require('ampersand-collection-lodash-mixin');
var Collection = require('ampersand-collection');
var FilteredCollection = require('ampersand-filtered-subcollection');
var SubCollection = FilteredCollection.extend(LodashMixin);
var Stream = require('otalk-model-media');
var DeviceManager = require('otalk-media-devices');
module.exports = State.extend({
props: {
defaultOptionalAudioConstraints: ['array', true],
defaultOptionalVideoConstraints: ['array', true],
capturingAudio: 'boolean',
capturingVideo: 'boolean',
capturingScreen: 'boolean',
detectSpeaking: ['boolean', true, true],
audioMonitoring: {
type: 'object',
required: true,
default: function () {
return {
threshold: -50,
interval: 100,
smoothing: 0.1
};
}
},
// Holding area for a local stream before adding it
// to our collection. Allows for the creation of
// "haircheck" preview UIs to let the user approve
// of the stream before we start using it.
preview: 'state',
// The various categories of streams
localStreams: 'collection',
localScreens: 'collection',
localVideoStreams: 'collection',
localAudioOnlyStreams: 'collection',
remoteStreams: 'collection',
remoteVideoStreams: 'collection',
remoteAudioOnlyStreams: 'collection',
// For multi-party applications using remote streams,
// we track "claimed" streams which are just streams
// that have a peer assigned as an owner.
claimedRemoteStreams: 'collection',
claimedRemoteVideoStreams: 'collection',
claimedRemoteAudioOnlyStreams: 'collection'
},
session: {
_localAudioCount: 'number',
_localVideoCount: 'number',
_localScreenCount: 'number'
},
children: {
devices: DeviceManager
},
collections: {
streams: Collection.extend({ model: Stream })
},
initialize: function () {
var self = this;
this.initializeSubCollections();
this.localVideoStreams.on('add remove reset', function () {
});
this.localStreams.bind('add remove reset', function () {
var updates = {
capturingAudio: false,
capturingVideo: false,
capturingScreeen: false
};
self.localStreams.forEach(function (stream) {
if (stream.hasAudio) {
updates.capturingAudio = true;
}
if (stream.hasVideo && !stream.isScreen) {
updates.capturingVideo = true;
}
if (stream.isScreen && stream.hasVideo) {
updates.capturingScreen = true;
}
});
self.set(updates);
});
this.localScreens.bind('add remove reset', function () {
self.capturingScreen = !!self.localScreens.length;
});
this.streams.bind('change:isEnded', function (stream) {
if (stream.isEnded) {
process.nextTick(function () {
self.streams.remove(stream.id);
});
}
});
},
initializeSubCollections: function () {
this.localStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isLocal: true
}
});
this.localScreens = new SubCollection(this.streams, {
where: {
isEnded: false,
isLocal: true,
isVideo: true,
isScreen: true
}
});
this.localVideoStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isLocal: true,
isVideo: true,
isScreen: false
}
});
this.localAudioOnlyStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isLocal: true,
isAudioOnly: true
}
});
this.remoteStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isRemote: true
}
});
this.remoteVideoStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isRemote: true,
isVideo: true
}
});
this.remoteAudioOnlyStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isRemote: true,
isAudioOnly: true
}
});
this.claimedRemoteStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isRemote: true,
isClaimed: true
}
});
this.claimedRemoteVideoStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isRemote: true,
isVideo: true,
isClaimed: true
}
});
this.claimedRemoteAudioOnlyStreams = new SubCollection(this.streams, {
where: {
isEnded: false,
isRemote: true,
isAudioOnly: true,
isClaimed: true
}
});
},
addLocalStream: function (stream, isScreen, opts) {
opts = opts || {};
if (stream.isState) {
stream.origin = 'local';
stream.isScreen = isScreen || false;
stream.session = opts.session;
return this.streams.add(stream);
} else {
return this.streams.add({
origin: 'local',
stream: stream,
isScreen: isScreen || false,
session: opts.session
});
}
},
addRemoteStream: function (stream, opts) {
opts = opts || {};
if (stream.isState) {
stream.origin = 'remote';
stream.session = opts.session;
stream.peer = opts.peer;
return this.streams.add(stream);
} else {
return this.streams.add({
origin: 'remote',
stream: stream,
session: opts.session,
peer: opts.peer
});
}
},
start: function (constraints, cb) {
var self = this;
cb = cb || function () {};
this._startStream(constraints, function (err, stream) {
if (err) {
return cb(err);
}
var localStream = self.addLocalStream(stream);
if (self.detectSpeaking && localStream.hasAudio) {
localStream.startVolumeMonitor(self.audioMonitoring);
}
cb(err, stream);
});
},
startScreenShare: function (constraints, cb) {
var self = this;
if (arguments.length === 1) {
cb = constraints;
constraints = {};
}
cb = cb || function () {};
constraints = this._prepConstraints(constraints);
getScreenMedia(function (err, stream) {
if (err) {
return cb(err);
}
if (constraints.audio) {
self._startStream({
audio: constraints.audio,
video: false
}, function (err, audioStream) {
if (err) {
return cb(err);
}
stream.addTrack(audioStream.getAudioTracks()[0]);
var localStream = self.addLocalStream(stream, true);
if (self.detectSpeaking && localStream.hasAudio) {
localStream.startVolumeMonitor(self.audioMonitoring);
}
cb(null, stream);
});
} else {
self.addLocalStream(stream, true);
cb(err, stream);
}
});
},
startPreview: function (constraints, cb) {
var self = this;
cb = cb || function () {};
this.stopPreview();
this._startStream(constraints, function (err, stream) {
if (err) {
return cb(err);
}
self.preview = new Stream({
origin: 'local',
stream: stream,
isScreen: false,
});
if (self.detectSpeaking && self.preview.hasAudio) {
self.preview.startVolumeMonitor(self.audioMonitoring);
}
cb(null, stream);
});
},
stop: function (stream) {
var self = this;
if (stream) {
stream = this.streams.get(stream.id);
if (stream) {
stream.stop();
}
} else {
var streams = this.localStreams.models;
this.localStreams.models = [];
streams.forEach(function (stream) {
stream.stop();
self.streams.remove(stream);
});
this.localStreams.trigger('reset');
this.stopScreenShare();
this.stopPreview();
}
},
stopScreenShare: function (stream) {
var self = this;
if (stream) {
stream = this.streams.get(stream.id);
if (stream) {
stream.stop();
}
} else {
var streams = this.localScreens.models;
this.localScreens.models = [];
streams.forEach(function (stream) {
stream.stop();
self.streams.remove(stream);
});
this.localScreens.trigger('reset');
}
},
stopPreview: function () {
if (this.preview) {
this.preview.stop();
this.unset('preview');
}
},
acceptPreview: function () {
if (this.preview) {
this.addLocalStream(this.preview);
this.unset('preview');
}
},
muteAudio: function () {
this.localStreams.forEach(function (stream) {
stream.muteAudio();
});
},
muteVideo: function () {
this.localStreams.forEach(function (stream) {
stream.muteVideo();
});
},
resumeAudio: function () {
this.localStreams.forEach(function (stream) {
stream.playAudio();
});
},
resumeVideo: function () {
this.localStreams.forEach(function (stream) {
stream.playVideo();
});
},
findStream: function (mediaStream) {
var matches = this.streams.filter(function (stream) {
return stream.stream === mediaStream || (stream.id && stream.id === mediaStream.id);
});
return matches[0];
},
ensureLocalStreams: function (constraints, cb) {
var check = constraints || {};
var existing = false;
var wantAudio = !!check.audio;
var wantVideo = !!check.video;
for (var i = 0, len = this.localStreams.length; i < len; i++) {
var stream = this.localStreams.at(i);
if (!stream.isScreen && wantAudio === stream.hasAudio && wantVideo === stream.hasVideo) {
existing = true;
break;
}
}
if (!existing) {
this.start(constraints, cb);
} else {
process.nextTick(cb);
}
},
_prepConstraints: function (constraints) {
if (!constraints) {
constraints = {
audio: this.useAudioWhenAvailable,
video: this.useVideoWhenAvailable
};
}
// Don't override if detailed constraints were explicitly given
if (constraints.audio === true) {
constraints.audio = {
optional: JSON.parse(JSON.stringify(this.defaultOptionalAudioConstraints))
};
if (this.devices.preferredMicrophone) {
if (WebRTC.prefix === 'webkit') {
constraints.audio.optional.push({
sourceId: this.devices.preferredMicrophone
});
} else {
constraints.audio.deviceId = this.devices.preferredMicrophone;
}
}
}
// Don't override if detailed constraints were explicitly given
if (constraints.video === true) {
constraints.video = {
optional: JSON.parse(JSON.stringify(this.defaultOptionalVideoConstraints))
};
if (this.devices.preferredCamera) {
if (WebRTC.prefix === 'webkit') {
constraints.video.optional.push({
sourceId: this.devices.preferredCamera
});
} else {
constraints.video.deviceId = this.devices.preferredCamera;
}
}
}
return constraints;
},
_startStream: function (constraints, cb) {
var self = this;
constraints = this._prepConstraints(constraints);
var transaction = {};
if (!!constraints.audio) {
transaction.wantMicrophoneAccess = true;
transaction.microphoneAccess = self.devices.requestMicrophoneAccess();
}
if (!!constraints.video) {
transaction.wantCameraAccess = true;
transaction.cameraAccess = self.devices.requestCameraAccess();
}
getUserMedia(constraints, function (err, stream) {
if (err) {
return self._handleError(err, transaction, cb);
}
if (stream.getAudioTracks().length > 0) {
transaction.microphoneAccess('granted');
} else if (transaction.wantMicrophoneAccess) {
transaction.microphoneAccess('error');
}
if (stream.getVideoTracks().length > 0) {
transaction.cameraAccess('granted');
} else if (transaction.wantCameraAccess) {
transaction.cameraAccess('error');
}
cb(err, stream);
});
},
_handleError: function (err, transaction, cb) {
function handleError(response) {
if (transaction.wantCameraAccess) {
transaction.cameraAccess(response);
}
if (transaction.wantMicrophoneAccess) {
transaction.microphoneAccess(response);
}
}
switch (err.name) {
case 'PermissionDeniedError':
handleError('denied');
break;
case 'PermissionDismissedError':
handleError('dismissed');
break;
case 'DevicesNotFoundError':
case 'ConstraintNotSatisfiedError':
case 'NotSupportedError':
case 'NoMediaRequestedError':
handleError('error');
break;
}
return cb(err);
}
});
| 5c842533c49520e2fb9355d1707ff78fbf5a9d8e | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | otalk/otalk-media-controller | b0dab1c9f9ae96cc3a616202fef2feb03309928e | bcb50b2484a4798d4ff3608d3bbe0aa5ce0c8528 |
refs/heads/main | <repo_name>dayalushanker/flaskapi<file_sep>/app/main.py
from flask import Flask
from flask_restplus import Resource, Api
from app import app,api
ns = api.namespace('helloworld', description='Operations related to Hello World')
@ns.route('/get')
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
<file_sep>/fapp.py
from app import app
import os
app.config['SECRET_KEY'] = os.urandom(32)
<file_sep>/README.md
Please use the following steps
Step 1:- Create .env file in root directory and put following
debug=True
export FLASK_APP = fapp.py
export FLASK_ENV = development
export FLASK_RUN_HOST=localhost
export FLASK_RUN_PORT=8888
Step 2:- Create virtual environment
$virtualenv venv
Activate it by following commond
$ source venv/bin/activate
Step 3:- Install all the python library
pip3 install -r requrirements.txt
Step 4: Please set the Mysql database in config.py
Step 5: Finally use commond "flask run" enjoy ...
<file_sep>/app/restplus.py
import logging
import traceback
from flask_restplus import Api
from sqlalchemy.orm.exc import NoResultFound
from app import app
log = logging.getLogger(__name__)
api = Api(app=app, version='3.0', title='Blog API',
description='A simple demonstration of a Flask RestPlus powered API')
@api.errorhandler
def default_error_handler(e):
message = 'An unhandled exception occurred.'
log.exception(message)
return {'message': message}, 500
@api.errorhandler(NoResultFound)
def database_not_found_error_handler(e):
log.warning(traceback.format_exc())
return {'message': 'A database result was required but none was found.'}, 404
<file_sep>/config.py
import os
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = 'mysql://root:Cor@1234@localhost/fapi'
SQLALCHEMY_TRACK_MODIFICATIONS = False | 5bb58b32d16d68442a29eda641dffa99be62c940 | [
"Markdown",
"Python"
]
| 5 | Python | dayalushanker/flaskapi | e878af30fa5870a86dd26d35a664504d80e2ef02 | 7cb15d4166dee93d50379ec0842e10b1c7abc729 |
refs/heads/master | <repo_name>e1668058/Epreuve_question3<file_sep>/category-cours.php
<?php
/**
* The template for displaying evenements pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/
*
* @package underscores
*/
get_header();
?>
<div id="primary" class="content-area">
<?php
$category_id = get_cat_ID('cours');
$cat_link = get_category_link($category_id);
echo '<h2><a href='.$cat_link.'>Cours</a></h2>';
?>
<h1>Question 3</h1>
<main id="main" class="site-main">
<header class="page-header">
</header><!-- .page-header -->
<?php
/* Start the Loop */
$n = 0;
while ( have_posts() ) {
the_post();
$n++;
$link = get_permalink();
$title = get_the_title();
$sess = substr($title, 4, 1);
$dom = substr($title, 5, 1);
echo '<div class=q3>';
echo '<h3>'.$n.'. <a href='.$link.'>'.$title .'</a> - </h3> <h3 class=session> Session: '.$sess.' </h3> <h3 class=domaine> Domaine : '.$dom.'</h3>';
echo '</div>';
}
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer(); | 11611ae663cd6a403463dd1f5804b1373af7f36c | [
"PHP"
]
| 1 | PHP | e1668058/Epreuve_question3 | b1f33d5cccaa889074f5b7d256e0f832af28f9fa | fbeb8b7717cb7d237f56f1b8fc0031bef176d39d |
refs/heads/master | <file_sep>import Defaults from './defaults.js';
import Get from './get.js';
import Post from './post.js';
import Put from './put.js';
import Patch from './patch.js';
import Delete from './delete.js';
import FetchEngine from './engines/fetch-engine.js';
Defaults.set({
url:'',
Engine: FetchEngine,
method: 'GET',
headers: {
"Content-Type":"application/json"
},
responseType: 'json',
includeMeta: false
});
function Api(...params) {
Defaults.Engine.execute(...params);
}
Api.defaults = Defaults.set;
Api.get = Get.execute;
Api.post = Post.execute;
Api.put = Put.execute;
Api.patch = Patch.execute;
Api.delete = Patch.execute;
export default Api;
<file_sep>import Defaults from './Defaults';
export default class FetchEngine{
static execute(params) {
const {
url,
responseType,
method,
credentials,
cors,
redirect,
includeMeta,
} = params;
delete params.url;
delete params.responseType;
delete params.includeMeta;
!url && (url = Defaults.url);
!method && (params.method = Defaults.method);
!includeMeta && (includeMeta = Defaults.includeMeta);
!credentials && (params.credentials = Defaults.credentials);
!cors && (params.cors = Defaults.cors);
!redirect && (params.credentials = Defaults.redirect);
params.headers = Object.assign(Defaults.headers, params.headers);
const responseWithMeta = response => response[responseType]()
.then(
data => ({data, meta:response})
);
const responseFunction = includeMeta ?
responseWithMeta
: response => response[responseType]()//just send back the data
return window.fetch(url, params)
.then(response => response.ok ?
responseFunction(response)
: Promise.reject(responseWithMeta(response))
)
}
}
<file_sep>import ObjectToUrlConverter from './objectToUrlConverter.js';
export default class Get {
static executeArray(array, subscription) {
let promises = [];
for(let params of array) {
promise.push(this.execute(params)
.then(response => subscription(response.json()))
.catch(subscription));
}
let allCompleted = Promise.all(promises);
}
static execute(params, options) {
!this.fetch && this.fetch = window.fetch;
let { url, body } = params;
typeof params === 'string' && (url = params);
if(params instanceof Array){
//fire off chain of arrays
}
else if(params instanceof Object) {
delete params.url;
options = params;
}
if(body) {
delete options.body;
let urlEncodedBody = ObjectToUrlConverter.convert(body);
// url += urlEncodedBody;
}
return this.fetch(url, options);
}
}
| 2719dd87fed57481be46868c2f827a4a71b4fde8 | [
"JavaScript"
]
| 3 | JavaScript | hyrumwhite/api | 416560ca436b012d91c3cca0c487ba1bbaf30fc8 | 2aebdd3ca94c50c5499cb62a5c847c77232ff31a |
refs/heads/master | <file_sep>import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {environment} from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class RouteService {
constructor(private http: HttpClient) {
}
// 获取用户信息
queryListForPage(): Observable<any> {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/queryListForPage`, {});
}
// 删除用户
delete(id): Observable<any> {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/delete/` + id , {} );
}
// 添加
add(data): Observable<any> {
if (data.id == null) {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/insert`, data);
} else {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/update`, data);
}
}
}
<file_sep>import { NZ_I18N, zh_CN } from "ng-zorro-antd";
import zh from "@angular/common/locales/zh";
import { registerLocaleData } from "@angular/common";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http";
import { SharedModule } from "./shared.module";
import { DemoComponent } from "./demo/demo.component";
import { AppRoutingModule } from "./app-routing.module";
import {
APPINIT_PROVIDES,
CookieInterceptor,
DefaultInterceptor,
TokenInterceptor
} from "yunzai8";
import { BrowserModule } from "@angular/platform-browser";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { RouteComponent } from './route/route.component';
import {ReactiveFormsModule} from '@angular/forms';
import { TesComponent } from './tes/tes.component';
registerLocaleData(zh);
@NgModule({
declarations: [AppComponent, DemoComponent, RouteComponent, TesComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
SharedModule,
ReactiveFormsModule,
AppRoutingModule
],
providers: [
{ provide: NZ_I18N, useValue: zh_CN },
{ provide: HTTP_INTERCEPTORS, useClass: CookieInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
...APPINIT_PROVIDES,
{ provide: HTTP_INTERCEPTORS, useClass: DefaultInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
<file_sep>import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {environment} from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class TesService {
constructor(
private http: HttpClient
) { }
// 获取短信信息
queryListForPage() {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/queryListForPage`, {} );
}
// 添加
add(data) {
if (data.id == null) {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/insert`, data)
} else {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/update`, data)
}
}
// 刪除
delete(id) {
return this.http.post(`${environment.gateway}/message-center/v2/msgtpl/delete/` + id, {});
}
}
<file_sep>import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { DemoComponent } from "./demo/demo.component";
import { RouteComponent } from "./route/route.component";
import { YzLayoutComponent, ActGuard, DisplayIndexComponent } from "yunzai8";
import { SimpleErrorComponent } from "yunzai8";
import {TesComponent} from './tes/tes.component';
const routes: Routes = [
{
path: "",
component: YzLayoutComponent,
data: { breadcrumb: "主页", description: "这是主页面" },
canActivate: [ActGuard],
canActivateChild: [ActGuard],
children: [
{ path: "route", redirectTo: "RouteComponent"},
{path: "demo",component: DemoComponent,
data: {breadcrumb: "DEMO TITLE",description: "demo页面是一个具有xxxx功能的xxxxxxxxxxxxxxx的页面xxxxx"
}
},
{path: "route",component: RouteComponent},
{ path: "displayIndex", component: DisplayIndexComponent },
{ path: "error/:status/:desc", component: SimpleErrorComponent },
{ path: 'tes', component: TesComponent}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule {}
<file_sep>import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {RouteService} from './route.service';
import {NzMessageService} from 'ng-zorro-antd';
@Component({
selector: 'app-route',
templateUrl: './route.component.html',
styleUrls: ['./route.component.less']
})
export class RouteComponent implements OnInit {
isVisible = false;
editId = null;
listOfData = [
];
validateForm: FormGroup;
constructor(private fb: FormBuilder,
private routeService: RouteService,
private nzMessageService: NzMessageService) { }
ngOnInit() {
this.validateForm = this.fb.group({
name: [null, [Validators.required]],
createdDate: [null, [Validators.required]],
content: [null, [Validators.required]],
code: [null, [Validators.required]],
/* key: [null, [Validators.required]],*/
});
this.find();
}
find() {
this.routeService.queryListForPage().subscribe(res => {
this.listOfData = res.list;
});
}
delete(data?) {
this.routeService.delete(data.id).subscribe((res: any) => {
this.nzMessageService.success(res.message);
this.find();
});
}
showModal(): void {
this.validateForm.reset();
this.isVisible = true;
}
updateModel(data?) {
this.editId = data.id;
this.validateForm.patchValue(data);
this.isVisible = true;
}
handleCancel(): void {
this.isVisible = false;
}
submitForm() {
// tslint:disable-next-line:forin
for (const i in this.validateForm.controls) {
this.validateForm.controls[i].markAsDirty();
this.validateForm.controls[i].updateValueAndValidity();
}
if (!this.validateForm.valid) {
return false;
}
const data = this.validateForm.value;
data.id = this.editId;
data.createdDate = new Date(data.createdDate).getTime();
this.routeService.add(data).subscribe(res => {
this.nzMessageService.success( res.message);
this.isVisible = false;
this.find();
}, err => {
this.nzMessageService.error(`${err.error.errorMessage}`);
});
}
confirm() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {TesService} from './tes.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
@Component({
selector: 'app-tes',
templateUrl: './tes.component.html',
styleUrls: ['./tes.component.less']
})
export class TesComponent implements OnInit {
isVisible = false;
editId = null;
listOfData = [];
validateForm: FormGroup;
constructor(
private tesService: TesService,
private fb: FormBuilder,
private nzMessageService: NzMessageService
) { }
showModal(): void {
this.validateForm.reset();
this.isVisible = true;
}
handleCancel(): void {
this.isVisible = false;
}
submitForm() {
// tslint:disable-next-line:forin
for (const key in this.validateForm.controls) {
this.validateForm.controls[key].markAsDirty();
this.validateForm.controls[key].updateValueAndValidity();
}
if (!this.validateForm.valid) {
return false;
}
const data = this.validateForm.value;
this.tesService.add(data).subscribe((res: any) => {
console.log(res);
this.nzMessageService.success(res.message);
this.isVisible = false;
this.find();
}, err => {
this.nzMessageService.error(`${err.error.errorMessage}`);
});
}
ngOnInit() {
this.validateForm = this.fb.group({
createdDate: [null, [Validators.required]],
name: [null, [Validators.required]],
code: [null, [Validators.required]],
content: [null, [Validators.required]],
});
this.find();
}
find() {
this.tesService.queryListForPage().subscribe((res: any) => {
this.listOfData = res.list;
});
}
delete(data?) {
this.tesService.delete(data.id).subscribe((res: any) => {
this.nzMessageService.success(res.message);
this.find();
});
}
update(data?) {
this.isVisible = true;
this.editId = data.id;
this.validateForm.patchValue(data);
}
}
<file_sep>export const environment = {
gateway: `/backstage`,
stomp_server_url: `/websocket/ws/`,
production: true
};
<file_sep>import { Yunzai8Module, BaseClient, BaseClientType } from 'yunzai8';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgZorroAntdModule } from 'ng-zorro-antd';
import { RouterModule } from '@angular/router';
import { environment } from 'src/environments/environment';
import {TranslateModule} from '@ngx-translate/core';
const baseClient: BaseClient = {
gateway: `${environment.gateway}`,
ignores: [`${environment.gateway}/cas-proxy/app/validate_full?callback=${window.location.href}`],
stomp: {
brokerURL: `${environment.stomp_server_url}`,
connectHeaders: { login: 'guest', passcode: '<PASSWORD>' },
heartbeatIncoming: 5,
heartbeatOutgoing: 20000,
reconnectDelay: 200
},
layout: {
show_sider: true,
show_header: true
},
systemcode: 'test-group-4',
type: BaseClientType.CAS_SYSTEM,
dev: false
};
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule,
NgZorroAntdModule,
ReactiveFormsModule,
Yunzai8Module.forRoot(baseClient),
TranslateModule.forRoot()
],
exports: [
CommonModule,
RouterModule,
FormsModule,
NgZorroAntdModule,
Yunzai8Module,
TranslateModule
]
})
export class SharedModule {
}
| 4767662277ce0696b7991451dfbd01191c7ccde8 | [
"TypeScript"
]
| 8 | TypeScript | upup297/angular | 4c91704c2f24a8162543bb30171ed7903e83f5f6 | 860f710265fd758ed164187e3fff060c3f4a5a76 |
refs/heads/master | <file_sep>from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
menu = Menu()
coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()
is_on =True
while is_on:
options = coffee_maker.get_items()
choice = input(f"What would you like to have {options}: ")
if choice == "off":
is_on = False
elif choice == "report":
coffee_maker.report()
money_machine.report()
else:
drink = menu.find_drink(choice)
print(drink) | 7830c31ff0b54152aef2b4c6f4c3902066e77768 | [
"Python"
]
| 1 | Python | Rohan-Deka/coffee | 57f22037d95210d29e82154950935df2053fbf47 | c7eba7a9cf897321ba19725133fca9c2cdedbe24 |
refs/heads/master | <repo_name>delgiudices/aneke_ios<file_sep>/Aneke/Product.swift
//
// Product.swift
// Aneke
//
// Created by <NAME> on 9/4/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class Product: NSObject {
var name: String
var product_description: String
var category: String
var company: String
var imageUrl: String
required init(data: NSDictionary) {
self.name = data["name"] as! String
self.product_description = data["description"] as! String
self.category = data["category"] as! String
self.company = data["company"] as! String
self.imageUrl = data["image"] as! String
}
func getImage( callBack: (UIImage) -> () ) {
let request = NSURLRequest(URL: NSURL(string: self.imageUrl)!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) in
let image = UIImage(data: data)
callBack(image!)
}
}
// Static Functions
class func all(params: String, callBack: ([Product]) -> () ) {
let url = NSURL(string: Settings.API_ROOT + "/products?" + params)!
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) in
let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
var queryset = [Product]()
for (product_json) in result {
queryset.append(Product(data: product_json as! NSDictionary))
}
callBack(queryset)
}
}
class func filter(querystring: String, callback: ([Product]) -> () ) {
var new_querystring = querystring.stringByReplacingOccurrencesOfString(" ", withString: "%20")
new_querystring = new_querystring.stringByReplacingOccurrencesOfString("&", withString: "%26")
let url = NSURL(string: Settings.API_ROOT + "/products?name__contains=" + new_querystring )!
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response, data, error) in
let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
var queryset = [Product]()
for (product_json) in result {
queryset.append(Product(data: product_json as! NSDictionary))
}
callback(queryset)
}
}
}
<file_sep>/Aneke/CategoryDataSource.swift
//
// CategoryDataSource.swift
// Aneke
//
// Created by <NAME> on 9/4/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class CategoryDataSource: NSObject, UITableViewDataSource {
var queryset: [Product]?
var tableViewController: UITableViewController
var category: String
init (controller: UITableViewController, category: String) {
self.tableViewController = controller
self.category = category
super.init()
let refreshControll = UIRefreshControl()
refreshControll.addTarget(self, action: "reload", forControlEvents: UIControlEvents.ValueChanged)
self.tableViewController.refreshControl = refreshControll
self.reload()
}
func reload() {
self.tableViewController.refreshControl?.beginRefreshing()
Product.all("category__name=" + self.category) {
products in
self.setQuerySet(products)
self.tableViewController.tableView.dataSource = self
self.tableViewController.tableView.reloadData()
self.tableViewController.refreshControl?.endRefreshing()
}
}
func setQuerySet(queryset: [Product]) {
self.queryset = queryset
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.queryset != nil) {
return self.queryset!.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("productCell") as! ProductTableViewCell
cell.setProduct(queryset![indexPath.row])
return cell
}
}
<file_sep>/Aneke/ProductTableViewCell.swift
//
// ProductTableViewCell.swift
// Aneke
//
// Created by <NAME> on 9/5/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class ProductTableViewCell: UITableViewCell {
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var productCompanyLabel: UILabel!
@IBOutlet weak var productImage: UIImageView!
func setProduct(product: Product) {
self.productCompanyLabel.text = product.company
self.productNameLabel.text = product.name as String
product.getImage() {
(image) in
self.productImage.image = image
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/Aneke/Settings.swift
//
// Settings.swift
// Aneke
//
// Created by <NAME> on 9/5/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class Settings: NSObject {
static let API_ROOT = "http://192.168.0.100:8000/api"
}
<file_sep>/Aneke/SearchDataSource.swift
//
// SearchDataSource.swift
// Aneke
//
// Created by <NAME> on 9/6/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class SearchDataSource: NSObject, UITableViewDataSource {
var searchText: String?
var queryset: [Product] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return queryset.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("productCell") as! ProductTableViewCell
cell.setProduct(queryset[indexPath.row])
return cell
}
func loadSearchData(controller: ProductsTableViewController, querystring: String) {
controller.tableView.dataSource = self
Product.filter(querystring) {
(products) in
self.queryset = products as [Product]
controller.tableView.reloadData()
}
}
}
| 92e5a849ecf873b40abb803f689b55939fdb25c9 | [
"Swift"
]
| 5 | Swift | delgiudices/aneke_ios | a72ae9dea021660a927e4dc81a2021e0c0e92f4d | 2735c674ed75cb3ee608c7ab09539ac60b6392e3 |
refs/heads/main | <file_sep># HelloARCloudAnchor
based on AR_depth_interpetertation
測試Cloud Anchor resolve功能 07/10
<file_sep>package com.google.ar.core.examples.java.helloar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.ar.core.examples.java.common.helpers.Point;
import java.util.ArrayList;
public class PointCloudDrawing extends Activity {
public ArrayList<Point>pp;
public PointCloudView customCanvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pp=PointCloudSaving.pointC;
customCanvas=new PointCloudView(this,null);
customCanvas.setBackgroundColor(Color.GRAY);
setContentView(customCanvas);
}
}
| 604b7d07fcfd1355279332c8c2213a52ac6d3945 | [
"Markdown",
"Java"
]
| 2 | Markdown | OhBlockByJames/HelloARCloudAnchor | be07d6c88449788ddbf256435c959031d1879c2f | f8f3358a9448a40707886fb9aafa006870143c53 |
refs/heads/master | <repo_name>rasendubi/passwords<file_sep>/src/main.rs
extern crate clap;
extern crate passwords;
use std::io;
use std::io::Write;
use clap::{Arg, App};
use passwords::{PasswordGenerator, ChainedGenerator, phrase_passwords, xkcd_passwords};
struct Config<'a> {
generator: ChainedGenerator<'a>,
}
impl<'a> Config<'a> {
fn get_generator(name: &str) -> Result<ChainedGenerator<'a>, String> {
match name {
"xkcd" => Ok(xkcd_passwords()),
"phrases" => Ok(phrase_passwords()),
_ => Err(format!("invalid generator name: {}", name)),
}
}
fn parse() -> Result<Config<'a>, String> {
let generator_names = ["phrases", "xkcd"];
let matches = App::new("Password Generator")
.arg(Arg::with_name("generator")
.short("g")
.long("generator")
.takes_value(true)
.help(&format!("specifies a password generator, one of {:?}", generator_names))
.possible_values(&generator_names))
.get_matches();
let generator_name = matches
.value_of("generator")
.unwrap_or(generator_names[0]);
let generator = Self::get_generator(generator_name)?;
Ok(Config { generator })
}
}
fn main() {
let config = Config::parse().unwrap();
for password in config.generator.iterator().into_iter() {
println!("{}", password);
let mut input = String::new();
print!("> ");
io::stdout().flush().unwrap();
match io::stdin().read_line(&mut input) {
Ok(_) if input.contains("exit") => {
println!("Bye!");
break
},
Ok(_) => continue,
Err(error) => println!("error: {}", error),
}
}
}
<file_sep>/Cargo.toml
[package]
name = "passwords"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
clap = "2.32.0"
rand = "0.5.5"
Inflector = "0.11.3"
<file_sep>/src/lib.rs
extern crate rand;
extern crate inflector;
pub mod generators;
pub use generators::base::{PasswordGenerator, ChainedGenerator, Constant};
pub use generators::case::Case;
pub use generators::defects::Defects;
pub use generators::phrase::{RandomPhrases, RandomWords, Text};
pub use generators::random_string::RandomString;
pub fn phrase_passwords<'a>() -> ChainedGenerator<'a> {
Constant::new("")
.pipe(RandomPhrases::from_text(&Text::the_time_machine(), 3, 5))
.pipe(Case::Class)
.pipe(RandomString::digits(2))
.pipe(Defects::with_symbols(1, 1))
.pipe(Defects::with_vowels(1, 1))
}
pub fn xkcd_passwords<'a>() -> ChainedGenerator<'a> {
Constant::new("")
.pipe(
RandomWords::from_text(&Text::nouns(), 4, 4)
.or(RandomWords::from_text(&Text::the_time_machine(), 4, 5))
)
}
| ac8e44410cfba4864c046a36b4553da86ffa1139 | [
"TOML",
"Rust"
]
| 3 | Rust | rasendubi/passwords | c85100139d8301f72c6948b672e98247571c8a51 | 3019a76c7a36a17709c85eb357121cbc23f0aec3 |
refs/heads/master | <file_sep># lab_sorts
Sorting algorithms in python
<file_sep>def main():
input_list = [5, 2, 7, 4, 0, 9, 8, 6]
print("Input: ", input_list)
bubble_sort(input_list)
print("Bubble sort: ", input_list)
input_list = [5, 2, 7, 4, 0, 9, 8, 6]
mergeSort(input_list)
print("Merge sort: ", input_list)
input_list = [5, 2, 7, 4, 0, 9, 8, 6]
input_list = quicksort(input_list)
print("Quick sort: ", input_list)
def bubble_sort(input_array):
n = 1
while n < len(input_array):
for i in range(len(input_array) - n):
if input_array[i] > input_array[i + 1]:
input_array[i], input_array[i + 1] = input_array[i + 1], input_array[i]
n += 1
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i = i + 1
else:
alist[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
alist[k] = righthalf[j]
j = j + 1
k = k + 1
def quicksort(seq):
if len(seq) <= 1:
return seq
lo, pi, hi = partition(seq)
return quicksort(lo) + [pi] + quicksort(hi)
def partition(seq):
pi, seq = seq[0], seq[1:]
lo = [x for x in seq if x <= pi]
hi = [x for x in seq if x > pi]
return lo, pi, hi
if __name__ == '__main__':
main()
| 03764d885aeb4aff7f31344f46b66c539ca0f90c | [
"Markdown",
"Python"
]
| 2 | Markdown | Danil2032/lab_sorts | 9b69623e4650976c114ad5035f85d6d8746203c7 | 2beffdfa0e3f3141699c5198cd5bad04402e936a |
refs/heads/master | <repo_name>mxnxsh/Interview-question<file_sep>/src/App.js
import React, { useState } from "react";
import PlayerScreen from "./screens/PlayerScreen";
function App() {
const [text, setText] = useState('')
return (
<div>
<div className="wrap">
<div className="search">
<input
type="text"
className="searchTerm"
placeholder="Search..."
onChange={e => setText(e.target.value)}
/>
<button type="submit" className="searchButton">
<i className="fa fa-search"></i>
</button>
</div>
</div>
<PlayerScreen text={text.toLowerCase()} />
</div>
);
}
export default App;
<file_sep>/src/screens/PlayerScreen.jsx
import React, { useEffect, useState } from 'react';
import Axios from 'axios';
import Player from '../components/Player';
import LoadingBox from '../components/LoadingBox';
const PlayerScreen = props => {
const [playersList, setPlayersList] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
const getData = async () => {
try {
const data = await Axios.get(
`https://api.jsonbin.io/b/604f1c137ea6546cf3ddf46e`
);
setLoading(false);
setPlayersList(data.data.playerList.reverse());
} catch (err) {
setError(err.message);
setLoading(false);
console.log(err.message);
}
};
getData();
}, []);
const items =
props.text === ''
? playersList
: playersList.filter(
player =>
player.PFName.toLowerCase().includes(props.text.toLowerCase()) ||
player.TName.toLowerCase().includes(props.text.toLowerCase())
);
return loading ? (
<LoadingBox />
) : error ? (
<p
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
width: '100%',
minHeight: '100vh',
color: 'red',
fontWeight: 'bold',
}}
>
{error}
</p>
) : (
<div className='row center'>
{items.length === 0 ? (
<p>No search found</p>
) : (
items.map(player => <Player key={player.Id} player={player} />)
)}
</div>
);
};
export default PlayerScreen;
<file_sep>/src/components/Player.jsx
import React from 'react';
import { v4 as uuidv4 } from 'uuid';
const Player = props => {
const { Id, PFName, SkillDesc, Value, UpComingMatchesList } = props.player;
return (
<div className='card'>
<div className='card-body'>
<div className='card-image'>
<img src={`assets/${Id}.jpg`} alt={Id} />
</div>
<div className='card-content'>
<p>{PFName}</p>
<p>{SkillDesc}</p>
<p>$ {Value}</p>
</div>
</div>
<div className='hr'></div>
<div className='card-footer'>
<h3>UpComing Matches</h3>
{UpComingMatchesList.map(match => (
<p key={uuidv4()}>
<span style={{ color: 'red' }}>{match.CCode} </span>{' '}
<span style={{ textTransform: 'lowercase' }}>vs</span>
<span style={{ color: 'blue' }}>{` ${match.VsCCode} `}</span>{' '}
Date:-
{match.MDate.split('/').join('-')}
</p>
))}
</div>
</div>
);
};
export default Player;
| ddd81c9245148353f90636a175e299f63cbf04e0 | [
"JavaScript"
]
| 3 | JavaScript | mxnxsh/Interview-question | 4271547ecda5f0dbbfbdc4f814650fc543531f3a | aa00348b68e5f9f0b3c761ce0ec46e7aafc1b9a3 |
refs/heads/master | <repo_name>chiflix/whatlanggo<file_sep>/detect.go
package whatlanggo
import (
"sort"
"unicode"
)
const maxDist = 300
//Detect language and script of the given text.
func Detect(text string) Info {
return DetectWithOptions(text, Options{})
}
//DetectLang detects only the language by a given text.
func DetectLang(text string) Lang {
return Detect(text).Lang
}
//DetectLangWithOptions detects only the language of the given text with the provided options.
func DetectLangWithOptions(text string, options Options) Lang {
return DetectWithOptions(text, options).Lang
}
//DetectWithOptions detects the language and script of the given text with the provided options.
func DetectWithOptions(text string, options Options) Info {
script := DetectScript(text)
if script != nil {
lang := detectLangBaseOnScript(text, options, script)
return Info{
Lang: lang,
Script: script,
}
}
return Info{}
}
//DetectLangsWithOptions detects the language and script of the given text with the provided options.
func DetectLangsWithOptions(text string, options Options) map[Lang]float64 {
res := make(map[Lang]float64)
scripts := DetectScripts(text)
total := float64(0)
for rt, s := range scripts {
lang := detectLangBaseOnScript(s, options, rt)
res[lang] = float64(len(s)) // TODO: some script weight more than others
total += res[lang]
}
for k, v := range res {
res[k] = v * 2 / total
}
return res
}
func detectLangBaseOnScript(text string, options Options, script *unicode.RangeTable) Lang {
switch script {
case unicode.Latin:
return detectLangInProfiles(text, options, latinLangs)
case unicode.Cyrillic:
return detectLangInProfiles(text, options, cyrillicLangs)
case unicode.Devanagari:
return detectLangInProfiles(text, options, devanagariLangs)
case unicode.Hebrew:
return detectLangInProfiles(text, options, hebrewLangs)
case unicode.Ethiopic:
return detectLangInProfiles(text, options, ethiopicLangs)
case unicode.Arabic:
return detectLangInProfiles(text, options, arabicLangs)
case unicode.Han:
return Cmn
case unicode.Bengali:
return Ben
case unicode.Hangul:
return Kor
case unicode.Georgian:
return Kat
case unicode.Greek:
return Ell
case unicode.Kannada:
return Kan
case unicode.Tamil:
return Tam
case unicode.Thai:
return Tha
case unicode.Gujarati:
return Guj
case unicode.Gurmukhi:
return Pan
case unicode.Telugu:
return Tel
case unicode.Malayalam:
return Mal
case unicode.Oriya:
return Ori
case unicode.Myanmar:
return Mya
case unicode.Sinhala:
return Sin
case unicode.Khmer:
return Khm
case _HiraganaKatakana:
return Jpn
}
return -1
}
func detectLangInProfiles(text string, options Options, langProfileList langProfileList) Lang {
if len(text) > 2048 { // ass max length to improve accuracy
text = text[:2047]
}
trigrams := getTrigramsWithPositions(text)
type langDistance struct {
lang Lang
dist int
}
langDistances := []langDistance{}
for lang, langTrigrams := range langProfileList {
if len(options.Whitelist) != 0 {
//Skip non-whitelisted languages.
if _, ok := options.Whitelist[lang]; !ok {
continue
}
} else if len(options.Blacklist) != 0 {
//skip blacklisted languages.
if _, ok := options.Blacklist[lang]; ok {
continue
}
}
dist := calculateDistance(langTrigrams, trigrams)
langDistances = append(langDistances, langDistance{lang, dist})
}
if len(langDistances) == 0 {
return -1
}
sort.SliceStable(langDistances, func(i, j int) bool { return langDistances[i].dist < langDistances[j].dist })
return langDistances[0].lang
}
func calculateDistance(langTrigrams []string, textTrigrams map[string]int) int {
var dist, totalDist int
for i, trigram := range langTrigrams {
if n, ok := textTrigrams[trigram]; ok {
dist = abs(n - i)
} else {
dist = maxDist
}
totalDist += dist
}
return totalDist
}
<file_sep>/info.go
package whatlanggo
import "unicode"
//Info represents a full outcome of language detection.
type Info struct {
Lang Lang
Script *unicode.RangeTable
}
| 7c08a956348f4ebd3c5fb12c1e51dcfec1e1b8a8 | [
"Go"
]
| 2 | Go | chiflix/whatlanggo | a1149b724e3599788b968903fa2465ee235a9793 | de73242b38087766625fa50e51249cfa98d6ee97 |
refs/heads/master | <file_sep>module.exports = function(app, models) {
// Passport
var passport = require("passport");
var auth = authorized;
var LocalStrategy = require('passport-local').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var googleConfig = {
clientID : process.env.GOOGLE_CLIENT_ID,
clientSecret : process.env.GOOGLE_CLIENT_SECRET,
callbackURL : process.env.GOOGLE_CALLBACK_URL
};
// Need user model for passport
var userModel = models.userModel;
passport.use('searchScape', new LocalStrategy(localStrategy));
passport.use('searchScapeGoogle', new GoogleStrategy(googleConfig, googleStrategy));
//Serialization
passport.serializeUser(serializeUser);
passport.deserializeUser(deserializeUser);
// Load encryption library
var bcrypt = require('bcrypt-nodejs');
// API
app.post ('/projectapi/login', passport.authenticate('searchScape'), login);
app.post ('/projectapi/logout', logout);
app.post ('/projectapi/register', register);
app.get ('/projectapi/loggedin', loggedin);
app.post("/projectapi/user", createUser)
app.get("/projectapi/user", getUsers);
app.get("/projectapi/user/:uid", findUserById);
app.get("/projectapi/user/:uid/friends", findAllFriendsForUser);
app.put("/projectapi/user/:uid/friend/:fid/add", addFriend);
app.put("/projectapi/user/:uid/friend/:fid/remove", removeFriend);
app.put("/projectapi/user/:uid", updateUser);
app.delete("/projectapi/user/:uid", deleteUser);
// Google
app.get('/auth/google', passport.authenticate('searchScapeGoogle', { scope : ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('searchScapeGoogle', {
successRedirect: '/project/index.html#/user',
failureRedirect: '/project/index.html#/login'
}));
// ----- PASSPORT FUNCTIONS ------
function authorized (req, res, next) {
if (!req.isAuthenticated()) {
res.send(401);
} else {
next();
}
}
function localStrategy(username, password, done) {
userModel
.findUserByUsername(username)
.then(
function(user) {
if(user && bcrypt.compareSync(password, user.password)) {
return done(null, user);
} else {
return done(null, false);
}
},
function(err) {
if (err) { return done(err); }
}
);
}
function serializeUser(user, done) {
done(null, user);
}
function deserializeUser(user, done) {
userModel
.findUserById(user._id)
.then(
function(resultUser){
done(null, resultUser);
},
function(err){
done(err, null);
}
);
}
function login(req, res) {
var user = req.user;
res.json(user);
}
function logout(req, res) {
req.logOut();
res.sendStatus(200);
}
function register (req, res) {
var user = req.body;
user.password = <PASSWORD>.<PASSWORD>(user.password);
userModel
.createUser(user)
.then(
function(user){
if(user){
req.login(user, function(err) {
if(err) {
res.sendStatus(400).send(err);
} else {
res.json(user);
}
});
}
}
);
}
function loggedin(req, res) {
res.send(req.isAuthenticated() ? req.user : '0');
}
// GOOGLE OAUTH
function googleStrategy(token, refreshToken, profile, done) {
userModel
.findUserByGoogleId(profile.id)
.then(
function(user) {
if(user) {
return done(null, user);
} else {
var email = profile.emails[0].value;
var emailParts = email.split("@");
var newGoogleUser = {
username: emailParts[0],
firstName: profile.name.givenName,
lastName: profile.name.familyName,
google: {
id: profile.id,
token: token
}
};
return userModel
.createUser(newGoogleUser)
.then(
function(succ) {
return done(null, succ);
},
function(err) {
return done(err, null);
}
);
}
},
function(err) {
if (err) { return done(err); }
}
)
.then(
function(user){
return done(null, user);
},
function(err){
if (err) { return done(err); }
}
);
}
// ----- CRUD OPERATIONS -----
function createUser(req, res) {
var toAdd = req.body;
toAdd.friends = [];
userModel
.createUser(toAdd)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(400);
}
);
}
function getUsers(req, res) {
var username = req.query["username"];
var password = req.query["<PASSWORD>"];
if(username && password) {
findUserByCredentials(username, password, res);
} else if(username) {
findUserByUsername(username, res);
} else {
res.send(users);
}
}
function findUserByCredentials(username, password, res) {
userModel
.findUserByCredentials(username, password)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function findUserByUsername(username, res) {
userModel
.findUserByUsername(username)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function findUserById(req, res) {
var userId = req.params["uid"];
userModel
.findUserById(userId)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function findAllFriendsForUser(req, res) {
var userId = req.params["uid"];
userModel
.findAllFriendsForUser(userId)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function addFriend(req, res) {
var userId = req.params["uid"];
var friendId = req.params["fid"];
userModel
.addFriend(userId, friendId)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
function removeFriend(req, res) {
var userId = req.params["uid"];
var friendId = req.params["fid"];
userModel
.removeFriend(userId, friendId)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
function updateUser(req, res) {
var user = req.body;
var userId = req.params["uid"];
userModel
.updateUser(userId, user)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
function deleteUser(req, res) {
var userId = req.params["uid"];
userModel
.deleteUser(userId)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
};<file_sep>module.exports = function() {
var mongoose = require("mongoose");
var PuzzleSchema = require("./puzzle.schema.server.js")();
var Puzzle = mongoose.model("Puzzle", PuzzleSchema);
var api = {
createPuzzle: createPuzzle,
findPuzzleById: findPuzzleById,
findAllPuzzlesForUser: findAllPuzzlesForUser,
updatePuzzle: updatePuzzle,
deletePuzzle: deletePuzzle
};
return api;
function createPuzzle(userId, puzzle) {
puzzle._user = userId;
return Puzzle.create(puzzle);
}
function findPuzzleById(puzzleId) {
return Puzzle.findById(puzzleId);
}
function findAllPuzzlesForUser(userId) {
return Puzzle.find({_user: userId});
}
function updatePuzzle(puzzleId, puzzle) {
return Puzzle.update(
{_id: puzzleId},
{
name: puzzle.name
}
);
}
function deletePuzzle(puzzleId) {
return Puzzle.remove({_id: puzzleId});
}
};<file_sep>(function() {
angular
.module("SearchScape")
.controller("LoginController", LoginController)
.controller("ProfileController", ProfileController)
.controller("RegisterController", RegisterController);
function LoginController(UserService, $rootScope, $location) {
var vm = this;
vm.login = login;
function login(username, password) {
if (username && password) {
vm.error = vm.usernameErr = vm.passwordErr = null;
var toLogin = {
username: username,
password: <PASSWORD>
};
UserService
.login(toLogin)
.then(
function (response) {
var user = response.data;
$rootScope.currentUser = user;
$location.url("/user/" + user._id);
},
function(error) {
vm.error = "Incorrect credentials. Try again.";
vm.usernameErr = null;
vm.passwordErr = null;
}
);
} else {
vm.error = "Missing info.";
// Handle username error
if (!username) {
vm.usernameErr = "Username required.";
} else {
vm.usernameErr = null;
}
// Handle password error
if (!password) {
vm.passwordErr = "Password required.";
} else {
vm.passwordErr = null;
}
}
}
}
function ProfileController(UserService, $routeParams, $rootScope, $location) {
var vm = this;
vm.update = update;
vm.logout = logout;
vm.unregister = unregister;
function init() {
vm.userId = $routeParams["uid"];
if (!vm.userId) {
vm.userId = $rootScope.currentUser._id;
}
UserService
.findUserById(vm.userId)
.then(
function(succ) {
vm.user = succ.data;
},
function(err) {
vm.error = "Could not load profile info.";
}
);
}
init();
function update() {
UserService
.updateUser(vm.userId, vm.user)
.then(
function(succ) {
vm.success = "Successfully update profile.";
},
function(err) {
vm.error = "Could not update profile.";
}
);
}
function logout() {
UserService
.logout()
.then(
function (response) {
$rootScope.currentUser = null;
$location.url("/");
},
function (err) {
vm.error = "Could not log out.";
}
);
}
function unregister() {
UserService
.deleteUser(vm.userId)
.then(
function(succ) {
$location.url("/login");
},
function(err) {
vm.error = "Could not unregister.";
}
)
}
}
function RegisterController(UserService, $rootScope, $location) {
var vm = this;
vm.register = register;
vm.registerAsAdmin = registerAsAdmin;
function register(fname, lname, uname, pass, vpass) {
if (uname && pass && vpass && pass === vpass) {
vm.error = vm.usernameErr = vm.passwordErr = vm.vpasswordErr = vm.matchErr = null;
var user = {
username: uname,
password: <PASSWORD>,
firstName: fname,
lastName: lname,
isAdmin: false
};
UserService
.register(user)
.then(
function(response) {
var newUser = response.data;
$rootScope.currentUser = newUser;
$location.url("/user/"+newUser._id);
},
function(err) {
vm.error = "Could not register. Username may be taken.";
}
);
} else {
vm.error = "Missing information.";
if (!uname) {
vm.usernameErr = "Username required.";
} else {
vm.usernameErr = null;
}
if (!pass) {
vm.passwordErr = "Password required.";
} else {
vm.passwordErr = null;
}
if (!vpass) {
vm.vpasswordErr = "Must verify password.";
} else {
vm.vpasswordErr = null;
}
if (pass && vpass && !(pass === vpass)) {
vm.matchErr = "Passwords do not match.";
} else {
vm.matchErr = null;
}
}
}
function registerAsAdmin(fname, lname, uname, pass, vpass) {
if (uname && pass && vpass && pass === vpass) {
vm.error = vm.usernameErr = vm.passwordErr = vm.vpasswordErr = vm.matchErr = null;
var user = {
username: uname,
password: <PASSWORD>,
firstName: fname,
lastName: lname,
isAdmin: true
};
UserService
.register(user)
.then(
function(response) {
var newUser = response.data;
$rootScope.currentUser = newUser;
$location.url("/user/"+newUser._id);
},
function(err) {
vm.error = "Could not register. Username may be taken.";
}
);
} else {
vm.error = "Missing information.";
if (!uname) {
vm.usernameErr = "Username required.";
} else {
vm.usernameErr = null;
}
if (!pass) {
vm.passwordErr = "Password required.";
} else {
vm.passwordErr = null;
}
if (!vpass) {
vm.vpasswordErr = "Must verify password.";
} else {
vm.vpasswordErr = null;
}
if (pass && vpass && !(pass === vpass)) {
vm.matchErr = "Passwords do not match.";
} else {
vm.matchErr = null;
}
}
}
}
})();<file_sep>(function() {
angular
.module("SearchScape")
.factory("UserService", UserService);
function UserService($http) {
var api = {
login: login,
logout: logout,
register: register,
createUser: createUser,
findUserByCredentials: findUserByCredentials,
findUserByUsername: findUserByUsername,
findUserById: findUserById,
findAllFriendsForUser: findAllFriendsForUser,
addFriend: addFriend,
removeFriend: removeFriend,
updateUser: updateUser,
deleteUser: deleteUser
};
return api;
function login(user) {
return $http.post("/projectapi/login", user);
}
function logout(user) {
return $http.post("/projectapi/logout");
}
function register(user) {
return $http.post("/projectapi/register", user);
}
function createUser(user) {
var url = "/projectapi/user";
return $http.post(url, user);
}
function findUserByCredentials(username, password) {
var url = "/projectapi/user?username=" + username + "&password=" + <PASSWORD>;
return $http.get(url);
}
function findUserByUsername(username) {
var url = "/projectapi/user?username=" + username;
return $http.get(url);
}
function findUserById(userId) {
var url = "/projectapi/user/" + userId;
return $http.get(url);
}
function findAllFriendsForUser(userId) {
var url = "/projectapi/user/" + userId + "/friends";
return $http.get(url);
}
function addFriend(userId, friendId) {
var url = "/projectapi/user/" + userId + "/friend/" + friendId + "/add";
return $http.put(url);
}
function removeFriend(userId, friendId) {
var url = "/projectapi/user/" + userId + "/friend/" + friendId + "/remove";
return $http.put(url);
}
function updateUser(userId, user) {
var url = "/projectapi/user/" + userId;
return $http.put(url, user);
}
function deleteUser(userId) {
var url = "/projectapi/user/" + userId;
return $http.delete(url);
}
}
})();<file_sep>(function() {
angular
.module("WebAppMaker")
.controller("PageListController", PageListController)
.controller("NewPageController", NewPageController)
.controller("EditPageController", EditPageController);
function EditPageController($routeParams, PageService, $location) {
var vm = this;
vm.userId = null;
vm.webId = null;
vm.pageId = null;
vm.page = null;
vm.applyChanges = applyChanges;
vm.deletePage = deletePage;
function init() {
vm.userId = $routeParams["uid"];
vm.webId = $routeParams["wid"];
vm.pageId = $routeParams["pid"];
PageService
.findPageById(vm.pageId)
.then(
function(response) {
vm.page = response.data;
},
function(error) {
vm.error = error.data;
}
);
}
init();
function applyChanges() {
if (vm.page.name && !(vm.page.name == "")) {
vm.error = null;
vm.nameErr = null;
PageService
.updatePage(vm.pageId, vm.page)
.then(
function (response) {
$location.url("/user/" + vm.userId + "/website/" + vm.webId + "/page");
},
function (error) {
vm.error = error.data;
}
);
} else {
vm.error = "Could not update page.";
vm.nameErr = "Name required.";
}
}
function deletePage() {
PageService
.deletePage(vm.pageId)
.then(
function(response) {
$location.url("/user/" + vm.userId + "/website/" + vm.webId + "/page");
},
function(error) {
vm.error = error.data;
}
);
}
}
function PageListController($routeParams, PageService) {
var vm = this;
vm.webId = null;
vm.userId = null;
var uid = $routeParams["uid"];
var wid = $routeParams["wid"];
//Event Handlers
function init() {
PageService
.findPagesByWebsiteId(wid)
.then(
function(response) {
vm.pages = response.data;
},
function(error) {
vm.error = error.data;
}
);
vm.userId = uid;
vm.webId = wid;
}
init();
}
function NewPageController($routeParams, PageService, $location) {
var vm = this;
vm.addPage = addPage;
vm.userId = null;
vm.webId = null;
function init() {
vm.userId = $routeParams["uid"];
vm.webId = $routeParams["wid"];
}
init();
/**
* Add the new page to the list
*
* @param newName The name of the new page
* @param newPageDescription The description of the new page
*/
function addPage(newName, newPageDescription) {
if (newName && !(newName == "")) {
vm.error = null;
vm.nameErr = null;
var toAdd = {_website: vm.webId + "", name: newName + "", description: newPageDescription + ""};
PageService
.createPage(vm.webId, toAdd)
.then(
function (response) {
$location.url("/user/" + vm.userId + "/website/" + vm.webId + "/page");
},
function (error) {
vm.error = error.data;
}
);
} else {
vm.error = "Could not create page.";
vm.nameErr = "Name required.";
}
}
}
})();<file_sep>module.exports = function() {
var mongoose = require("mongoose");
var WidgetSchema = require("./widget.schema.server.js")();
var Widget = mongoose.model("Widget", WidgetSchema);
var api = {
createWidget: createWidget,
findAllWidgetsForPage: findAllWidgetsForPage,
findWidgetById: findWidgetById,
updateWidget: updateWidget,
deleteWidget: deleteWidget,
reorderWidget: reorderWidget
};
return api;
/**
* Creates new widget instance for parent page whose _id is pageId
*
* @param pageId The id of the page this widget belongs to
* @param widget The widget to be created
*/
function createWidget(pageId, widget) {
widget._page = pageId;
return Widget.count({_page: pageId}).then(
function(count) {
widget.order = count;
return Widget.create(widget);
}
);
}
/**
* Retrieves all widgets for parent page whose _id is pageId
*
* @param pageId The id of the page whose widgets are being retrieved
*/
function findAllWidgetsForPage(pageId) {
return Widget.find({_page: pageId}).sort({order: 1});
}
/**
* Retrieves widget whose _id is widgetId
*
* @param widgetId The id of the widget to be found
*/
function findWidgetById(widgetId) {
return Widget.findById(widgetId);
}
/**
* Updates widget whose _id is widgetId
*
* @param widgetId The id of the widget to be updated
* @param widget The widget to update it to
*/
function updateWidget(widgetId, widget) {
switch(widget.type) {
case 'HEADING':
return Widget.update(
{_id: widgetId},
{
name: widget.name,
text: widget.text,
size: widget.size,
placeholder: widget.placeholder,
class: widget.class,
icon: widget.icon,
deletable: widget.deletable,
formatted: widget.formatted,
order: widget.order
}
);
case 'IMAGE':
return Widget.update(
{_id: widgetId},
{
name: widget.name,
text: widget.text,
placeholder: widget.placeholder,
description: widget.description,
url: widget.url,
width: widget.width,
class: widget.class,
icon: widget.icon,
deletable: widget.deletable,
formatted: widget.formatted,
order: widget.order
}
);
case 'YOUTUBE':
return Widget.update(
{_id: widgetId},
{
name: widget.name,
text: widget.text,
url: widget.url,
width: widget.width,
class: widget.class,
icon: widget.icon,
deletable: widget.deletable,
formatted: widget.formatted,
order: widget.order
}
);
case 'HTML':
return Widget.update(
{_id: widgetId},
{
name: widget.name,
text: widget.text,
placeholder: widget.placeholder,
class: widget.class,
icon: widget.icon,
deletable: widget.deletable,
order: widget.order
}
);
case 'INPUT':
return Widget.update(
{_id: widgetId},
{
name: widget.name,
text: widget.text,
placeholder: widget.placeholder,
rows: widget.rows,
class: widget.class,
icon: widget.icon,
deletable: widget.deletable,
formatted: widget.formatted,
order: widget.order
}
);
}
}
/**
* Removes widget whose _id is widgetId
*
* @param widgetId The id of the widget to be deleted
*/
function deleteWidget(widgetId) {
return Widget.remove({_id: widgetId});
}
/**
* Modifies the order of widget at position start into final position end in page whose _id is pageId
*
* @param start The current location of the widget
* @param end The desired location of the widget
*/
function reorderWidget(pageId, start, end) {
return Widget.update({order : start, _page: pageId}, {order : -1}).then(
function(success) {
return Widget.update({order : end, _page: pageId}, {order: start}).then(
function(success) {
return Widget.update({order : -1, _page: pageId}, {order : end});
}
);
}
);
// I CAN'T GET THIS TO WORK PROPERLY
// var i;
//
// if (start < end) {
// for (i = start; i <= end; i++) {
// return reorderHelper(i, start, end, pageId).then(
// function(succ) {
// }
// );
// }
// } else if (end < start) {
// for (i = end; i <= start; i++) {
// return reorderHelper(i, start, end, pageId).then(
// function(succ) {
// }
// );
// }
// }
}
function reorderHelper(index, start, end, pageId) {
if (start < end) {
if (index == start) {
return Widget.update({_page: pageId, order: start}, {order: end});
} else if (index > start && index <= end) {
return Widget.update({_page: pageId, order: index}, {order: index-1});
}
} else if (end < start) {
if (index == end) {
return Widget.update({_page: pageId, order: end}, {order: start});
} else if (index > end && index <= start) {
return Widget.update({_page: pageId, order:index}, {order:index+1});
}
}
}
};<file_sep>module.exports = function() {
var mongoose = require("mongoose");
var userModel = require("./user/user.model.server.js")();
var puzzleModel = require("./puzzle/puzzle.model.server")();
var messageModel = require("./message/message.model.server")();
var commentModel = require("./comment/comment.model.server")();
var connectionString = 'mongodb://127.0.0.1:27017/projectJackDavis';
if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
connectionString = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
process.env.OPENSHIFT_APP_NAME;
}
mongoose.connect(connectionString);
var models = {
userModel: userModel,
puzzleModel: puzzleModel,
messageModel: messageModel,
commentModel: commentModel
};
return models;
};<file_sep>module.exports = function(app, models) {
var puzzleModel = models.puzzleModel;
app.post("/api/user/:uid/puzzle", createPuzzle);
app.get("/api/puzzle/:pid", findPuzzleById);
app.get("/api/user/:uid/puzzle", findAllPuzzlesForUser);
app.put("/api/puzzle/:pid", updatePuzzle);
app.delete("/api/puzzle/:pid", deletePuzzle);
function createPuzzle(req, res) {
var toAdd = req.body;
var userId = req.params["uid"];
puzzleModel
.createPuzzle(userId, toAdd)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(400);
}
);
}
function findPuzzleById(req, res) {
var puzzleId = req.params["pid"];
puzzleModel
.findPuzzleById(puzzleId)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function findAllPuzzlesForUser(req, res) {
var userId = req.params["uid"];
puzzleModel
.findAllPuzzlesForUser(userId)
.then(
function(succ) {
res.send(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function updatePuzzle(req, res) {
var puzzleId = req.params["pid"];
var puzzle = req.body;
puzzleModel
.updatePuzzle(puzzleId, puzzle)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
function deletePuzzle(req, res) {
var puzzleId = req.params["pid"];
puzzleModel
.deletePuzzle(puzzleId)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
};<file_sep>module.exports = function(app, models) {
var commentModel = models.commentModel;
app.post("/projectapi/comment", createComment);
app.get("/projectapi/comment/:cid", findCommentById);
app.get("/projectapi/comment/all/:pid", findAllCommentsForPuzzle);
app.put("/projectapi/comment/:cid", updateComment);
app.delete("/projectapi/comment/:cid", deleteComment);
function createComment(req, res) {
var comment = req.body;
commentModel
.createComment(comment)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(400);
}
);
}
function findCommentById(req, res) {
var commentId = req.params["cid"];
commentModel
.findCommentById(commentId)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function findAllCommentsForPuzzle(req, res) {
var puzzleId = req.params["pid"];
commentModel
.findAllCommentsForPuzzle(puzzleId)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function updateComment(req, res) {
var commentId = req.params["cid"];
var comment = req.body;
commentModel
.updateComment(commentId, comment)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
function deleteComment(req, res) {
var commentId = req.params["cid"];
commentModel
.deleteComment(commentId)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
};<file_sep>(function() {
angular
.module("WebAppMaker")
.factory("UserService", UserService);
function UserService($http) {
var api = {
createUser: createUser,
findUserByCredentials: findUserByCredentials,
login: login,
logout: logout,
register: register,
findUserByID: findUserByID,
updateUser: updateUser,
deleteUser: deleteUser,
findUserByUsername: findUserByUsername
};
return api;
function login(username, password) {
var url = "/api/login";
var user = {
username : username,
password : <PASSWORD>
};
return $http.post(url, user);
}
function logout() {
return $http.post("/api/logout");
}
function register(user) {
return $http.post("/api/register", user);
}
/**
* Add a new User to the users array
*
* @param newid The new User's ID
* @param newusername The new User's username
* @param newpassword The new User's password
* @param newfirstName The new User's first name
* @param newlastName The new User's last name
* @returns {*} The new user
*/
function createUser(user) {
var url = "/api/user";
return $http.post(url, user);
}
/**
* Find a User given their credentials
*
* @param username The User's username
* @param password The User's password
* @returns {*} The correct User if the credentials match one. Otherwise, returns null.
*/
function findUserByCredentials(username, password) {
var url = "/api/user?username=" + username + "&password=" + password;
return $http.get(url);
}
/**
* Find a User given their credentials
*
* @param id The id to search for
* @returns {*} The correct User if the ID matches one. Otherwise, returns null.
*/
function findUserByID(id) {
var url = "/api/user/" + id;
return $http.get(url);
}
/**
* Update a User based on their ID
*
* @param id The ID to look for
* @param newUser The data to copy over to the existing User
* @returns {boolean} Whether the update was successful or not
*/
function updateUser(id, newUser) {
var url = "/api/user/" + id;
return $http.put(url, newUser);
}
/**
* Delete a user based on the id
*
* @param id The id of the User to be deleted
* @returns {boolean} Whether the deletion was successful
*/
function deleteUser(id) {
var url = "/api/user/" + id;
return $http.delete(url);
}
/**
* Find a user by their username
*
* @param username The username of the desired user
* @returns {*} The user if found, or an empty object if not
*/
function findUserByUsername(username) {
var url = "/api/user?username=" + username;
return $http.get(url);
}
}
})();<file_sep>module.exports = function(app, models) {
var messageModel = models.messageModel;
app.post("/projectapi/message", createMessage);
app.get("/projectapi/message/id/:mid", findMessageById);
app.get("/projectapi/message/auth/:aid/reci/:rid", findAllMessagesForUsers);
app.put("/projectapi/message/:mid", updateMessage);
app.delete("/projectapi/message/:mid", deleteMessage);
function createMessage(req, res) {
var message = req.body;
messageModel
.createMessage(message)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(400);
}
);
}
function findMessageById(req, res) {
var messageId = req.params["mid"];
messageModel
.findMessageById(messageId)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function findAllMessagesForUsers(req, res) {
var userOne = req.params["aid"];
var userTwo = req.params["rid"];
messageModel
.findAllMessagesForUsers(userOne, userTwo)
.then(
function(succ) {
res.json(succ);
},
function(err) {
res.sendStatus(404);
}
);
}
function updateMessage(req, res) {
var messageId = req.params["mid"];
var message = req.body;
messageModel
.updateMessage(messageId, message)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
function deleteMessage(req, res) {
var messageId = req.params["mid"];
messageModel
.deleteMessage(messageId)
.then(
function(succ) {
res.sendStatus(200);
},
function(err) {
res.sendStatus(400);
}
);
}
};<file_sep>module.exports = function() {
var mongoose = require("mongoose");
var MessageSchema = mongoose.Schema({
author: {type: mongoose.Schema.Types.ObjectId, ref: "projectUser"},
recipient: {type: mongoose.Schema.Types.ObjectId, ref: "projectUser"},
text: String,
url: String,
urlAuthor : String,
date: Date
}, {collection: "message"});
return MessageSchema;
};<file_sep>module.exports = function() {
var mongoose = require("mongoose");
var UserSchema = require("./user.schema.server.js")();
var ProjectUser = mongoose.model("ProjectUser", UserSchema);
var api = {
createUser: createUser,
findUserById: findUserById,
findUserByUsername: findUserByUsername,
findUserByCredentials: findUserByCredentials,
findAllFriendsForUser: findAllFriendsForUser,
addFriend: addFriend,
removeFriend: removeFriend,
updateUser: updateUser,
deleteUser: deleteUser,
findUserByGoogleId: findUserByGoogleId
};
return api;
function createUser(user) {
return ProjectUser.findOne({username: user.username}).then(
function(succ) {
if (!succ) {
return ProjectUser.create(user);
}
}
);
}
function findUserById(userId) {
return ProjectUser.findById(userId);
}
function findUserByUsername(username) {
return ProjectUser.findOne({username: username});
}
function findUserByCredentials(username, password) {
return ProjectUser.findOne({username: username, password: <PASSWORD>});
}
function findAllFriendsForUser(userId) {
return ProjectUser.findById(userId).then(
function(succ) {
return succ.friends;
}
);
}
function addFriend(userId, friendId) {
return ProjectUser.update(
{_id: userId},
{$push: {friends: friendId}}
);
}
function removeFriend(userId, friendId) {
return ProjectUser.update(
{_id: userId},
{$pull: {friends: friendId}}
);
}
function updateUser(userId, user) {
return ProjectUser.update({_id: userId}, {
username: user.username,
firstName: user.firstName,
lastName: user.lastName
});
}
function deleteUser(userId) {
return ProjectUser.remove({_id: userId});
}
function findUserByGoogleId(profileId) {
return ProjectUser.findOne({'google.id': profileId});
}
};<file_sep>(function() {
angular
.module("WebAppMaker")
.controller("WebsiteListController", WebsiteListController)
.controller("NewWebsiteController", NewWebsiteController)
.controller("EditWebsiteController", EditWebsiteController);
function EditWebsiteController($routeParams, $location, WebsiteService) {
var vm = this;
vm.userId = $routeParams["uid"];
vm.webId = $routeParams["wid"];
vm.updateWebsite = updateWebsite;
vm.deleteWebsite = deleteWebsite;
function init() {
WebsiteService
.findWebsiteByID(vm.webId)
.then(
function(response) {
vm.website = response.data;
},
function(error) {
vm.error = error.data;
}
);
}
init();
function updateWebsite() {
if (vm.website.name) {
vm.error = null;
vm.nameErr = null;
var result = WebsiteService.updateWebsite(vm.website._id, vm.website);
WebsiteService
.updateWebsite(vm.website._id, vm.website)
.then(
function (response) {
vm.success = "Update successful";
},
function (error) {
vm.error = error.data;
}
);
} else {
vm.error = "Could not edit.";
vm.nameErr = "Must have a name.";
}
}
function deleteWebsite() {
WebsiteService
.deleteWebsite(vm.webId)
.then(
function(response) {
$location.url("/user/" + vm.userId + "/website");
},
function(error) {
vm.error = error.data;
}
);
}
}
function WebsiteListController($routeParams, WebsiteService) {
var vm = this;
vm.userId = $routeParams["uid"];
// Event handlers
function init() {
WebsiteService
.findWebsitesByUser(vm.userId)
.then(
function(response) {
vm.websites = response.data;
},
function(error) {
vm.error = error.data;
}
);
}
init();
}
function NewWebsiteController($routeParams, WebsiteService, $location) {
var vm = this;
vm.userId = $routeParams["uid"];
vm.addWebsite = addWebsite;
function addWebsite(newName, newDescription) {
if (newName) {
vm.error = null;
vm.nameErr = null;
var toAdd = {_user: vm.userId, name: newName, description: newDescription};
WebsiteService
.createWebsite(vm.userId, toAdd)
.then(
function (response) {
$location.url("/user/" + vm.userId + "/website");
},
function (error) {
vm.error = error.data;
}
);
} else {
vm.error = "Could not create website."
vm.nameErr = "Name required.";
}
}
}
})();<file_sep>(function() {
angular
.module("SearchScape")
.controller("NewFriendController", NewFriendController)
.controller("FriendListController", FriendListController)
.controller("FriendProfileController", FriendProfileController)
.controller("MessageFriendController", MessageFriendController);
function NewFriendController(UserService, $routeParams) {
var vm = this;
vm.search = search;
function init() {
vm.userId = $routeParams["uid"];
}
init();
function search(request) {
if (request) {
UserService
.findUserByUsername(request)
.then(
function (succ) {
vm.error = null;
vm.results = succ.data;
},
function (err) {
vm.error = "Did not find a user with that username.";
}
);
} else {
vm.error = "Must have a search term.";
}
}
}
function FriendListController(UserService, $routeParams) {
var vm = this;
function init() {
vm.userId = $routeParams["uid"];
vm.friends = [];
UserService
.findAllFriendsForUser(vm.userId)
.then(
function(succ) {
vm.friendIds = succ.data;
initHelper(0);
},
function(err) {
vm.error = "Could not retrieve friend list.";
}
);
}
init();
function initHelper(index) {
if (index < vm.friendIds.length) {
UserService
.findUserById(vm.friendIds[index])
.then(
function(succ) {
vm.friends.push(succ.data);
initHelper(index+1);
}
);
}
}
}
function FriendProfileController(UserService, $routeParams, PuzzleService, $location) {
var vm = this;
vm.addFriend = addFriend;
vm.removeFriend = removeFriend;
vm.deleteUser = deleteUser;
vm.removePuzzle = removePuzzle;
function init() {
vm.userId = $routeParams["uid"];
vm.friendId = $routeParams["fid"];
return UserService
.findUserById(vm.friendId)
.then(
function(succ) {
vm.friend = succ.data;
return UserService
.findUserById(vm.userId);
},
function(err) {
vm.error = "Could not load profile data.";
}
)
.then(
function(succ) {
vm.user = succ.data;
return PuzzleService.findAllPuzzlesForUser(vm.friend._id)
}
)
.then(
function(succ) {
vm.friendPuzzles = succ.data;
}
);
}
init();
function addFriend() {
if (vm.user.friends.indexOf(vm.friendId) === -1) {
UserService
.addFriend(vm.userId, vm.friendId)
.then(
function (succ) {
vm.success = "Added " + vm.friend.username + " as a friend.";
},
function (err) {
vm.error = "Could not add friend.";
}
);
} else {
vm.error = vm.friend.username + " is already a friend.";
}
}
function removeFriend() {
UserService
.removeFriend(vm.userId, vm.friendId)
.then(
function(succ) {
vm.success = "Removed " + vm.friend.username + " as a friend.";
},
function(err) {
vm.error = "Failed to remove friend.";
}
);
}
function deleteUser() {
// ADMIN FUNCTION ONLY
UserService
.deleteUser(vm.friendId)
.then(
function(succ) {
$location.url("/user/" + vm.userId + "/friend");
},
function(err) {
vm.error = "Could not remove user.";
}
);
}
function removePuzzle(puzzleId) {
// ADMIN FUNCTION ONLY
PuzzleService
.deletePuzzle(puzzleId)
.then(
function(succ) {
init();
},
function(err) {
vm.error = "Could not remove puzzle.";
}
);
}
}
function MessageFriendController(MessageService, $routeParams) {
var vm = this;
vm.sendMessage = sendMessage;
vm.deleteMessage = deleteMessage;
function init() {
vm.userId = $routeParams["uid"];
vm.friendId = $routeParams["fid"];
vm.messageText = "";
MessageService
.findAllMessagesForUsers(vm.userId, vm.friendId)
.then(
function(succ) {
vm.messages = succ.data;
},
function(err) {
vm.error = "Could not retrieve messages.";
}
);
}
return init();
function sendMessage() {
if (vm.messageText) {
var message = {author: vm.userId, recipient: vm.friendId, text: vm.messageText, date: getTodayDate()};
MessageService
.createMessage(message)
.then(
function(succ) {
init(); // Refresh, show new messages.
},
function(err) {
vm.error = "Could not send message.";
}
);
} else {
vm.error = "Need message body to send!";
}
}
function deleteMessage(messageId) {
MessageService
.deleteMessage(messageId)
.then(
function(succ) {
init();
},
function(err) {
vm.error = "Could not delete message.";
}
);
}
// Ripped from: http://stackoverflow.com/questions/1531093/how-to-get-current-date-in-javascript
function getTodayDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
return today;
}
}
})();<file_sep>(function() {
angular
.module("WebAppMaker")
.factory("WebsiteService", WebsiteService);
function WebsiteService($http) {
var vm = this;
// API
var api = {
createWebsite: createWebsite,
findWebsitesByUser: findWebsitesByUser,
findWebsiteByID: findWebsiteByID,
updateWebsite: updateWebsite,
deleteWebsite: deleteWebsite
};
return api;
/**
* Add a new website to the list
*
* @param userId The user ID of whoever created this website
* @param website The new website's object
* @returns {*} The new website
*/
function createWebsite(userId, website) {
website.developerId = userId;
var url = "/api/user/" + userId + "/website";
return $http.post(url, website);
}
/**
* Find all websites from a developer
*
* @param userId The developer's user ID
* @returns {*} The websites in question, or an empty array if there are none
*/
function findWebsitesByUser(userId) {
var url = "/api/user/" + userId + "/website";
return $http.get(url);
}
/**
* Find a website from its website ID
*
* @param websiteId The ID of the desired website
* @returns {*} The website in question, or null if it does not exist
*/
function findWebsiteByID(websiteId) {
var url = "/api/website/" + websiteId;
return $http.get(url);
}
/**
* Update a website to the desired object based on its website ID
*
* @param websiteId The website ID of the website to be updated
* @param website The new information
* @returns {boolean} Whether the update was successful
*/
function updateWebsite(websiteId, website) {
var url = "/api/website/" + websiteId;
return $http.put(url, website);
}
/**
* Delete a website from its ID
*
* @param websiteId The ID of the website to be deleted
* @returns {boolean} Whether the deletion was successful
*/
function deleteWebsite(websiteId) {
var url = "/api/website/" + websiteId;
return $http.delete(url);
}
}
})();<file_sep>(function() {
angular
.module("SearchScape")
.controller("NewPuzzleController", NewPuzzleController)
.controller("PuzzleListController", PuzzleListController)
.controller("SolvePuzzleController", SolvePuzzleController)
.controller("PuzzleCommentController", PuzzleCommentController)
.controller("EditPuzzleController", EditPuzzleController)
.controller("SendPuzzleController", SendPuzzleController);
function NewPuzzleController(PuzzleService, $routeParams, $location) {
var vm = this;
vm.assignWords = assignWords;
vm.backToAssign = backToAssign;
vm.build = build;
vm.goToNaming = goToNaming;
vm.backToBuild = backToBuild;
vm.finish = finish;
function init() {
vm.userId = $routeParams["uid"];
vm.choosing = true;
vm.building = false;
vm.naming = false;
vm.word1 = vm.word2 = vm.word3 = vm.word4 = vm.word5 = null;
vm.grid = [];
for (var i = 0; i < 6; i++) {
vm.grid.push([]);
for(var j = 0; j < 5; j++) {
vm.grid[i].push("");
}
}
}
init();
function checkDiff() {
vm.wordOneErr = vm.wordTwoErr = vm.wordThreeErr = vm.wordFourErr = vm.wordFiveErr = null;
if (vm.words.length != 5) {
return false;
}
for(var wordIndex in vm.words) {
if (!vm.words[wordIndex]) {
return false;
}
}
for(var i in vm.words) {
for(var j = i+1; j < vm.words.length; j++) {
if (vm.words[i] === vm.words[j]) {
return false;
}
}
}
return true;
}
function assignWords() {
vm.words = [vm.word1, vm.word2, vm.word3, vm.word4, vm.word5];
if (checkDiff()) {
vm.choosing = false;
vm.building = true;
vm.naming = false;
} else {
if (!vm.word1) {
vm.wordOneErr = "You need a word there, buddyboy.";
} else {
vm.wordOneErr = null;
}
if (!vm.word2) {
vm.wordTwoErr = "C'mon, just put a word there.";
} else {
vm.wordTwoErr = null;
}
if (!vm.word3) {
vm.wordThreeErr = "Need word.";
} else {
vm.wordThreeErr = null;
}
if (!vm.word4) {
vm.wordFourErr = "Need word.";
} else {
vm.wordFourErr = null;
}
if (!vm.word5) {
vm.wordFiveErr = "A word would really tie the room together.";
} else {
vm.wordFiveErr = null;
}
}
}
function backToAssign() {
vm.choosing = true;
vm.building = false;
vm.naming = false;
}
function backToBuild() {
vm.choosing = false;
vm.building = true;
vm.naming = false;
}
function goToNaming() {
vm.puzzle = {name: "", _user: vm.userId, grid: vm.grid, words: vm.words};
vm.choosing = false;
vm.building = false;
vm.naming = true;
}
function build() {
vm.error = null;
for(var i = 0; i < vm.grid.length; i++) {
for(var j = 0; j < vm.grid[i].length; j++) {
if (!vm.grid[i][j] || vm.grid[i][j] === '') {
vm.error = "Incomplete puzzle.";
}
}
}
if (!vm.error) {
vm.goToNaming();
}
}
function finish() {
if (scanForWords()) {
PuzzleService
.createPuzzle(vm.userId, vm.puzzle)
.then(
function (succ) {
$location.url("/user/" + vm.userId + "/puzzle");
},
function (err) {
vm.error = "Could not create puzzle.";
}
);
} else {
vm.error = "This puzzle cannot be solved.";
}
}
function scanForWords() {
// Set up array of bools to make sure all words are accounted for
var verify = [];
for(var i in vm.words) {
verify.push(false);
}
for(var wordIndex in vm.words) { // Iterate through words
for(var row = 0; row < vm.grid.length; row++) { // Iterate through rows
for(var col = 0; col < vm.grid[row].length; col++) { // Iterate through columns
if (vm.grid[row][col] === vm.words[wordIndex].charAt(0)) { // Check if this is the beginning of word
if (scanAllDirections(row, col, wordIndex) === true) {
verify[wordIndex] = true;
}
}
}
}
}
for(var j in verify) {
if (verify[j] === false) {
return false;
}
return true;
}
}
function scanAllDirections(row, col, wordIndex) {
// 1 : East
// 2 : SouthEast
// 3 : South
// 4 : SouthWest
// 5 : West
// 6 : NorthWest
// 7 : North
// 8 : NorthEast
directionCodes = [1, 2, 3, 4, 5, 6, 7, 8];
word = vm.words[wordIndex];
// Scan in each direction one at a time
for(var dir = 0; dir < directionCodes.length; dir++) {
if (searchInLine(word, directionCodes[dir], row, col)) {
return true;
}
}
return false;
}
function searchInLine(word, dir, row, col) {
var myRow = row;
var myCol = col;
for(var c = 0; c < word.length; c++) {
if (word.charAt(c) === vm.grid[myRow][myCol] && c === word.length-1) { // Base case
return true;
} else {
if (word.charAt(c) === vm.grid[myRow][myCol]) {
var nextCoords = nextInDir(dir, myRow, myCol);
if (0 <= nextCoords[0] && nextCoords[0] <= 5 && 0 <= nextCoords[1] && nextCoords[1] <= 4) {
myRow = nextCoords[0];
myCol = nextCoords[1];
} else {
return false;
}
} else {
return false;
}
}
}
}
function nextInDir(dir, row, col) {
var returnPckg = [];
switch(dir) {
case 1:
returnPckg = [row, col+1];
break;
case 2:
returnPckg = [row+1, col+1];
break;
case 3:
returnPckg = [row+1, col];
break;
case 4:
returnPckg = [row+1, col-1];
break;
case 5:
returnPckg = [row, col-1];
break;
case 6:
returnPckg = [row-1, col-1];
break;
case 7:
returnPckg = [row-1, col];
break;
case 8:
returnPckg = [row-1, col+1];
break;
}
return returnPckg;
}
}
function PuzzleListController(PuzzleService, $routeParams) {
var vm = this;
vm.deletePuzzle = deletePuzzle;
// vm.puzzles = [];
function init() {
vm.userId = $routeParams["uid"];
PuzzleService
.findAllPuzzlesForUser(vm.userId)
.then(
function(succ) {
vm.puzzles = succ.data;
// initHelper(0);
},
function(err) {
vm.error = "Could not retrieve puzzles.";
}
)
}
init();
function initHelper(index) {
if (index < vm.puzzleIds.length) {
PuzzleService
.findPuzzleById(vm.puzzleIds[index])
.then(
function(succ) {
vm.puzzles.push(succ.data);
initHelper(index+1);
}
);
}
}
function deletePuzzle(puzzleId) {
PuzzleService
.deletePuzzle(puzzleId)
.then(
function(succ) {
init();
},
function(err) {
vm.error = "Could not delete puzzle.";
}
)
}
}
function SolvePuzzleController(PuzzleService, $routeParams, $rootScope, $location) {
var vm = this;
vm.log = log;
vm.clearQueue = clearQueue;
vm.calculateLastPosition = calculateLastPosition;
function init() {
vm.userId = $routeParams["uid"];
vm.puzzleId = $routeParams["pid"];
vm.moveQueue = [];
vm.checkList = [];
PuzzleService
.findPuzzleById(vm.puzzleId)
.then(
function(succ) {
vm.puzzle = succ.data;
prepareGrid();
},
function(err) {
vm.error = "Could not load puzzle.";
}
);
}
init();
// SINCE MONGODB FEELS LIKE TURNING ARRAYS OF STRINGS INTO GIANT STRINGS, I HAVE TO FIX THAT >:(
function prepareGrid() {
for(var i in vm.puzzle.grid) {
vm.puzzle.grid[i] = vm.puzzle.grid[i].split(",");
}
}
function log(row, col) {
if (authorizedMove(row, col)) {
vm.moveQueue.push({row: row, col: col});
checkWord();
} else {
clearQueue();
}
vm.cur = addUpWord();
}
function calculateLastPosition() {
if (vm.userId === vm.puzzle._user) {
$location.url("/user/" + vm.userId + "/puzzle");
} else {
$location.url("/user/" + vm.userId + "/friend/" + vm.puzzle._user);
}
}
function authorizedMove(row, col) {
if (vm.moveQueue.length == 0) {
return true;
} else {
return adjacent(vm.moveQueue[vm.moveQueue.length-1], {row: row, col: col});
}
}
function adjacent(moveOne, moveTwo) {
return Math.abs(moveOne.row-moveTwo.row) <= 1 && Math.abs(moveOne.col-moveTwo.col) <= 1;
}
function checkWord() {
for (var wordIndex in vm.puzzle.words) {
if (vm.puzzle.words[wordIndex] === addUpWord()
&& vm.checkList.indexOf(vm.puzzle.words[wordIndex]) === -1) {
vm.checkList.push(vm.puzzle.words[wordIndex]);
clearQueue();
if (checkWin()) {
win();
}
}
}
}
function addUpWord() {
var result = "";
for (var i in vm.moveQueue) {
result += vm.puzzle.grid[vm.moveQueue[i].row][vm.moveQueue[i].col];
}
return result;
}
function checkWin() {
return vm.checkList.length === vm.puzzle.words.length;
}
function clearQueue() {
vm.moveQueue = [];
vm.cur = "";
}
function win() {
vm.success = "You won!";
}
}
function PuzzleCommentController(UserService, CommentService, $routeParams) {
var vm = this;
vm.submitComment = submitComment;
vm.deleteComment = deleteComment;
vm.authorNames = [];
function init() {
vm.userId = $routeParams["uid"];
vm.puzzleId = $routeParams["pid"];
vm.myComment = "";
CommentService
.findAllCommentsForPuzzle(vm.puzzleId)
.then(
function(succ) {
vm.comments = succ.data;
grabAuthorUsernames(0);
},
function(err) {
vm.error = "Could not load comments.";
}
);
}
init();
function submitComment() {
if (vm.myComment) {
var comment = {author: vm.userId, _puzzle: vm.puzzleId, text: vm.myComment, date: getTodayDate()};
CommentService
.createComment(comment)
.then(
function(succ) {
init();
},
function(err) {
vm.error = "Could not submit comment.";
}
);
} else {
vm.error = "Need comment to submit.";
}
}
function deleteComment(commentId) {
CommentService
.deleteComment(commentId)
.then(
function(succ) {
init();
},
function(err) {
vm.error = "Could not delete comment.";
}
);
}
function grabAuthorUsernames(index) {
if (index < vm.comments.length) {
UserService
.findUserById(vm.comments[index].author)
.then(
function(succ) {
vm.authorNames.push({id: vm.comments[index]._id, author: succ.data.username});
grabAuthorUsernames(index+1);
},
function(err) {
vm.error = "Could not load author usernames.";
}
);
} else {
UserService
.findUserById(vm.userId)
.then(
function(succ) {
vm.user = succ.data;
},
function(err) {
vm.error = "Could not retrieve user.";
}
);
}
}
function getAuthorUsername(commentId) {
for(var i in vm.authorNames) {
if (vm.authorNames[i].id === commentId) {
return vm.authorNames[i].author;
}
}
}
// Ripped from: http://stackoverflow.com/questions/1531093/how-to-get-current-date-in-javascript
function getTodayDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
return today;
}
}
function EditPuzzleController(PuzzleService, $routeParams, $location) {
var vm = this;
vm.updatePuzzle = updatePuzzle;
function init() {
vm.userId = $routeParams["uid"];
vm.puzzleId = $routeParams["pid"];
vm.copyGrid = new Array(6);
PuzzleService
.findPuzzleById(vm.puzzleId)
.then(
function(succ) {
vm.puzzle = succ.data;
prepareGrid();
},
function(err) {
vm.error = "Could not retrieve puzzle data.";
}
);
}
init();
function updatePuzzle() {
if (checkValidity()) {
PuzzleService
.updatePuzzle(vm.puzzleId, vm.puzzle)
.then(
function(succ) {
$location.url("/user/" + vm.userId + "/puzzle");
},
function(err) {
vm.error = "Could not update puzzle.";
}
);
} else {
vm.error = "Missing information.";
}
}
function checkValidity() {
for(var i in vm.puzzle.words) {
if (!vm.puzzle.words[i] || vm.puzzle.words[i] === "") {
return false;
}
}
for(var j in vm.puzzle.grid) {
for(var k in vm.puzzle.grid[j]) {
if (!vm.puzzle.grid[j][k] || vm.puzzle.grid[j][k] === "") {
return false;
}
}
}
if (!vm.puzzle.name || vm.puzzle.name === "") {
return false;
}
return true;
}
// SINCE MONGODB FEELS LIKE TURNING ARRAYS OF STRINGS INTO GIANT STRINGS, I HAVE TO FIX THAT >:(
function prepareGrid() {
for(var i in vm.puzzle.grid) {
vm.copyGrid[i] = vm.puzzle.grid[i].split(",");
}
}
}
function SendPuzzleController(UserService, MessageService, $location, $routeParams) {
var vm = this;
vm.sendPuzzle = sendPuzzle;
function init() {
vm.userId = $routeParams["uid"];
vm.puzzleId = $routeParams["pid"];
vm.friends = [];
UserService
.findAllFriendsForUser(vm.userId)
.then(
function(succ) {
vm.friendIds = succ.data;
initHelper(0);
},
function(err) {
vm.error = "Could not retrieve friend list.";
}
);
}
init();
function initHelper(index) {
if (index < vm.friendIds.length) {
UserService
.findUserById(vm.friendIds[index])
.then(
function(succ) {
vm.friends.push(succ.data);
initHelper(index+1);
}
);
}
}
function sendPuzzle(friendId) {
var myUrl = "#/user/" + friendId + "/puzzle/" + vm.puzzleId;
var authorUrl = "#/user/" + vm.userId + "/puzzle/" + vm.puzzleId;
var message = {author: vm.userId, recipient: friendId, text: "Puzzle Link", url: myUrl,
urlAuthor: authorUrl, date: getTodayDate()};
MessageService
.createMessage(message)
.then(
function(succ) {
$location.url("/user/" + vm.userId + "/friend/" + friendId + "/message");
},
function(err) {
vm.error = "Could not send puzzle.";
}
);
}
// Ripped from: http://stackoverflow.com/questions/1531093/how-to-get-current-date-in-javascript
function getTodayDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
return today;
}
}
})();<file_sep>(function () {
angular
.module("SearchScape")
.factory("MessageService", MessageService);
function MessageService($http) {
var api = {
createMessage: createMessage,
findMessageById: findMessageById,
findAllMessagesForUsers: findAllMessagesForUsers,
updateMessage: updateMessage,
deleteMessage: deleteMessage
};
return api;
function createMessage(message) {
return $http.post("/projectapi/message", message);
}
function findMessageById(messageId) {
return $http.get("/projectapi/message/id/" + messageId);
}
function findAllMessagesForUsers(userId, friendId) {
return $http.get("/projectapi/message/auth/" + userId + "/reci/" + friendId);
}
function findMessageByAuthor(authorId) {
return $http.get("/projectapi/message/author/" + authorId);
}
function updateMessage(messageId, message) {
return $http.put("/projectapi/message/" + messageId, message);
}
function deleteMessage(messageId) {
return $http.delete("/projectapi/message/" + messageId);
}
}
})();<file_sep>(function() {
angular.module("SearchScape", ["ngRoute"]);
})();<file_sep>(function() {
angular
.module("WebAppMaker")
.factory("WidgetService", WidgetService);
function WidgetService($http) {
var api = {
createWidget: createWidget,
findWidgetsByPageId: findWidgetsByPageId,
findWidgetById: findWidgetById,
updateWidget: updateWidget,
deleteWidget: deleteWidget,
sorted: sorted
};
return api;
/**
* Add a new widget to the array
*
* @param pageId The page ID of the new widget
* @param widget The widget object to be tweaked and added
*/
function createWidget(pageId, widget) {
widget._page = pageId;
var url = "/api/page/" + pageId + "/widget";
return $http.post(url, widget);
}
/**
* Find all widgets attributed to the given page ID
*
* @param pageId The page ID in question
* @returns {Array} The array of widgets attributed to that page
*/
function findWidgetsByPageId(pageId) {
var url = "/api/page/" + pageId + "/widget";
return $http.get(url);
}
/**
* Find a widget by its ID
*
* @param widgetId The ID to search for
* @returns {*} The sought after widget or null if it does not exist
*/
function findWidgetById(widgetId) {
var url = "/api/widget/" + widgetId;
return $http.get(url);
}
/**
* Update a widget based on its id
*
* @param widgetId The id of the widget to be updated
* @param widget The data to update the widget to
* @returns {boolean} Whether the update was successful
*/
function updateWidget(widgetId, widget) {
var url = "/api/widget/" + widgetId;
return $http.put(url, widget);
}
/**
* Delete a widget based on its id
*
* @param widgetId The id of the widget to be deleted
* @returns {boolean} Whether the deletion was successful
*/
function deleteWidget(widgetId) {
var url = "/api/widget/" + widgetId;
return $http.delete(url);
}
function sorted(startIndex, endIndex, pageId) {
var url = "/api/widget?start=" + startIndex + "&end=" + endIndex + "&pid=" + pageId;
return $http.put(url);
}
}
})();<file_sep>module.exports = function() {
var mongoose = require("mongoose");
var MessageSchema = require("./message.schema.server")();
var Message = mongoose.model("Message", MessageSchema);
var api = {
createMessage: createMessage,
findMessageById: findMessageById,
findAllMessagesForUsers: findAllMessagesForUsers,
updateMessage: updateMessage,
deleteMessage: deleteMessage
};
return api;
function createMessage(message) {
return Message.create(message);
}
function findMessageById(messageId) {
return Message.findById(messageId);
}
function findAllMessagesForUsers(userOne, userTwo) {
return Message.find({$or: [{author: userOne, recipient: userTwo}, {author: userTwo, recipient: userOne}]});
}
function updateMessage(messageId, message) {
return Message.update(
{_id: messageId},
{
text: message.text
}
);
}
function deleteMessage(messageId) {
return Message.remove({_id: messageId});
}
}; | cecbad5d4a15368f6b48b6bea12b5b85a85820b2 | [
"JavaScript"
]
| 21 | JavaScript | dackJavies/DAVIS-JACK-web-dev | ef163a8f2e1572e834cb40cde7f80d548fde8344 | d6f8c93abadaad0da0e303e93c6aeb51057e7cdc |
refs/heads/master | <file_sep>var missingDataGraphParams = {
title: "Instant Article Views",
animate_on_load: true,
missing_is_zero: true,
description: "Instant Articles for the requested page views",
chart_type: 'missing-data',
missing_text: 'Query for insights',
target: '#chart',
full_width: true,
height: 300,
x_label: 'Dates',
y_label: 'Visitors',
show_tooltips: true,
right: 50,
legend: ['All traffic', 'Android', 'IOS'],
};
var dataGraphParams = {
title: "Instant Article Views",
animate_on_load: true,
missing_is_zero: true,
description: "Instant Articles for the requested page views",
area: false,
full_width: true,
height: 300,
target: '#chart',
x_accessor: 'time',
y_accessor: 'value',
x_label: 'Dates',
y_label: 'Visitors',
show_tooltips: true,
right: 50,
legend: ['All traffic', 'Android', 'IOS'],
};
$(document).ready(function(){
MG.data_graphic(missingDataGraphParams);
});
function renderGraph(data){
for(var i = 0; i < data.length; i++) {
MG.convert.date(data[i], 'time', "%Y-%m-%d");
}
dataGraphParams["data"] = data;
MG.data_graphic(dataGraphParams);
}
function populateDataTable(table, data){
var table = $(table).DataTable({
retrieve: true,
dom: 'rBtip',
columns: [
{data: 'time', title: "Date", type: "date"},
{data: 'value', title: "Visitors"},
{data: 'android', title: "Android"},
{data: 'ios', title: "IOS"},
],
paging: false,
buttons: [ {extend: 'csv', text: 'Export to CSV'} ]
});
table.clear().rows.add(data).draw();
}
function formatDailyData(data){
_.each(data, function(group){
_.each(group, function(dayData){
dayData.time = moment(dayData.time).format("YYYY-MM-DD");
dayData.value = parseInt(dayData.value);
});
});
}
function getVisitData(params, params2){
var publisherID = document.getElementById('pubID').value;
FB.api(publisherID, 'get', params, function(response) {
FB.api(publisherID, 'get', params2, function(response2) {
if (!!response.instant_articles_insights) {
var byPlatform= _.groupBy(response2.instant_articles_insights.data,
function(currentDayData){
return currentDayData.breakdowns.platform;
});
var totalDailyVisitors = response.instant_articles_insights.data;
var allData = [];
if(!_.isEmpty(totalDailyVisitors)){
allData.push(totalDailyVisitors);
}
if(!_.isEmpty(byPlatform["ANDROID"])){
allData.push(byPlatform["ANDROID"]);
}
if(!_.isEmpty(byPlatform["IOS"])){
allData.push(byPlatform["IOS"]);
}
var mergedData = mergeData(allData[0], allData[1], allData[2]);
formatDailyData(allData)
renderGraph(allData);
populateDataTable("#table", mergedData);
} else {
missingDataGraphParams["missing_text"] = "Insights is unavailable for the window requested";
MG.data_graphic(missingDataGraphParams);
}
});
});
}
function getStats() {
var startOfRange = document.getElementById('rangeStart').value;
var endOfRange = document.getElementById('rangeEnd').value;
if(_.isEmpty(startOfRange)){
startOfRange = "90 days ago";
}
if(_.isEmpty(endOfRange)){
endOfRange = "now";
}
var allViewsParams = {
fields:
'instant_articles_insights.metric(all_views).period(day).since('+startOfRange+').until('+endOfRange+')'
};
var allViewsByPlatformParams = {
fields:
'instant_articles_insights.metric(all_views).breakdown(platform).period(day).since('+startOfRange+').until('+endOfRange+')'
};
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
getVisitData(allViewsParams, allViewsByPlatformParams);
} else {
FB.login();
}
});
}
function mergeData(totalVisitorData,
androidVisitorData,
iosVisitorData){
_.each(totalVisitorData, function(current){
var androidMatch = _.find(androidVisitorData, function(x){
return moment(x.time).isSame(current.time);
});
var iosMatch = _.find(iosVisitorData, function(y){
return moment(y.time).isSame(current.time);
});
if(androidMatch){
current['android'] = androidMatch['value'];
}else{
current['android'] = 0;
}
if(iosMatch){
current['ios'] = iosMatch['value'];
}else{
current['ios'] = 0;
}
});
return totalVisitorData;
}
| adb2b347456a10662ff56b91b27ccb88a35bd76e | [
"JavaScript"
]
| 1 | JavaScript | demoive/akeem.github.io | 6151c06988f035000b09241256091b1b48b7cd10 | 68b916b5d5c52f37c8ae3e08db23a53b2c11f32e |
refs/heads/main | <file_sep>package com.revature.util;
import com.revature.models.ReimbursementType;
import javax.persistence.AttributeConverter;
/**
* helper method so that the Type can be converted from an integer into an ENUM and vise versa
*/
public class TypeHelper implements AttributeConverter<ReimbursementType,Integer> {
/**
* converts from an ENUM to an Integer
* @param reimbursementType the ENUM passed in that we need to use but have to convert to Integer first
* @return the Integer representation of the Type
*/
@Override
public Integer convertToDatabaseColumn(ReimbursementType reimbursementType) {
if (reimbursementType == null) {
return null;
}
switch (reimbursementType) {
case LODGING:
return 1;
case TRAVEL:
return 2;
case FOOD:
return 3;
case OTHER:
return 4;
default:
throw new IllegalArgumentException(reimbursementType + " invalid type");
}
}
/**
* converts the Integer passed in back into the ENUM representation of it
* @param integer the integer representation of the ENUM
* @return the ENUM type of the integer passed in
*/
@Override
public ReimbursementType convertToEntityAttribute(Integer integer) {
if (integer == null) {
return null;
}
switch (integer) {
case 1:
return ReimbursementType.LODGING;
case 2:
return ReimbursementType.TRAVEL;
case 3:
return ReimbursementType.FOOD;
case 4:
return ReimbursementType.OTHER;
default:
throw new IllegalArgumentException(integer + "invalid Integer");
}
}
}
<file_sep>package com.revature.servlets;
import com.revature.hibernate.users.UserRepository;
import com.revature.hibernate.users.UserService;
import com.revature.models.Role;
import com.revature.util.UserSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(
name="loginServlet",
description= "Login Screen",
urlPatterns = {"/loginServlet"}
)
/**
* the login only has a doPost because after the user is logged in other servlets can be used to do specific things
*/
public class loginServlet extends HttpServlet {
/**
*
* @param request gets the information from the user
* @param response can give something back to the user for example a status code
* @throws IOException error if something goes wrong with writting or getting information
* @throws ServletException error if something goes wrong with the servlet
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
PrintWriter pt = response.getWriter();
UserService userService;
String user = request.getParameter("username");
String pass = request.getParameter("password");
int role;
userService = new UserService();
UserRepository userRepository = new UserRepository();
role = userService.authenticateRole(user,pass);
HttpSession session = UserSession.getUserSession().createSession(request,userService.authenticate(user,pass));
if(role == Role.ADMIN.ordinal()+1){
pt.println("Session User: "+ session.getAttribute("fullname"));
// response.sendRedirect("/ERS1.5/adminServlet");
}
else if(role == Role.FINANCE_MANAGER.ordinal()+1){
pt.println("Session User: "+ session.getAttribute("fullname"));
pt.println("Finance Manager");
}
else if(role == Role.EMPLOYEE.ordinal()+1){
pt.println("Session User: "+ session.getAttribute("fullname"));
pt.println("Employee");
}
else{
pt.println("Not a valid User");
response.setStatus(401);
}
pt.println("Login Screen");
}
}<file_sep>package com.revature.util;
import com.revature.models.ReimbursementStatus;
import javax.persistence.AttributeConverter;
/**
* This class help by converting an ENUM, it can convert to an Integer, and also take in an integer
* to convert it back into the ENUM representation
*/
public class StatusHelper implements AttributeConverter<ReimbursementStatus,Integer> {
/**
* convert the status of the ReimbursmentStatus passed in to an Integer
* @param reimbursementStatus the column of the Reimbursment table, it is an enum so we need to convert to Integer
* @return returns Integer object
*/
@Override
public Integer convertToDatabaseColumn(ReimbursementStatus reimbursementStatus) {
if( reimbursementStatus == null){
return null;
}
switch (reimbursementStatus){
case PENDING:
return 1;
case APPROVED:
return 2;
case DENIED:
return 3;
case CLOSED:
return 4;
default:
throw new IllegalArgumentException(reimbursementStatus + " invalid!");
}
}
/**
* converts the integer passed in into the ENUM representation
* @param integer the integer representation of the status
* @return returns the ENUM
*/
@Override
public ReimbursementStatus convertToEntityAttribute(Integer integer) {
if (integer == null) {
return null;
}
switch (integer) {
case 1:
return ReimbursementStatus.PENDING;
case 2:
return ReimbursementStatus.APPROVED;
case 3:
return ReimbursementStatus.DENIED;
case 4:
return ReimbursementStatus.CLOSED;
default:
throw new IllegalArgumentException(integer + " not supported");
}
}
}
<file_sep>$(document).ready(function(){
$("#loginform").click(function(){
$("#body").load("resources/loginform.html");
});
$("#registerform").click(function(){
$("#body").load("resources/registerform.html");
});
$("#empform").click(function(){
$("#body").load("resources/empform.html");
});
});
<file_sep>package com.revature.hibernate.Reimbursements;
import com.revature.exceptions.InvalidRequestException;
import com.revature.models.Reimbursement;
import com.revature.models.ReimbursementStatus;
import com.revature.models.ReimbursementType;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
public class ReimbursementService {
private ReimbursementsRepository reimRepo = new ReimbursementsRepository();
/**
* Manager level service - adds a new reimbursement to the database
* @param reimbursement the new reimbursement
*/
public void addReimbursement(Reimbursement reimbursement){
if (reimbursement==null){ throw new InvalidRequestException();}
reimRepo.addReimbursement(reimbursement);
}
/**
* Manager level service - queries all reimbursements in the database
* @return a list containing all reimbursements
*/
public List viewAllReimbursement(){
return reimRepo.viewAllReimbursement();
}
/**
* Employee level service - View all reimbursements associated with an employee
* @param Id the id of the employee to be queried
* @return a list of reimbursements
*/
public List viewAllReimbursementEmployee(Integer Id){
if (Id <= 0) {throw new InvalidRequestException();}
return reimRepo.viewAllReimbursementEmployee(Id);
}
/**
* Employee level service - view one reimbursement associated with an employee
* @param id the id of the employee
* @param reimId the id of the reimbursement
* @return a list of one =)
*/
public List<Reimbursement> viewOneReimbursementEmployee(Integer id, Integer reimId){
if (id <= 0 || reimId <= 0) {throw new InvalidRequestException();}
return reimRepo.viewOneReimbursementEmployee( id, reimId);
}
/**
* Manager level service - view all reimbursements based on its status
* @param status the status of reimbursement to be queried: Pending, Denied, Closed or Approved
* @return a list of all reimbursements of a single reimbursement status
*/
public List viewAllReimbursementByStatus(ReimbursementStatus status){
if(!isReimbursementStatusValid(status)){throw new InvalidRequestException();}
return reimRepo.viewAllReimbursementbyStatus(status);
}
/**
* manager level service - view all reimbursements based on its type
* @param type the type of reimbursement to be queried: Food, Lodging, Travel, or Other
* @return a list of all reimbursements of a single reimbursement type
*/
public List viewAllReimbursementByType(ReimbursementType type){
if(!isReimbursementTypeValid(type)){throw new InvalidRequestException();}
return reimRepo.viewAllReimbursementbyType(type);
}
//optional?
public Optional<Reimbursement> getReimbursementById(Integer id){
if (id <= 0 || id > 4) {throw new InvalidRequestException();}
return reimRepo.getReimbursementById(id);
}
/**
* Manager level service - Update the resolver id of a reimbursement
* @param reimbursementId the id of the reimbursement to be updated
* @param resolverId the id to enter into the resolver id field
* @return
*/
public boolean updateResolverByReimbursementId(Integer reimbursementId, Integer resolverId){
if (resolverId <= 0 || reimbursementId <= 0) {throw new InvalidRequestException();}
return reimRepo.updateResolverByReimbursementId(reimbursementId,resolverId);
}
/**
* Manager level service -
* @param reimbursementId id of the reimbursement to be updated
* @param date the new date
* @param status the new status
* @return true if successful, false otherwise
*/
public boolean updateStatusTime(Integer reimbursementId, Timestamp date, ReimbursementStatus status){
if(!isReimbursementStatusValid(status)){throw new InvalidRequestException();}
return reimRepo.updateStatusTime(reimbursementId,date,status);
}
/**
* Employee level service - updates all aspects of a reimbursement based on the id
* @param reimbursementId id of the reimbursement to be updated
* @param amount the new amount
* @param description the new description
* @param type the new type
* @return true if successful, false otherwise
*/
public boolean updatePendingRowAll(Integer reimbursementId, Double amount, String description, ReimbursementType type){
if(!isReimbursementTypeValid(type)){throw new InvalidRequestException();}
return reimRepo.updatePendingRowAll(reimbursementId, amount,description, type);
}
/**
* Employee level service - updates the type of a reimbursement based on the id
* @param rId id of the reimbursement to be updated
* @param type the new type
* @return true if successful, false otherwise
*/
public boolean updatePendingRowType(Integer rId, ReimbursementType type){
if(!isReimbursementTypeValid(type)){throw new InvalidRequestException();}
return reimRepo.updatePendingRowType(rId,type);
}
/**
* Employee level service - updates the amount of a reimbursement based on the id
* @param rId id of the reimbursement to be updated
* @param amount the new amount
* @return true if successful, false otherwise
*/
public boolean updatePendingRowAmount(Integer rId, Double amount){
if (rId <= 0) {throw new InvalidRequestException();}
return reimRepo.updatePendingRowAmount(rId,amount);
}
/**
* Employee level service - updates the description of a reimbursement of a 'Pending' status reimbursement
* @param rId id of the reimbursement to be updated
* @param d the new description
* @return true if successful, false otherwise
*/
public boolean updatePendingRowDescription(Integer rId, String d){
if (rId <= 0 || d == null) {throw new InvalidRequestException();}
return reimRepo.updatePendingRowDescription(rId,d);
}
/**
* Validates that a given reimbursement status of a correct status type
* @param r the status to be tested
* @return true if valid, false otherwise
*/
public Boolean isReimbursementStatusValid(ReimbursementStatus r) {
if (r == null) return false;
if (r != ReimbursementStatus.PENDING &&
r != ReimbursementStatus.APPROVED &&
r != ReimbursementStatus.DENIED &&
r != ReimbursementStatus.CLOSED) return false;
return true;
// return false;
}
/**
* Validates that a given reimbursement type of a correct type
* @param t the type to be tested
* @return true if valid, false otherwise
*/
public Boolean isReimbursementTypeValid(ReimbursementType t) {
if (t == null) return false;
if (t != ReimbursementType.OTHER &&
t != ReimbursementType.FOOD &&
t != ReimbursementType.TRAVEL &&
t != ReimbursementType.LODGING) return false;
return true;
// return false;
}
}
| 45f750d05447d3f459c0432d3c4823f5cf83dcd9 | [
"JavaScript",
"Java"
]
| 5 | Java | ZGCalvin/ers_p1-5 | 828fdb8da11ff0250bb285a14a6b7ad784369913 | c336b5fd4456f5f5daceaa98f9288cdf673f10f3 |
refs/heads/master | <repo_name>mertala/Textfield-SwiftUI<file_sep>/Textfield-SwiftUI/ContentView.swift
//
// ContentView.swift
// Textfield-SwiftUI
//
// Created by <NAME> on 9.10.2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var email: String = ""
@State var sifre: String = ""
var body: some View
{
VStack {
TextField("Email gir", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.frame(width: 300, height: 60)
.shadow(radius: 5.0)
.keyboardType(UIKeyboardType.emailAddress)
SecureField("Şifre gir", text: $sifre)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 300, height: 60)
.padding(.bottom, 10)
.shadow(radius: 5.0)
.keyboardType(UIKeyboardType.numberPad)
Button(action: {}) {
HStack {
Text("Giriş")}
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.foregroundColor(.white)
.background(Color.green)
.frame(width: 300, height: 60)
.cornerRadius(30.0)
.shadow(radius: 5.0)
}
}
}
}
| 8ce087c6db577e127ef39691547fdf5f012d938a | [
"Swift"
]
| 1 | Swift | mertala/Textfield-SwiftUI | 49840cb75cac3e816cd2a678c5651f4d9f832e89 | e82572be185e25a4b3a8e309c0aa77221f0a4426 |
refs/heads/master | <file_sep>import scrapy
import re
class HockeysFuturePositionsSpider(scrapy.Spider):
name = 'hockeysfuturepositions'
allowed_domains = ['hfboards.hockeysfuture.com']
start_urls = ['http://hfboards.hockeysfuture.com/showpost.php?p=118067873&postcount=1']
def parse(self, response):
for cell in response.css('table.stg_table td::text'):
m = re.match("(?P<player>[A-z' -]+) \(\d+, (?P<position>LW|C|RW|RD|LD|G)\)", cell.extract())
if m:
yield {key: value.upper() for key, value in m.groupdict().items()}
<file_sep>import scrapy
import re
base_url = 'https://hockey.fantasysports.yahoo.com'
class YahooFantasyHockeySpider(scrapy.Spider):
name = 'yahoofantasyhockey'
allowed_domains = ['hockey.fantasysports.yahoo.com']
start_urls = ['https://hockey.fantasysports.yahoo.com/hockey/draftanalysis?pos=ALL']
def parse(self, response):
for row in response.css('table#draftanalysistable tr')[1:]:
yield dict(zip(
('name', 'positions', 'avg_pick', 'avg_round', 'pct_drafted'),
self.parse_player(row)
))
url = response.xpath('//a[contains(., "Next 50")]/@href').extract_first()
if url:
yield scrapy.Request(base_url + url, callback=self.parse)
def parse_player(self, row):
td_name, *rest = row.css('td')
name = td_name.css('a.name::text').extract_first()
pos_raw = td_name.css('span.Fz-xxs::text').extract_first()
positions = re.split('\s*-\s*', pos_raw, maxsplit=1)[-1]
dpick, dround, dpct = [td.css('::text').extract_first() for td in rest]
return (
name,
positions.replace('W', '').replace(',', ''),
dpick,
dround,
dpct.rstrip('%')
)
<file_sep>fantasyhockey
=============
Tools and data for Yahoo Fantasy Hockey.
Yahoo draft scraper
-------------------
[scrapy](https://scrapy.org/) scraper for Yahoo draft data, including player
position, average draft position, etc. Verified that this works for 2019-20.
Install requirements with [pipenv](https://docs.pipenv.org/en/latest/).
```bash
$ pipenv install
$ pipenv shell
$ scrapy runspider spiders/yahoo.py -o yahoo.csv
```
| f28e787fc9cd452ad4becd3e2b589cfb9484f803 | [
"Markdown",
"Python"
]
| 3 | Python | thesquelched/fantasyhockey | 8635265ee99a7aa4728c2cfcba755931eb1f8966 | 46318f5b033102488863d3c42c7af94876b7cf4a |
refs/heads/master | <repo_name>g-prathyusha99/1643B35_OS-17<file_sep>/README.md
# 1643B35_OS-17
This approach improves the CPU Performance in real time OS. The given problem is priority based Round robin CPU Scheduling algorithm. It has the same property of round robin and fixed priority with an advantage of reducing starvation and integrates priority-based scheduling. This code or algorithm improves all the drawbacks like varying time quantum, average waiting time, Turnaround time and number of context switches. This code implements multilevel Feedback Queue in two levels. Level 1: Fixed Priority Pre-emptive Scheduling Level 2: Round Robin Scheduling
<file_sep>/OS 17.cpp
#include<stdio.h>
#include<stdlib.h>
struct process_structure
{
int process_id, arrival_time, burst_time, priority;
int w_flag,waiting_time;
int turnaround_time;
};
int main ()
{
int a, count;
int TimeQ;
int waiting_time;
int i, j;
printf("\n Level 1 : Fixed priority preemptive Scheduling\n Level 2 : Round Robin Scheduling\n\n");
printf("Enter Total Number of Processes : ");
scanf("%d", & a);
printf("Enter Time Quantum for Round Robin in multiple of 2: ");
scanf("%d", & TimeQ);
struct process_structure p1[a];
struct process_structure p2[a];
struct process_structure processTree[a];
int flag = 1;
int Qlevel=1;
int q1 = 0, q2 = 0;
for (count = 0; count < a; count++)
{
printf("Process ID : ");
scanf("%d", & p1[q1].process_id);
printf("Arrival Time : ");
scanf("%d", & p1[q1].arrival_time);
printf("Burst Time : ");
scanf("%d", & p1[q1].burst_time);
printf("Process Priority : ");
scanf("%d", & p1[q1].priority);
p1[q1].w_flag=0;
p1[q1].waiting_time=0;
p1[q1].turnaround_time=0;
processTree[count]=p1[q1];
q1++;
}
printf("\n\n \t\t\tLEVEL 1 QUEUE IS Running\n\n");
struct process_structure temp;
for (i = 1; i < q1; i++)
for (j = 0; j < q1 - i; j++)
{
if (p1[j].arrival_time > p1[j + 1].arrival_time)
{
temp = p1[j];
p1[j] = p1[j + 1];
p1[j + 1] = temp;
}
}
for (i = 0; i < q1; i++)
{
printf("\nProcess ID:%d\t Arrival Time:%d \tPriority: %d\tBurst Time:%d", p1[i].process_id, p1[i].arrival_time, p1[i].priority, p1[i].burst_time);
}
printf("\n\n");
int total_process_L1 = q1;
i = 0;
int run;
for (run = 0;; run++)
{
if (q1 == 0)
{
break;
}
//premepts previous process
if (p1[i]. priority > p1[i + 1].priority && p1[i + 1].arrival_time == run)
{
p2[q2] = p1[i];
p1[i].priority=-1;
p2[q2].arrival_time = run;
p2[q2].w_flag=0;
p2[q2].priority = -1;
printf("\t\t\t\t\t Process %d is shifted to Queue 2\n ", p1[i].process_id);
q1--;
q2++;
i++;
}
if (p1[i].arrival_time <= run && p1[i].burst_time != 0)
{
if(p1[i].w_flag==0)
{
p1[i].waiting_time+=((run)-p1[i].arrival_time);
p1[i].w_flag=1;
}
printf("\nProcess ID:%d Priority: %d Burst Time %d time %d", p1[i].process_id, p1[i].priority, p1[i].burst_time, run);
p1[i].burst_time--;
}
else if (p1[i].burst_time == 0)
{
printf("\t\t\t\t\tProcess %d has completed\n ",Ěp1[i].process_id);
q1--;
run--;
i++;
}
}
int k=0;
for (i = 0; i < total_process_L1; i++)
{
for(k=0;k<a;k++)
{
if(p1[i].process_id==processTree[k].process_id)
{
processTree[k].waiting_time=p1[i].waiting_time;
}
}
}
printf("\n\n");
printf("\n\n LEVEL 2 is Running\n\n");
for (i = 1; i < q2; i++)
{
for (j = 0; j < q2 - i; j++)
{
if (p2[j].arrival_time > p2[j + 1].arrival_time)
{
temp = p2[j];
p2[j] = p2[j + 1];
p2[j + 1] = temp;
}
}
}
int total_process_L2 = q2;
for (i = 0; i < q2; i++)
{
printf("\nProcess ID:%d\t Arrival Time:%d \tBurst Time:%d", p2[i].process_id, p2[i].arrival_time, p2[i].burst_time);
}
printf("\n\n");
i = 0;
int resetter = 0;
for (run;; run++)
{
if (total_process_L2 == 0)
{
break; }
if(p2[i].burst_time == 0)
{
printf("\t\t\t\t\tProcess %d has Completed\n", p2[i].process_id);
i++;
run--;
total_process_L2--;
resetter = 0;
continue;
}
else if (resetter == TimeQ)
{
printf("\n\n!! Time Quantum Complete of %d seconds !!! \n", resetter);
p2[q2] = p2[i];
p2[q2].arrival_time=run;
i++;
q2++;
resetter = 0;
}
if (p2[i].arrival_time <= run && p2[i].burst_time != 0)
{
if(resetter==0&&p2[i].process_id!=p2[i-1].process_id)
{
p2[i].waiting_time+=(run-p2[i].arrival_time);
p2[i].w_flag=1;
}
printf("\nProcess ID:%d Burst Time %d Time Taken %d", p2[i].process_id, p2[i].burst_time, run);
p2[i].burst_time --;
}
else if (p2[i].burst_time == 0)
{
printf("\t\t\t\t\t Process %d has Completed\n", p2[i].process_id);
i++;
run--;
total_process_L2--;
resetter = 0;
}
resetter++;
}
for (i = 0; i < q2; i++) {
for(k=0;k<a;k++)
{
if(p2[i].process_id==processTree[k].process_id)
{
processTree[k].waiting_time=p2[i].waiting_time;
}
}
}
float avg_wait_time=0;
float avg_turn_time=0;
for (i = 0; i < a; i++)
{
processTree[i].turnaround_time=processTree[i].burst_time+processTree[i].waiting_time;
printf("\n\t\t ********** PROCESS TABLE ********** ");
printf("\n| Process ID:%d | Arrival Time:%d | Burst Time:%d | waiting Time:%d | Turn Time:%d |", processTree[i].process_id, processTree[i].arrival_time,processTree[i].burst_time, processTree[i].waiting_time,processTree[i].turnaround_time);
avg_wait_time+=processTree[i].waiting_time;
avg_turn_time+=processTree[i].turnaround_time;
}
printf("\n\n");
avg_wait_time/=a;
avg_turn_time/=a;
printf("Average Waiting Time : %.2f\n",avg_wait_time);
printf("Average TurnAround Time : %.2f\n",avg_turn_time);
}
| 2d67e53ef8ca9a4c1ef2a56b6e8938bc7de5d5c9 | [
"Markdown",
"C++"
]
| 2 | Markdown | g-prathyusha99/1643B35_OS-17 | 69b18ea8087018481437ccb770ec2f42ab1be4c1 | 84d7286f48a7f7a825aba97c657eb5c684e0f6b0 |
refs/heads/master | <file_sep>#pragma once
#include "Components/ActorComponent.h"
#include "VehicleSimData.generated.h"
USTRUCT()
struct FChassisSimData
{
GENERATED_USTRUCT_BODY()
FChassisSimData()
: LinearVelocity(FVector::ZeroVector)
, AngularVelocity(FVector::ZeroVector)
, Speed(0.f)
{
}
UPROPERTY(Transient)
FVector AngularVelocity;
UPROPERTY(Transient)
FVector LinearVelocity;
UPROPERTY(Transient)
float Speed;
};
USTRUCT()
struct FWheelSimData
{
GENERATED_USTRUCT_BODY()
FWheelSimData()
: SteerAngle(0.f)
, RotationAngle(0.f)
, SuspensionOffset(0.f)
{
}
UPROPERTY(Transient)
FVector Velocity;
UPROPERTY(Transient)
float Speed;
UPROPERTY(Transient)
float SteerAngle;
UPROPERTY(Transient)
float RotationAngle;
UPROPERTY(Transient)
float SuspensionOffset;
};
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class TIMEATTACK_API UVehicleSimData : public UActorComponent
{
GENERATED_BODY()
public:
UVehicleSimData();
virtual void BeginPlay() override;
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
private:
UPROPERTY(Transient)
FChassisSimData ChassisSimData;
UPROPERTY(Transient)
TArray<FWheelSimData> WheelSimData;
};<file_sep>Per modificare l'unità di misura del valore che si vuole visualizzare, è necessario scrivere al termine della stringa un underscore "_" seguito dall'unità di misura desiderata; per concatenare più comandi, utilizzare il punto e virgola ";".
Se non viene specificata alcuna unità di misura, o viene inserità una metrica errata, verrà automaticamente utilizzata quella di default, ossia metri per le distanze, m/s per la velocità e gradi per gli angoli.
Metriche supportate:
- Velocità: cm/s, m/s (default), km/h
- Distanze: mm, cm, m (default)
- Angoli: gradi (default), rad
Esempio di comando:
Telemetry VehicleSimData.ChassisSimData.Speed;VehicleSimData.ChassisSimData.Speed_km/h;VehicleSimData.ChassisSimData.Speed_cm/s | d4af85eb292ce6b9d7215388bbc69c604c7d784c | [
"Text",
"C++"
]
| 2 | C++ | Boriky/TimeAttackHLP | 7105a63321ccc0fc73ada5635bab70504df20149 | 6b25ae159f50962d759adfd677c6472b174ae306 |
refs/heads/master | <repo_name>NelsonJyostna/repo<file_sep>/linux-content/dieroll.sh
declare -A Dict
for (( i=1; i<=100; i++ ))
do
randomcheck=$(( $RANDOM%6+1 ))
case $randomcheck in
1 ) echo "$i:$randomcheck";;
2 ) echo "$i:$randomcheck";;
3 ) echo "$i:$randomcheck";;
4 ) echo "$i:$randomcheck";;
5 ) echo "$i:$randomcheck";;
6 ) echo "$i:$randomcheck";;
* ) echo "Nothing"
esac
done
#while [ $randomcheck -le 10 ]
#do
# Dict[$randomcheck]=$(( $randomcheck ))
#done
#echo "${dict[@]}"
| a3633b16335b0febf2009ba11cfba97d94b65ca7 | [
"Shell"
]
| 1 | Shell | NelsonJyostna/repo | f32a89b375da137498b208f9f123ea41ca029959 | 50cb8c62f0b629341862e53e7c830074bf7566d6 |
refs/heads/master | <repo_name>demo-Ashif/Agro-Web-Portal<file_sep>/getCropBankInfo.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category_id = $_POST['categoryID'];
$crop_id = $_POST['cropID'];
$criteria = $_POST['criteria'];
if ($criteria == 1)
{
$criteriaDB = 'cultivation_process';
}
elseif ($criteria == 2) {
$criteriaDB = 'irrigation_process';
}
elseif ($criteria == 3) {
$criteriaDB = 'fertilizer_process';
}
elseif ($criteria == 4) {
$criteriaDB = 'disease_manage';
}
elseif ($criteria == 5) {
$criteriaDB = 'insects_manage';
}
elseif ($criteria == 6) {
$criteriaDB = 'harvest_collection';
}
elseif ($criteria == 7) {
$criteriaDB = 'seed_manage';
}
elseif ($criteria == 8) {
$criteriaDB = 'soil_land_select';
}
elseif ($criteria == 9) {
$criteriaDB = 'interim_caring';
}
$sql1 = $con->query("SELECT $criteriaDB from crop_info_bank where category_id ='".$category_id."' and crop_id = '".$crop_id."' ");
$row1= $sql1->fetch_array();
echo $row1[$criteriaDB];
?><file_sep>/js/all-local.js
/*Login form function to position on middle and others*/
$(document).ready(function(){
//open popup
$("#admin-login").click(function(){
$("#form").fadeIn(1000);
positionPopup();
});
//close popup
$(".close").click(function(){
$("#form").fadeOut(500);
});
});
//position the popup at the center of the page
function positionPopup(){
if(!$("#form").is(':visible')){
return;
}
$("#form").css({
left: ($(window).width() - $('#form').width()) / 2,
top: ($(window).width() - $('#form').width()) / 7,
position:'absolute'
});
}
//maintain the popup at center of the page when browser resized
$(window).bind('resize',positionPopup); /*Login form function to position on middle and others*/
/* smooth scrolling function*/
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
}); /* smooth scrolling function*/
/* mainpage dropdown menu togle function */
function DropDown(el) {
this.dd = el;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
obj.dd.on('click', function(event){
$(this).toggleClass('active');
event.stopPropagation();
});
}
}
$(function() {
var dd = new DropDown( $('#dd') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-2').removeClass('active');
});
});
$(function() {
var dd = new DropDown( $('#dd2') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-2').removeClass('active');
});
}); /* mainpage dropdown menu togle function */
<file_sep>/show_tools_info.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$query = $con->query("select * from agri_tools_info");
$row= $query->fetch_array();
if ($query)
{
echo $row['title'];
echo "<br>";
echo $row['post'];
echo "<br>";
echo "<img src=".$row['photo_dir'].">";
}else
{
echo mysqli_error($con);
}
?>
<file_sep>/district_info_html.php
<div id="canvas">
<div id="papermap"> </div> <!--BD map is displayed here -->
<!-- district text info -->
<!-- Panchogar Thakurgaon Nilphamari Dinajpur Rangpur Kurigram Lalmonirhat Gaibandha Joypurhat Naogaon Bogra Jamalpur Sherpur Nawabganj Rajshahi Natore Sirajganj Tangail Mymensingh Netrokona Sunamganj Sylhet MBazar Hobiganj Kishoreganj Gazipur Kushtia Pabna Manikganj Dhaka NGanj Narsingdi BBaria Comilla Chadpur Shariatpur Madaripur Munshiganj Faridpur Gopalganj Magura Jhenaidah Chuadanga Meherpur Jessore Narail Satkhira Khulna Bagerhat Pirojpur Jhalokathi Barguna Patuakhali Barisal Vola Laxmipur Noakhali Feni Chittagong Khagrachari Rangamati Bandorban CoxBazar Rajbari -->
<div id="Panchogar">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $Panchogar['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $Panchogar['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $Panchogar['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $Panchogar['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $Panchogar['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $Panchogar['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $Panchogar['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $Panchogar['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $Panchogar['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $Panchogar['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $Panchogar['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $Panchogar['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $Panchogar['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $Panchogar['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $Panchogar['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $Panchogar['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $Panchogar['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $Panchogar['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Thakurgaon">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $thakurgaon['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $thakurgaon['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $thakurgaon['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $thakurgaon['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $thakurgaon['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $thakurgaon['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $thakurgaon['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $thakurgaon['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $thakurgaon['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $thakurgaon['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $thakurgaon['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $thakurgaon['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $thakurgaon['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $thakurgaon['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $thakurgaon['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $thakurgaon['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $thakurgaon['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $thakurgaon['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Nilphamari">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $nilphamari['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $nilphamari['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $nilphamari['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $nilphamari['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $nilphamari['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $nilphamari['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $nilphamari['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $nilphamari['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $nilphamari['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $nilphamari['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $nilphamari['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $nilphamari['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $nilphamari['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $nilphamari['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $nilphamari['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $nilphamari['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $nilphamari['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $nilphamari['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Dinajpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $dinajpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $dinajpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $dinajpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $dinajpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $dinajpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $dinajpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $dinajpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $dinajpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $dinajpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $dinajpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $dinajpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $dinajpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $dinajpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $dinajpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $dinajpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $dinajpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $dinajpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $dinajpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Rangpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $rangpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $rangpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $rangpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rangpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rangpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rangpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rangpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rangpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rangpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $rangpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $rangpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $rangpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $rangpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $rangpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $rangpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $rangpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $rangpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $rangpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Kurigram">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $kurigram['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $kurigram['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $kurigram['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $kurigram['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $kurigram['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $kurigram['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $kurigram['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $kurigram['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $kurigram['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $kurigram['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $kurigram['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $kurigram['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $kurigram['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $kurigram['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $kurigram['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $kurigram['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $kurigram['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $kurigram['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Lalmonirhat">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $lalmonirhat['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $lalmonirhat['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $lalmonirhat['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $lalmonirhat['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $lalmonirhat['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $lalmonirhat['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $lalmonirhat['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $lalmonirhat['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $lalmonirhat['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $lalmonirhat['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $lalmonirhat['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $lalmonirhat['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $lalmonirhat['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $lalmonirhat['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $lalmonirhat['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $lalmonirhat['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $lalmonirhat['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $lalmonirhat['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Gaibandha">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $gaibandha['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $gaibandha['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $gaibandha['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $gaibandha['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $gaibandha['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $gaibandha['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $gaibandha['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $gaibandha['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $gaibandha['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $gaibandha['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $gaibandha['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $gaibandha['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $gaibandha['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $gaibandha['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $gaibandha['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $gaibandha['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $gaibandha['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $gaibandha['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Joypurhat">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $joypurhat['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $joypurhat['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $joypurhat['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $joypurhat['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $joypurhat['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $joypurhat['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $joypurhat['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $joypurhat['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $joypurhat['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $joypurhat['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $joypurhat['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $joypurhat['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $joypurhat['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $joypurhat['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $joypurhat['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $joypurhat['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $joypurhat['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $joypurhat['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Naogaon">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $naogaon['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $naogaon['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $naogaon['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $naogaon['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $naogaon['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $naogaon['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $naogaon['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $naogaon['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $naogaon['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $naogaon['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $naogaon['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $naogaon['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $naogaon['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $naogaon['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $naogaon['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $naogaon['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $naogaon['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $naogaon['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Bogra">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $bogra['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $bogra['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $bogra['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bogra['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bogra['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bogra['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bogra['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bogra['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bogra['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $bogra['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $bogra['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $bogra['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $bogra['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $bogra['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $bogra['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $bogra['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $bogra['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $bogra['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Jamalpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $jamalpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $jamalpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $jamalpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jamalpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jamalpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jamalpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jamalpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jamalpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jamalpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $jamalpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $jamalpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $jamalpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $jamalpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $jamalpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $jamalpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $jamalpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $jamalpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $jamalpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Sherpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $sherpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $sherpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $sherpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sherpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sherpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sherpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sherpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sherpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sherpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $sherpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $sherpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $sherpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $sherpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $sherpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $sherpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $sherpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $sherpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $sherpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Nawabganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $nawabganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $nawabganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $nawabganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $nawabganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $nawabganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $nawabganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $nawabganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $nawabganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $nawabganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $nawabganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $nawabganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $nawabganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $nawabganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $nawabganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $nawabganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $nawabganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $nawabganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $nawabganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Rajshahi">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $rajshahi['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $rajshahi['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $rajshahi['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rajshahi['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rajshahi['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rajshahi['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rajshahi['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rajshahi['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rajshahi['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $rajshahi['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $rajshahi['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $rajshahi['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $rajshahi['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $rajshahi['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $rajshahi['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $rajshahi['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $rajshahi['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $rajshahi['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Natore">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $natore['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $natore['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $natore['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $natore['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $natore['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $natore['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $natore['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $natore['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $natore['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $natore['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $natore['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $natore['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $natore['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $natore['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $natore['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $natore['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $natore['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $natore['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Sirajganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $sirajganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $sirajganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $sirajganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sirajganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sirajganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sirajganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sirajganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sirajganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sirajganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $sirajganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $sirajganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $sirajganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $sirajganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $sirajganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $sirajganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $sirajganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $sirajganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $sirajganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Tangail">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $tangail['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $tangail['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $tangail['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $tangail['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $tangail['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $tangail['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $tangail['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $tangail['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $tangail['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $tangail['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $tangail['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $tangail['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $tangail['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $tangail['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $tangail['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $tangail['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $tangail['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $tangail['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Mymensingh">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $mymensingh['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $mymensingh['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $mymensingh['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $mymensingh['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $mymensingh['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $mymensingh['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $mymensingh['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $mymensingh['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $mymensingh['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $mymensingh['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $mymensingh['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $mymensingh['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $mymensingh['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $mymensingh['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $mymensingh['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $mymensingh['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $mymensingh['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $mymensingh['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Netrokona">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $netrokona['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $netrokona['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $netrokona['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $netrokona['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $netrokona['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $netrokona['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $netrokona['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $netrokona['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $netrokona['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $netrokona['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $netrokona['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $netrokona['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $netrokona['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $netrokona['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $netrokona['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $netrokona['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $netrokona['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $netrokona['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Sunamganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $sunamganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $sunamganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $sunamganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sunamganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sunamganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sunamganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sunamganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sunamganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sunamganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $sunamganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $sunamganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $sunamganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $sunamganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $sunamganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $sunamganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $sunamganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $sunamganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $sunamganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Sylhet">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $sylhet['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $sylhet['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $sylhet['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sylhet['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sylhet['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sylhet['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $sylhet['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $sylhet['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $sylhet['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $sylhet['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $sylhet['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $sylhet['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $sylhet['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $sylhet['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $sylhet['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $sylhet['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $sylhet['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $sylhet['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="MBazar">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $mbazar['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $mbazar['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $mbazar['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $mbazar['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $mbazar['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $mbazar['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $mbazar['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $mbazar['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $mbazar['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $mbazar['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $mbazar['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $mbazar['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $mbazar['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $mbazar['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $mbazar['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $mbazar['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $mbazar['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $mbazar['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Hobiganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $hobiganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $hobiganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $hobiganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $hobiganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $hobiganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $hobiganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $hobiganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $hobiganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $hobiganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $hobiganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $hobiganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $hobiganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $hobiganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $hobiganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $hobiganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $hobiganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $hobiganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $hobiganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Kishoreganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $kishoreganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $kishoreganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $kishoreganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $kishoreganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $kishoreganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $kishoreganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $kishoreganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $kishoreganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $kishoreganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $kishoreganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $kishoreganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $kishoreganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $kishoreganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $kishoreganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $kishoreganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $kishoreganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $kishoreganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $kishoreganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Gazipur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $gajipur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $gajipur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $gajipur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $gajipur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $gajipur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $gajipur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $gajipur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $gajipur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $gajipur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $gajipur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $gajipur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $gajipur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $gajipur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $gajipur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $gajipur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $gajipur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $gajipur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $gajipur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Kushtia">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $kushtia['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $kushtia['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $kushtia['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $kushtia['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $kushtia['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $kushtia['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $kushtia['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $kushtia['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $kushtia['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $kushtia['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $kushtia['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $kushtia['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $kushtia['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $kushtia['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $kushtia['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $kushtia['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $kushtia['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $kushtia['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Pabna">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $pabna['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $pabna['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $pabna['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $pabna['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $pabna['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $pabna['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $pabna['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $pabna['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $pabna['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $pabna['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $pabna['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $pabna['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $pabna['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $pabna['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $pabna['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $pabna['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $pabna['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $pabna['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Manikganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $manikganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $manikganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $manikganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $manikganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $manikganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $manikganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $manikganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $manikganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $manikganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $manikganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $manikganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $manikganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $manikganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $manikganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $manikganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $manikganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $manikganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $manikganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="NGanj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $nganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $nganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $nganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $nganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $nganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $nganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $nganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $nganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $nganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $nganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $nganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $nganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $nganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $nganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $nganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $nganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $nganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $nganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<!-- *************** Real Dhaka ***************** -->
<div id="Dhaka">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $dhaka['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $dhaka['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $dhaka['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $dhaka['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $dhaka['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $dhaka['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $dhaka['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $dhaka['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $dhaka['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $dhaka['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $dhaka['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $dhaka['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $dhaka['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $dhaka['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $dhaka['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $dhaka['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $dhaka['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $dhaka['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Narsingdi">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $narsingdi['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $narsingdi['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $narsingdi['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $narsingdi['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $narsingdi['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $narsingdi['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $narsingdi['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $narsingdi['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $narsingdi['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $narsingdi['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $narsingdi['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $narsingdi['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $narsingdi['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $narsingdi['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $narsingdi['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $narsingdi['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $narsingdi['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $narsingdi['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="BBaria">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $bbaria['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $bbaria['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $bbaria['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bbaria['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bbaria['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bbaria['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bbaria['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bbaria['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bbaria['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $bbaria['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $bbaria['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $bbaria['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $bbaria['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $bbaria['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $bbaria['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $bbaria['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $bbaria['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $bbaria['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Comilla">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $comilla['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $comilla['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $comilla['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $comilla['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $comilla['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $comilla['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $comilla['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $comilla['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $comilla['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $comilla['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $comilla['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $comilla['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $comilla['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $comilla['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $comilla['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $comilla['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $comilla['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $comilla['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Chadpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $chadpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $chadpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $chadpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $chadpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $chadpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $chadpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $chadpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $chadpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $chadpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $chadpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $chadpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $chadpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $chadpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $chadpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $chadpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $chadpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $chadpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $chadpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Shariatpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $shariatpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $shariatpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $shariatpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $shariatpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $shariatpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $shariatpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $shariatpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $shariatpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $shariatpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $shariatpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $shariatpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $shariatpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $shariatpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $shariatpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $shariatpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $shariatpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $shariatpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $shariatpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Madaripur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $madaripur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $madaripur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $madaripur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $madaripur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $madaripur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $madaripur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $madaripur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $madaripur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $madaripur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $madaripur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $madaripur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $madaripur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $madaripur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $madaripur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $madaripur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $madaripur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $madaripur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $madaripur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Munshiganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $munsiganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $munsiganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $munsiganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $munsiganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $munsiganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $munsiganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $munsiganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $munsiganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $munsiganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $munsiganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $munsiganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $munsiganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $munsiganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $munsiganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $munsiganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $munsiganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $munsiganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $munsiganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Faridpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $faridpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $faridpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $faridpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $faridpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $faridpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $faridpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $faridpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $faridpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $faridpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $faridpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $faridpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $faridpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $faridpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $faridpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $faridpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $faridpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $faridpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $faridpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Rajbari">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $rajbari['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $rajbari['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $rajbari['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rajbari['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rajbari['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rajbari['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rajbari['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rajbari['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rajbari['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $rajbari['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $rajbari['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $rajbari['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $rajbari['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $rajbari['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $rajbari['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $rajbari['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $rajbari['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $rajbari['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Gopalganj">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $gopalganj['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $gopalganj['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $gopalganj['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $gopalganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $gopalganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $gopalganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $gopalganj['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $gopalganj['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $gopalganj['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $gopalganj['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $gopalganj['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $gopalganj['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $gopalganj['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $gopalganj['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $gopalganj['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $gopalganj['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $gopalganj['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $gopalganj['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Magura">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $magura['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $magura['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $magura['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $magura['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $magura['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $magura['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $magura['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $magura['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $magura['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $magura['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $magura['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $magura['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $magura['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $magura['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $magura['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $magura['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $magura['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $magura['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Jhenaidah">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $jhenaidah['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $jhenaidah['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $jhenaidah['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jhenaidah['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jhenaidah['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jhenaidah['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jhenaidah['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jhenaidah['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jhenaidah['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $jhenaidah['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $jhenaidah['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $jhenaidah['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $jhenaidah['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $jhenaidah['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $jhenaidah['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $jhenaidah['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $jhenaidah['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $jhenaidah['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Chuadanga">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $chuadanga['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $chuadanga['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $chuadanga['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $chuadanga['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $chuadanga['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $chuadanga['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $chuadanga['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $chuadanga['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $chuadanga['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $chuadanga['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $chuadanga['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $chuadanga['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $chuadanga['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $chuadanga['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $chuadanga['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $chuadanga['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $chuadanga['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $chuadanga['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Meherpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $meherpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $meherpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $meherpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $meherpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $meherpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $meherpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $meherpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $meherpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $meherpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $meherpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $meherpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $meherpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $meherpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $meherpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $meherpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $meherpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $meherpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $meherpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Jessore">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $jessore['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $jessore['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $jessore['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jessore['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jessore['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jessore['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jessore['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jessore['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jessore['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $jessore['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $jessore['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $jessore['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $jessore['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $jessore['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $jessore['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $jessore['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $jessore['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $jessore['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Narail">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $narail['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $narail['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $narail['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $narail['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $narail['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $narail['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $narail['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $narail['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $narail['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $narail['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $narail['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $narail['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $narail['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $narail['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $narail['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $narail['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $narail['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $narail['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Satkhira">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $satkhira['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $satkhira['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $satkhira['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $satkhira['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $satkhira['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $satkhira['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $satkhira['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $satkhira['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $satkhira['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $satkhira['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $satkhira['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $satkhira['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $satkhira['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $satkhira['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $satkhira['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $satkhira['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $satkhira['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $satkhira['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Khulna">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $khulna['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $khulna['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $khulna['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $khulna['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $khulna['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $khulna['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $khulna['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $khulna['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $khulna['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $khulna['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $khulna['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $khulna['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $khulna['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $khulna['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $khulna['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $khulna['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $khulna['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $khulna['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Bagerhat">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $bagerhat['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $bagerhat['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $bagerhat['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bagerhat['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bagerhat['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bagerhat['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bagerhat['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bagerhat['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bagerhat['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $bagerhat['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $bagerhat['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $bagerhat['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $bagerhat['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $bagerhat['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $bagerhat['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $bagerhat['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $bagerhat['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $bagerhat['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Pirojpur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $pirojpur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $pirojpur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $pirojpur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $pirojpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $pirojpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $pirojpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $pirojpur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $pirojpur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $pirojpur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $pirojpur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $pirojpur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $pirojpur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $pirojpur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $pirojpur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $pirojpur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $pirojpur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $pirojpur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $pirojpur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Jhalokathi">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $jhalokathi['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $jhalokathi['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $jhalokathi['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jhalokathi['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jhalokathi['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jhalokathi['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $jhalokathi['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $jhalokathi['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $jhalokathi['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $jhalokathi['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $jhalokathi['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $jhalokathi['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $jhalokathi['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $jhalokathi['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $jhalokathi['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $jhalokathi['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $jhalokathi['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $jhalokathi['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Barguna">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $barguna['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $barguna['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $barguna['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $barguna['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $barguna['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $barguna['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $barguna['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $barguna['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $barguna['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $barguna['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $barguna['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $barguna['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $barguna['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $barguna['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $barguna['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $barguna['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $barguna['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $barguna['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Patuakhali">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $patuakhali['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $patuakhali['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $patuakhali['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $patuakhali['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $patuakhali['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $patuakhali['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $patuakhali['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $patuakhali['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $patuakhali['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $patuakhali['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $patuakhali['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $patuakhali['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $patuakhali['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $patuakhali['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $patuakhali['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $patuakhali['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $patuakhali['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $patuakhali['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Barisal">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $barishal['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $barishal['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $barishal['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $barishal['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $barishal['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $barishal['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $barishal['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $barishal['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $barishal['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $barishal['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $barishal['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $barishal['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $barishal['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $barishal['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $barishal['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $barishal['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $barishal['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $barishal['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Vola">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $vola['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $vola['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $vola['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $vola['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $vola['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $vola['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $vola['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $vola['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $vola['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $vola['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $vola['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $vola['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $vola['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $vola['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $vola['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $vola['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $vola['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $vola['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Laxmipur">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $laxmipur['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $laxmipur['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $laxmipur['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $laxmipur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $laxmipur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $laxmipur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $laxmipur['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $laxmipur['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $laxmipur['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $laxmipur['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $laxmipur['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $laxmipur['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $laxmipur['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $laxmipur['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $laxmipur['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $laxmipur['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $laxmipur['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $laxmipur['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Noakhali">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $noakhali['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $noakhali['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $noakhali['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $noakhali['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $noakhali['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $noakhali['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $noakhali['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $noakhali['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $noakhali['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $noakhali['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $noakhali['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $noakhali['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $noakhali['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $noakhali['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $noakhali['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $noakhali['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $noakhali['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $noakhali['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Feni">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $feni['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $feni['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $feni['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $feni['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $feni['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $feni['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $feni['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $feni['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $feni['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $feni['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $feni['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $feni['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $feni['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $feni['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $feni['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $feni['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $feni['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $feni['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Chittagong">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $chittagong['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $chittagong['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $chittagong['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $chittagong['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $chittagong['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $chittagong['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $chittagong['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $chittagong['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $chittagong['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $chittagong['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $chittagong['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $chittagong['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $chittagong['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $chittagong['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $chittagong['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $chittagong['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $chittagong['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $chittagong['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Khagrachari">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $khagrachari['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $khagrachari['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $khagrachari['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $khagrachari['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $khagrachari['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $khagrachari['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $khagrachari['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $khagrachari['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $khagrachari['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $khagrachari['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $khagrachari['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $khagrachari['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $khagrachari['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $khagrachari['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $khagrachari['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $khagrachari['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $khagrachari['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $khagrachari['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Rangamati">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $rangamati['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $rangamati['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $rangamati['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rangamati['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rangamati['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rangamati['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $rangamati['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $rangamati['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $rangamati['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $rangamati['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $rangamati['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $rangamati['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $rangamati['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $rangamati['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $rangamati['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $rangamati['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $rangamati['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $rangamati['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="Bandorban">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $bandorban['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $bandorban['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $bandorban['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bandorban['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bandorban['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bandorban['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $bandorban['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $bandorban['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $bandorban['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $bandorban['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $bandorban['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $bandorban['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $bandorban['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $bandorban['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $bandorban['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $bandorban['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $bandorban['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $bandorban['avg_hum'] ;?>% </h4>
</div>
</div>
</div>
<div id="CoxBazar">
<div class="district">
<div class="title">
<h1>জেলা : <?php echo $coxbazar['district'] ;?></h1>
</div>
<div class="content">
<h4>কৃষি অঞ্চল : <?php echo $coxbazar['agri_zone'] ;?></h4>
<h4>চাষযোগ্য জমি : <?php echo $coxbazar['land'] ;?> হেক্টর</h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $coxbazar['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $coxbazar['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $coxbazar['min_produce'] ;?> </h4>
</div>
</div>
<div class="district2">
<div class="only-content">
<h4>গড় উৎপাদন : <?php echo $coxbazar['avg_produce'] ;?> লাখ মে. টন </h4>
<h4>সর্বোচ্চ উৎপাদিত ফসল : <?php echo $coxbazar['max_produce'] ;?> </h4>
<h4>সর্বনিম্ন উৎপাদিত ফসল : <?php echo $coxbazar['min_produce'] ;?> </h4>
</div>
</div>
<div class="district3">
<div class="title">
<h1>উৎপাদিত ফসলসমূহ </h1>
</div>
<div class="content">
<h4><?php echo $coxbazar['crops'] ;?></h4>
</div>
</div>
<div class="district-soil">
<div class="title">
<h1>মাটির বিবরন</h1>
</div>
<div class="content">
<h4>মাটির ধরন: <?php echo $coxbazar['soil_type'] ;?>, উর্বরতা শ্রেনী : <?php echo $coxbazar['fertile_class'] ;?></h4>
<h4>সেচ পদ্ধতি : <?php echo $coxbazar['irrigation_process'] ;?></h4>
</div>
</div>
<div class="district-weather">
<div class="title">
<h1>আবহাওয়া বিবরন </h1>
</div>
<div class="content">
<h4>গড় বৃষ্টিপাত: <?php echo $coxbazar['avg_rain'] ;?> মিমি </h4>
<h4>গড় তাপমাত্রা : <?php echo $coxbazar['avg_temp'] ;?> ডিগ্রি সে. </h4>
<h4>গড় সর্বোচ্চ তাপমাত্রা : <?php echo $coxbazar['avg_max_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় সর্বনিম্ন তাপমাত্রা : <?php echo $coxbazar['avg_min_temp'] ;?> ডিগ্রি সে.</h4>
<h4>গড় আদ্রতা : <?php echo $coxbazar['avg_hum'] ;?>% </h4>
</div>
</div>
</div> <!-- district text info -->
<div class="social-popout">
<a href="#a"><img id="facebook" src="images/social/facebook.png" /></a>
<a href="#a"><img id="twitter" src="images/social/twitter.png" /></a>
<a href="#a"><img id="g-plus" src="images/social/g-plus.png" /></a>
</div>
</div><file_sep>/info_update.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/view-update.css" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css_infoBank/myown.css" />
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js" charset="utf-8"></script>
<script>
function getdetails() {
$('#loader').hide();
$('#updated').hide();
var check = $('#district-box').val();
//console.log(check);
if(check == '0')
{
alert("You haven't select any district");
}
else
{
var name = check;
//console.log(name);
$.ajax({
type: "POST",
url: "view_action.php",
data: {district:name},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
document.getElementById("tbox1").value = data.b;
document.getElementById("tbox2").value = data.c;
document.getElementById("tbox3").value = data.d;
document.getElementById("tbox4").value = data.e;
document.getElementById("tbox5").value = data.f;
$("#tbox6").html(data.g);
document.getElementById("tbox7").value = data.h;
$("#tbox8").html(data.i);
document.getElementById("tbox9").value = data.j;
document.getElementById("tbox10").value = data.k;
document.getElementById("tbox11").value = data.l;
document.getElementById("tbox12").value = data.m;
document.getElementById("tbox13").value = data.n;
document.getElementById("tbox14").value = data.o;
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log("Some error happened");
}
});
}
}
</script>
</head>
<body>
<div id="header">
<nav class="navbar navbar-default " role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="mainpage.php">মূলপাতা</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">
<li class="active"><a href="#a">জেলা তথ্য</a></li>
<li><a href="crop_infobank_update.php">তথ্য ব্যাংক</a></li>
<li><a href="recent_news_update.php">কৃষি নিউজ</a></li>
<li><a href="tools_info_update.php">প্রযুক্তি তথ্য</a></li>
<!--<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
<li class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li> -->
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="খুঁজুন">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><img src="http://placehold.it/20x20" alt="Profile Image" style="display: inline-block !important"/><b class="caret grey"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
<div class="hero-unit">
<div class="container">
<div id="info-title" class="alert alert-error fade in">
<h4>জেলা নির্বাচন করুন তথ্য দেখার এবং হালনাগাদ করবার জন্য</h4>
</div>
<div class="row">
<h3><label class="col-md-3 label label-primary">জেলা</label></h3>
<div class="col-md-6">
<select id="district-box" class="input-sm" onChange="getdetails()">
<option value="0">---</option>
<?php
include('connect.php');
$query = $con->query("Select id,district from area_info");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->district."'>".$row->district."</option>";
}
?>
</select>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">কৃষি অঞ্চল</label></h3>
<div class="col-md-6">
<textarea id="tbox1" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">কৃষি জমি (হেক্টর)</label></h3>
<div class="col-md-6">
<textarea id="tbox2" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">গড় উৎপাদন (মে.টন)</label></h3>
<div class="col-md-6">
<textarea id="tbox3" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">সর্বোচ্চ উৎপাদন (মে.টন)</label></h3>
<div class="col-md-6">
<textarea id="tbox4" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">সর্বনিম্ন উৎপাদন (মে.টন)</label></h3>
<div class="col-md-6">
<textarea id="tbox5" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">উৎপাদিত শস্যাদি</label></h3>
<div class="col-md-6">
<textarea id="tbox6" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">জমির ধরন</label></h3>
<div class="col-md-6">
<textarea id="tbox7" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">জমির উর্বরতা শ্রেণী</label></h3>
<div class="col-md-6">
<textarea id="tbox8" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">সেচ ব্যবস্থা</label></h3>
<div class="col-md-6">
<textarea id="tbox9" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">গড় বৃষ্টিপাত (মি.মি.)</label></h3>
<div class="col-md-6">
<textarea id="tbox10" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">গড় তাপমাত্রা (সে.)</label></h3>
<div class="col-md-6">
<textarea id="tbox11" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">গড় সর্বোচ্চ তাপমাত্রা (সে.)</label></h3>
<div class="col-md-6">
<textarea id="tbox12" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">গড় সর্বনিম্ন তাপমাত্রা (সে.)</label></h3>
<div class="col-md-6">
<textarea id="tbox13" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">গড় আর্দ্রতা (%)</label></h3>
<div class="col-md-6">
<textarea id="tbox14" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label id="no-label" class="label-des col-md-3 label label-primary">Primary2</label></h3>
<div class="col-md-6">
<button type="submit" name='submit' id="filter-button" class="btn btn-success " onclick="showdetails()">তথ্য হালনাগাদ</button>
<img id="loader" src="images/loader.gif" style="height:30px; width:30px; display:none;">
<img id="updated" src="images/success.png" style="height:25px; width:25px; display:none;">
</div>
</div>
</div>
</div>
<div id="header">
<nav class="navbar navbar-default " role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="#">Brand</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">
<li class="active"><a href="#">Link</a></li>
<li><a href="#b">Link</a></li>
<li><a href="#c">Link</a></li>
<li><a href="#d">Link</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
<script>
function showdetails() {
var data1 = document.getElementById("tbox1").value;
var data2 = document.getElementById("tbox2").value;
var data3 = document.getElementById("tbox3").value;
var data4 = document.getElementById("tbox4").value;
var data5 = document.getElementById("tbox5").value;
var data6 = document.getElementById("tbox6").value;
var data7 = document.getElementById("tbox7").value;
var data8 = document.getElementById("tbox8").value;
var data9 = document.getElementById("tbox9").value;
var data10 = document.getElementById("tbox10").value;
var data11= document.getElementById("tbox11").value;
var data12 = document.getElementById("tbox12").value;
var data13 = document.getElementById("tbox13").value;
var data14 = document.getElementById("tbox14").value;
//var dataset = clicked_id;
var district = $('#district-box').val();
//var value = $('#'+box_id).val();
//console.log(value);
$('#loader').show();
//$('#'+img_id + ' .image-loader').show();
//setInterval(function(){alert("Hello")},3000);
$.ajax({
type: "POST",
url: "update_action.php",
data: {data1:data1,data2:data2,data3:data3,data4:data4,data5:data5,data6:data6,data7:data7,data8:data8,data9:data9,data10:data10,data11:data11,data12:data12,data13:data13,data14:data14,district:district},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
$('#loader').hide();
$('#updated').show();
document.getElementById("tbox1").value = data.b;
document.getElementById("tbox2").value = data.c;
document.getElementById("tbox3").value = data.d;
document.getElementById("tbox4").value = data.e;
document.getElementById("tbox5").value = data.f;
$("#tbox6").html(data.g);
document.getElementById("tbox7").value = data.h;
$("#tbox8").html(data.i);
document.getElementById("tbox9").value = data.j;
document.getElementById("tbox10").value = data.k;
document.getElementById("tbox11").value = data.l;
document.getElementById("tbox12").value = data.m;
document.getElementById("tbox13").value = data.n;
document.getElementById("tbox14").value = data.o;
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log("Some error happened");
}
});
}
</script>
</body>
</html><file_sep>/project_reg.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
session_start();
if(isset($_POST['signupsubmit']))
{
$usernamesignup = $_POST['usernamesignup'];
$passwordsignup = $_POST['passwordsignup'];
$passwordsignup_confirm = $_POST['passwordsignup_confirm'];
$emailsignup = $_POST['emailsignup'];
$usernamesignup = strip_tags($usernamesignup);
$usernamesignup = $con->real_escape_string($usernamesignup);
$passwordsignup = strip_tags($passwordsignup);
$passwordsignup = $con->real_escape_string($passwordsignup);
$passwordsignup = md5($passwordsignup);
$passwordsignup_confirm = strip_tags($passwordsignup_confirm);
$passwordsignup_confirm = $con->real_escape_string($passwordsignup_confirm);
$passwordsignup_confirm = md5($passwordsignup_confirm);
date_default_timezone_set('Asia/Dhaka');
$date = date('Y:m:d h:i:s');
$query = $con->query("insert into users (username,password,email_add,joined,type) values ('$usernamesignup','$passwordsignup','$emailsignup','$date','user')");
if ($query)
{
header('location:project_reg.php');
}else
{
echo "Error";
}
}
if(isset($_POST['loginsubmit']))
{
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$username = strip_tags($username);
$username = $con->real_escape_string($username);
$password = strip_tags($password);
$password = $con->real_escape_string($password);
$password = md5($password);
$query = $con->query("select * from users where username = '$username' and password = '$password'");
$row = $query->fetch_array();
$_SESSION['userlogin'] = $row['username'];
header('location:mainpage.php');
}
?>
<!DOCTYPE html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6 lt8"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie7 lt8"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie8 lt8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->
<html lang="en" class="no-js"> <!--<![endif]-->
<head>
<meta charset="UTF-8" />
<!-- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> -->
<title>Login and Registration</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Login and Registration Form with HTML5 and CSS3" />
<meta name="keywords" content="html5, css3, form, switch, animation, :target, pseudo-class" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" type="text/css" href="css_reg/demo.css" />
<link rel="stylesheet" type="text/css" href="css_reg/style.css" />
<link rel="stylesheet" type="text/css" href="css_reg/animate-custom.css" />
</head>
<body>
<div class="container">
<!-- Codrops top bar -->
<div class="codrops-top">
<a href="">
</a>
<span class="right">
</span>
<div class="clr"></div>
</div><!--/ Codrops top bar -->
<header>
</header>
<section>
<div id="container_demo" >
<!-- hidden anchor to stop jump http://www.css3create.com/Astuce-Empecher-le-scroll-avec-l-utilisation-de-target#wrap4 -->
<a class="hiddenanchor" id="toregister"></a>
<a class="hiddenanchor" id="tologin"></a>
<div id="wrapper">
<div id="login" class="animate form">
<form action="project_reg.php" autocomplete="on" method="post">
<h1>Log in</h1>
<p>
<label for="username" class="uname" data-icon="u" > Your username </label>
<input id="username" name="username" required="required" type="text" placeholder="myusername"/>
</p>
<p>
<label for="password" class="youpasswd" data-icon="p"> Your password </label>
<input id="password" name="password" required="required" type="password" placeholder="eg. <PASSWORD>" />
</p>
<p class="login button">
<input type="submit" name="loginsubmit" value="Login" />
</p>
<p class="change_link">
Not a member yet ?
<a href="#toregister" class="to_register">Join us</a>
<a href="mainpage.php" class="to_register">Home</a>
</p>
</form>
</div>
<div id="register" class="animate form">
<form action="project_reg.php" autocomplete="on" method="post">
<h1> Sign up </h1>
<p>
<label for="usernamesignup" class="uname" data-icon="u">Your username</label>
<input id="usernamesignup" name="usernamesignup" required="required" type="text" placeholder="myusername" />
</p>
<p>
<label for="emailsignup" class="youmail" data-icon="e" > Your email</label>
<input id="emailsignup" name="emailsignup" required="required" type="email" placeholder="<EMAIL>"/>
</p>
<p>
<label for="passwordsignup" class="youpasswd" data-icon="p">Your password </label>
<input id="passwordsignup" name="passwordsignup" required="required" type="password" placeholder="eg.<PASSWORD>"/>
</p>
<p>
<label for="passwordsignup_confirm" class="youpasswd" data-icon="p">Please confirm your password </label>
<input id="passwordsignup_confirm" name="passwordsignup_confirm" required="required" type="password" placeholder="eg. <PASSWORD>"/>
</p>
<p class="signin button">
<input type="submit" name="signupsubmit" value="Sign up"/>
</p>
<p class="change_link">
Already a member ?
<a href="#tologin" class="to_register"> Log in </a>
<a href="mainpage.php" class="to_register"> Home </a>
</p>
</form>
</div>
</div>
</div>
</section>
</div>
</body>
</html><file_sep>/crop_info_bank.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Agro Search</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- stylesheets -->
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/login.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/weatherstyle.css" type="text/css">
<link rel="stylesheet" type="text/css" href="css/navstyle.css" />
<link rel="stylesheet" type="text/css" href="css/buttons.css" />
<link rel="stylesheet" type="text/css" href="css_infoBank/style.css" />
<link rel="stylesheet" type="text/css" href="css_infoBank/myown.css" />
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css' />
<script type="text/javascript" src="js/modernizr.custom.79639.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="js/all-local.js" charset="utf-8"></script>
<script type="text/javascript" src="js/bootstrap.js" charset="utf-8"></script>
<style type="text/css">
label {display: inline;}
</style>
<script>
function showCrops() {
var name = $('#box-1 option:selected').text();
//this.options[this.selectedIndex].innerHTML
console.log(name);
$.ajax({
type: "POST",
url: "getCropInfo.php",
data: {category:name},
//dataType: 'json',
success: function(data, textStatus, jqXHR)
{
var opts = $.parseJSON(data);
$('#box-2').empty().append('<option value="0">---</option>');
$('#box-3').empty().append('<option value="0">---</option>');
$.each(opts, function(i,d) {
$('#box-2').append('<option value="' + d.crop_id + '">' + d.crop_name + '</option>');
console.log(d.crop_id);
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
}
});
}
</script>
<script>
function showCategory() {
var name = $('#box-2 option:selected').text();
console.log(name);
if (name == '---')
{
$('#box-3').empty().append('<option value="0">---</option>');
}
else
{
$('#box-3').empty().append('<option value="0">---</option><option value="1">চাষাবাদ পদ্ধতি</option><option value="2">সেচ পদ্ধতি</option><option value="3">সার ব্যবস্থাপনা</option><option value="4">রোগ-বালাই ব্যবস্থাপনা</option><option value="5">পোকা ব্যবস্থাপনা</option><option value="6">ফসল সংগ্রহ</option><option value="7">বীজ ব্যবস্থাপনা</option><option value="8">জমি ও মাটি নির্বাচন</option><option value="9">অন্তর্বর্তীকালীন পরিচর্যা</option>');
}
}
</script>
<script>
function showInfo() {
var box1 = $('#box-1 option:selected').text();
var box2 = $('#box-2 option:selected').text();
var box3 = $('#box-3 option:selected').text();
if (box1 == '---' || box2 == '---' || box3 == '---')
{
alert("Select all options from select box");
}
else
{
var boxval1 = $('#box-1').val();
var boxval2 = $('#box-2').val();
var boxval3 = $('#box-3').val();
$.ajax({
type: "POST",
url: "getCropBankInfo.php",
data: {categoryID:boxval1,cropID:boxval2,criteria:boxval3},
//dataType: 'json',
success: function(data, textStatus, jqXHR)
{
$('#information').empty().append(data);
//document.getElementById("col-2").value = data.b;
//console.log(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
}
});
}
}
</script>
</head>
<body>
<div id="header">
<div id="logo"></div>
<div id="nav-bar">
<div id="upper-part"></div>
<div id="nav-bar1">
<div class="container">
<section class="main">
<div class="wrapper-demo">
<div id="dd" class="wrapper-dropdown-2" tabindex="1">বাংলার ফসল
<ul class="dropdown">
<?php
if (isset($_SESSION['user'])) {
echo "<li><a href='crop_info_bank.php'><i class='icon-adjust icon-large'></i>ফসলের পাতা</a></li>";
echo "<li><a href='crop_tree_nodes.php'><i class='icon-adjust icon-large'></i>ফসলের পরিচিতি</a></li>";
echo "<li><a href='info_update.php'><i class='icon-adjust icon-large'></i>তথ্য হালনাগাদ</a></li>";
}
else {
echo "<li><a href='crop_info_bank.php'><i class='icon-adjust icon-large'></i>ফসলের পাতা</a></li>";
echo "<li><a href='crop_tree_nodes.php'><i class='icon-adjust icon-large'></i>ফসলের পরিচিতি</a></li>";
}
?>
</ul>
</div>
</div>
</section>
</div>
</div>
<div id="nav-ico1">
<div class="icon-image1">
<a class="button-secondary pure-button" href="mainpage.php#weather-forecast">আবহাওয়া</a>
</div>
</div>
<div id="nav-ico2">
<div class="icon-image2">
<a class="button-secondary pure-button" href="#">আর্কাইভ</a>
</div>
</div>
<div id="nav-bar2">
<div class="container">
<section class="main">
<div class="wrapper-demo">
<div id="dd2" class="wrapper-dropdown-2" tabindex="1">কৃষি উপকরন
<ul class="dropdown">
<li><a href="#agri-tools"><i class="icon-adjust icon-large"></i>কৃষি প্রযুক্তি</a></li>
<li><a href="#"><i class="icon-adjust icon-large"></i>কৃষি প্রতিষ্ঠান</a></li>
</ul>
</div>
</div>
</section>
</div>
</div>
</div>
<div id="login-system">
<?php
if (isset($_SESSION['user'])) {
echo "<a id='admin-welcome' class='button-secondary pure-button' href='#b'>";echo $_SESSION['user'];echo "</a>";
echo "<a id='admin-logout' class='button-secondary pure-button' href='logout.php?page=crop_info_bank'>লগআউট</a>";
}
elseif (isset($_SESSION['userlogin'])) {
echo "<a id='admin-welcome' class='button-secondary pure-button' href='#b'>";echo $_SESSION['userlogin'];echo "</a>";
echo "<a id='admin-logout' class='button-secondary pure-button' href='logout.php?page=crop_info_bank'>লগআউট</a>";
}
else{
echo "<a id='admin-login' class='button-secondary pure-button' href='#a'>এডমিন প্রবেশ</a>";
echo "<a id='user-login' class='button-secondary pure-button' href='project_reg.php'>সাইট প্রবেশ</a>";
}
?>
</div>
</div>
<div id='info-holder'>
<!--<form action = "#" method = "post"> -->
<div id="select-box-holder" class="alert alert-danger fade in">
<div id="info-title" class="alert alert-error fade in">
<h4>ফসল নির্বাচন করুন তথ্য পাবার জন্য</h4>
</div>
<div id="all-box">
<div class="box-label"><label>ফসলের ধরন</label></div>
<div class="box-select">
<select id="box-1" onchange="showCrops()">
<option value="0">---</option>
<?php
$query = $con->query("Select*from categories");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->category_id."'>".$row->category."</option>";
//echo $row['category_id'];
}
?>
</select>
</div>
<div class="box-label"><label>ফসলের নাম</label></div>
<div class="box-select">
<select id="box-2" onchange="showCategory()">
<option value="0">---</option>
</select>
</div>
<div class="box-label"><label>তথ্যের বিষয়</label></div>
<div class="box-select">
<select id="box-3">
<option value="0">---</option>
</select>
</div>
</div>
<div id="button-holder">
<button type="submit" name='submit' id="filter-button" class="btn btn-primary" onclick="showInfo()">তথ্য দেখুন</button>
</div>
</div>
<!--</form>-->
<div id="crop-info-holder" class="alert alert-danger fade in" style="overflow-y:auto">
<p id="information"></p>
</div>
</div>
<div id="footer">
<div id="home-logo"></div>
<div id="all-link">
<div id="links">
<ul>
<li><a href="">মূলপাতা |</a></li>
<li><a href=""> আমাদের সম্পর্কে |</a></li>
<li><a href=""> যোগাযোগ</a></li>
</ul>
</div>
<div id="ref-img">
<div id="img-holder">
<a href=""><img class="footer-img" src="images/footer_img/ais.png"></a>
<a href=""><img class="footer-img" src="images/footer_img/bsb.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/dae.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/OWMap.png"></a>
<a href=""><img class="footer-img" src="images/footer_img/brri.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/barc.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/bari.jpg"></a>
</div>
</div>
</div>
<div id="top-button"></div>
</div>
<!-- Popup div for login Form -->
<div id="form" >
<form name="login-form" class="login-form" action="admin_login.php" method="post">
<div id="admin-header">
<div class="admin-icon"><img id="img-admin" src="images/admin.png"></div>
<div class="admin-text">Admin Login</div>
</div>
<div id="user-part">
<div class="user-box">
<div class="user-icon"><img id="img-user" src="images/user.png"></div>
<div class="text-box">
<input name="username" type="text" class="input username" required = "required" placeholder="Username"/><!--END USERNAME-->
</div>
</div>
<div class="user-box">
<div class="user-icon"><img id="img-pass" src="images/pass.png"></div>
<div class="text-box">
<input name="password" type="password" class="input password" required = "required" placeholder="******"/><!--END PASSWORD-->
</div>
</div>
</div>
<div id="admin-footer">
<div class="btn-box1">
<input type="submit" name="submit" value="Login" class="button" /><!--END LOGIN BUTTON-->
</div>
<div class="btn-box2">
<input type="submit" name="submit" value="Close" class="close" /><!--END REGISTER BUTTON-->
</div>
</div>
</form>
</div>
<!--END WRAPPER-->
</body>
</html>
<file_sep>/connect.php
<?php
//connect.php
$con=mysqli_connect("localhost","root","","agri_web");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!mysqli_set_charset($con, "utf8")) {
printf("Error loading character set utf8: %s\n", mysqli_error($con));
}
$item_per_page = 1;
?> <file_sep>/new_post.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Agro Search</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- stylesheets -->
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
<script src="js/jquery-1.10.2.min.js"></script>
<style type="text/css">
#post-page{
margin: auto;
width: 800px;
}
label {display: block;}
</style>
<script>
function showCrops() {
var name = $('#category-box option:selected').text();
//this.options[this.selectedIndex].innerHTML
console.log(name);
$.ajax({
type: "POST",
url: "getCropName.php",
data: {category:name},
//dataType: 'json',
success: function(data, textStatus, jqXHR)
{
var opts = $.parseJSON(data);
$('#crop-box').empty().append('<option value="0">নির্বাচন করুন</option>');
$.each(opts, function(i,d) {
$('#crop-box').append('<option value="' + d.crop_id + '">' + d.crop_name + '</option>');
console.log(d.crop_id);
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
}
});
}
</script>
</head>
<body>
<div id="post-page">
<form action = "crop_info_insert.php" method = "post">
<label>Category:</label>
<select id="category-box" name="category_id" onchange="showCrops()" >
<option value ="0">নির্বাচন করুন</option>
<?php
$query = $con->query("Select*from categories");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->category_id."'>".$row->category."</option>";
//echo $row['category_id'];
}
?>
</select>
<label>Crops:</label>
<select id="crop-box" name="crop_id"><option value="5">নির্বাচন করুন</option></select>
<label for="body">চাষাবাদ:</label>
<textarea id="col-2" name="cultivation" cols=40 rows=5></textarea>
<label for="body">সেচ:</label>
<textarea id="col-2" name="irrigation" cols=40 rows=5></textarea>
<label for="body">সার ব্যবস্থাপনা:</label>
<textarea id="col-2" name="fertilizer" cols=40 rows=5></textarea>
<label for="body">রোগ প্রতিকার:</label>
<textarea id="col-2" name="disease" cols=40 rows=5></textarea>
<label for="body">পোকা ব্যবস্থাপনা:</label>
<textarea id="col-2" name="insects" cols=40 rows=5></textarea>
<label for="body">ফসল সংগ্রহ</label>
<textarea id="col-2" name="harvest" cols=40 rows=5></textarea>
<label for="body">বীজ ব্যবস্থাপনা:</label>
<textarea id="col-2" name="seed" cols=40 rows=5></textarea>
<label for="body">মাটি ও জমি বাছাই:</label>
<textarea id="col-2" name="soil_land" cols=40 rows=5></textarea>
<label for="body">পরিচর্যা:</label>
<textarea id="col-2" name="caring" cols=40 rows=5></textarea>
<br />
<input type="submit" name="submit">
</form>
</div>
</body>
</html>
<file_sep>/view_action.php
<?php
include("connect.php");
$district = $_POST['district'];
$sql = mysqli_query($con,"SELECT * from area_info where district ='".$district."' ");
$row=mysqli_fetch_array($sql);
echo json_encode(array(
"a" => $row['district'],
"b" => $row['agri_zone'],
"c" => $row['land'],
"d" => $row['avg_produce'],
"e" => $row['max_produce'],
"f" => $row['min_produce'],
"g" => $row['crops'],
"h" => $row['soil_type'],
"i" => $row['fertile_class'],
"j" => $row['irrigation_process'],
"k" => $row['avg_rain'],
"l" => $row['avg_temp'],
"m" => $row['avg_max_temp'],
"n" => $row['avg_min_temp'],
"o" => $row['avg_hum']
)
);
?><file_sep>/update_action.php
<?php
include("connect.php");
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$data3 = $_POST['data3'];
$data4 = $_POST['data4'];
$data5 = $_POST['data5'];
$data6 = $_POST['data6'];
$data7 = $_POST['data7'];
$data8 = $_POST['data8'];
$data9 = $_POST['data9'];
$data10 = $_POST['data10'];
$data11 = $_POST['data11'];
$data12 = $_POST['data12'];
$data13 = $_POST['data13'];
$data14 = $_POST['data14'];
$district = $_POST['district'];
$sql1 = mysqli_query($con,"UPDATE area_info set agri_zone = '".$data1."',land = '".$data2."',avg_produce = '".$data3."',max_produce = '".$data4."',min_produce = '".$data5."',crops = '".$data6."',soil_type = '".$data7."',fertile_class = '".$data8."',irrigation_process = '".$data9."',avg_rain = '".$data10."',avg_temp = '".$data11."',avg_max_temp = '".$data12."',avg_min_temp = '".$data13."',avg_hum = '".$data14."' where district = '".$district."' ");
$sql2 = mysqli_query($con,"SELECT * from area_info where district ='".$district."' ");
$row=mysqli_fetch_array($sql2);
echo json_encode(array(
"a" => $row['district'],
"b" => $row['agri_zone'],
"c" => $row['land'],
"d" => $row['avg_produce'],
"e" => $row['max_produce'],
"f" => $row['min_produce'],
"g" => $row['crops'],
"h" => $row['soil_type'],
"i" => $row['fertile_class'],
"j" => $row['irrigation_process'],
"k" => $row['avg_rain'],
"l" => $row['avg_temp'],
"m" => $row['avg_max_temp'],
"n" => $row['avg_min_temp'],
"o" => $row['avg_hum']
)
);
?><file_sep>/mainpage.php
<?php
include("district_info_php.php");
header('Content-type: text/html; charset=utf-8');
include("connect.php");
session_start();
$results = mysqli_query($con,"SELECT COUNT(*) FROM agri_tools_info");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li><a href="#" class="paginate_click" id="'.$i.'-page">'.$i.'</a></li>';
}
$pagination .= '</ul>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Agro Search</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- stylesheets -->
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/login.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/map.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/qTip.css" type="text/css">
<link rel="stylesheet" href="css/weatherstyle.css" type="text/css">
<link rel="stylesheet" type="text/css" href="css/navstyle.css" />
<link rel="stylesheet" type="text/css" href="css/buttons.css" />
<link rel="stylesheet" type="text/css" href="css_infoBank/myown.css" />
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css' />
<link rel="stylesheet" type="text/css" href="css/popup.css" />
<link href="assets/css/main.css" rel="stylesheet">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<script type="text/javascript" src="js/modernizr.custom.79639.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="js/raphael.js" charset="utf-8"></script>
<script type="text/javascript" src="js/g.raphael.js" charset="utf-8"></script>
<script type="text/javascript" src="js/g.pie.js" charset="utf-8"></script>
<script type="text/javascript" src="js/path.js" charset="utf-8"></script>
<script type="text/javascript" src="js/qTip.js" charset="utf-8"></script>
<script type="text/javascript" src="js/all-local.js" charset="utf-8"></script>
<script type="text/javascript" src="js/weather.js" charset="utf-8"></script>
<script type="text/javascript" src="js/jquery.newsTicker.js" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
</head>
<body>
<div id="header">
<div id="logo"></div>
<div id="nav-bar">
<div id="upper-part"></div>
<div id="nav-bar1">
<div class="container">
<section class="main">
<div class="wrapper-demo">
<div id="dd" class="wrapper-dropdown-2" tabindex="1">বাংলার ফসল
<ul class="dropdown">
<?php
if (isset($_SESSION['user'])) {
echo "<li><a href='crop_info_bank.php'><i class='icon-adjust icon-large'></i>ফসলের পাতা</a></li>";
echo "<li><a href='crop_tree_nodes.php'><i class='icon-adjust icon-large'></i>ফসলের পরিচিতি</a></li>";
echo "<li><a href='info_update.php'><i class='icon-adjust icon-large'></i>তথ্য হালনাগাদ</a></li>";
}
else {
echo "<li><a href='crop_info_bank.php'><i class='icon-adjust icon-large'></i>ফসলের পাতা</a></li>";
echo "<li><a href='crop_tree_nodes.php'><i class='icon-adjust icon-large'></i>ফসলের পরিচিতি</a></li>";
}
?>
</ul>
</div>
</div>
</section>
</div>
</div>
<div id="nav-ico1">
<div class="icon-image1">
<a class="button-secondary pure-button" href="#weather-forecast">আবহাওয়া</a>
</div>
</div>
<div id="nav-ico2">
<div class="icon-image2">
<a class="button-secondary pure-button" href="#">আর্কাইভ</a>
</div>
</div>
<div id="nav-bar2">
<div class="container">
<section class="main">
<div class="wrapper-demo">
<div id="dd2" class="wrapper-dropdown-2" tabindex="1">কৃষি উপকরন
<ul class="dropdown">
<li><a href="#agri-tools"><i class="icon-adjust icon-large"></i>কৃষি প্রযুক্তি</a></li>
<li><a href="#"><i class="icon-adjust icon-large"></i>কৃষি প্রতিষ্ঠান</a></li>
</ul>
</div>
</div>
</section>
</div>
</div>
</div>
<div id="login-system">
<?php
if (isset($_SESSION['user'])) {
echo "<a id='admin-welcome' class='button-secondary pure-button' href='#b'>";echo $_SESSION['user'];echo "</a>";
echo "<a id='admin-logout' class='button-secondary pure-button' href='logout.php'>লগআউট</a>";
}
elseif (isset($_SESSION['userlogin'])) {
echo "<a id='admin-welcome' class='button-secondary pure-button' href='#b'>";echo $_SESSION['userlogin'];echo "</a>";
echo "<a id='admin-logout' class='button-secondary pure-button' href='logout.php'>লগআউট</a>";
}
else{
echo "<a id='admin-login' class='button-secondary pure-button' href='#a'>এডমিন প্রবেশ</a>";
echo "<a id='user-login' class='button-secondary pure-button' href='project_reg.php'>সাইট প্রবেশ</a>";
}
?>
</div>
</div>
<div id="holder">
<div id="sidebar">
<div id="piechart">
<div id="piechart-holder"></div>
</div>
<div id="ticker">
<div id="ticker-news">
<div id="nt-example1-container">
<i class="fa fa-arrow-up" id="nt-example1-prev"></i>
<ul id="nt-example1">
<?php
$sql = $con->query("SELECT news_title FROM recent_news");
while($row = $sql->fetch_assoc())
{
echo "<li>"; echo $row['news_title']; echo "<a href='c#'>";echo " ";echo "Read more...</a></li>";
}
?>
</ul>
<i class="fa fa-arrow-down" id="nt-example1-next"></i>
</div>
</div>
<div id="ticker-weather">
<select id="district-list" onchange = "showWeather()">
<option value="0">জেলা নির্বাচন করুন</option>
<?php
$query = $con->query("Select id,district_eng,district from area_info");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->district_eng."'>".$row->district."</option>";
//echo $row['category_id'];
}
?>
</select>
</div>
</div>
</div>
<!-- map div start using svg and raphael js -->
<?php
require_once 'district_info_html.php';
?>
<!-- map div end using svg and raphael js -->
</div>
<div id="weather-forecast">
<div id="wind-hum">
<div class="hum"></div>
<div class="speed"></div>
<div class="direction"></div>
<div class="pressure"></div>
</div>
<div id="icon">
<div class="icon-type"></div>
<div class="sky"></div>
</div>
<div id="temp">
<div class="temp-value"></div>
<div class="temp-title"><p>তাপমাত্রা</p></div>
</div>
<div id="sun">
<div class="rise">
<div class="rise-value"></div>
<div class="rise-title"><p>সূর্যোদয়</p></div>
</div>
<div class="set">
<div class="set-value"></div>
<div class="set-title"><p>সূর্যাস্ত</p></div>
</div>
</div>
</div>
<div id="agri-tools">
<div id="results"></div>
<?php echo $pagination; ?>
</div>
<div id="footer">
<div id="home-logo"></div>
<div id="all-link">
<div id="links">
<ul>
<li><a href="">মূলপাতা |</a></li>
<li><a href=""> আমাদের সম্পর্কে |</a></li>
<li><a href=""> যোগাযোগ</a></li>
</ul>
</div>
<div id="ref-img">
<div id="img-holder">
<a href=""><img class="footer-img" src="images/footer_img/ais.png"></a>
<a href=""><img class="footer-img" src="images/footer_img/bsb.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/dae.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/OWMap.png"></a>
<a href=""><img class="footer-img" src="images/footer_img/brri.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/barc.jpg"></a>
<a href=""><img class="footer-img" src="images/footer_img/bari.jpg"></a>
</div>
</div>
</div>
<div id="top-button"></div>
</div>
<!-- Popup div for login Form -->
<div id="form" >
<form name="login-form" class="login-form" action="admin_login.php" method="post">
<div id="admin-header">
<div class="admin-icon"><img id="img-admin" src="images/admin.png"></div>
<div class="admin-text">Admin Login</div>
</div>
<div id="user-part">
<div class="user-box">
<div class="user-icon"><img id="img-user" src="images/user.png"></div>
<div class="text-box">
<input name="username" type="text" class="input username" required = "required" placeholder="Username"/><!--END USERNAME-->
</div>
</div>
<div class="user-box">
<div class="user-icon"><img id="img-pass" src="images/pass.png"></div>
<div class="text-box">
<input name="password" type="<PASSWORD>" class="input password" required = "required" placeholder="******"/><!--END PASSWORD-->
</div>
</div>
</div>
<div id="admin-footer">
<div class="btn-box1">
<input type="submit" name="submit" value="Login" class="button" /><!--END LOGIN BUTTON-->
</div>
<div class="btn-box2">
<input type="submit" name="submit" value="Close" class="close" /><!--END REGISTER BUTTON-->
</div>
</div>
</form>
</div>
<!--END WRAPPER-->
<a href="#" class="scrollToTop"></a>
<script type="text/javascript">
var nt_example1 = $('#nt-example1').newsTicker({
row_height: 80,
max_rows: 3,
duration: 4000,
prevButton: $('#nt-example1-prev'),
nextButton: $('#nt-example1-next')
});
</script>
<script type="text/javascript">
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
</script>
</body>
</html>
<file_sep>/crop_info_insert.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
session_start();
if (isset($_POST['submit'])) {
$category_id = $_POST['category_id'];
$crop_id = $_POST['crop_id'];
$cultivation = $_POST['cultivation'];
$irrigation = $_POST['irrigation'];
$fertilizer = $_POST['fertilizer'];
$disease = $_POST['disease'];
$insects = $_POST['insects'];
$harvest = $_POST['harvest'];
$seed = $_POST['seed'];
$soil_land = $_POST['soil_land'];
$caring = $_POST['caring'];
date_default_timezone_set('Asia/Dhaka');
$date = date('Y:m:d h:i:s');
/*echo $category_id;
echo $crop_id;
echo $cultivation;
echo $irrigation;
echo $fertilizer;
echo $disease;
echo $insects;
echo $harvest;
echo $seed;
echo $soil_land;
echo $caring;
echo $date; */
date_default_timezone_set('Asia/Dhaka');
$date = date('Y:m:d h:i:s');
$query = $con->query("insert into crop_info_bank (category_id,crop_id,cultivation_process,irrigation_process,fertilizer_process,disease_manage,insects_manage,harvest_collection,seed_manage,soil_land_select,interim_caring,store_date) values ('$category_id','$crop_id','$cultivation','$irrigation','$fertilizer','$disease','$insects','$harvest','$seed','$soil_land','$caring','$date')");
if ($query)
{
echo 'Insertion Complete';
}else
{
echo 'Error';
}
}
?><file_sep>/updateCropBankInfo.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category_id = $_POST['categoryID'];
$crop_id = $_POST['cropID'];
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$data3 = $_POST['data3'];
$data4 = $_POST['data4'];
$data5 = $_POST['data5'];
$data6 = $_POST['data6'];
$data7 = $_POST['data7'];
$data8 = $_POST['data8'];
$data9 = $_POST['data9'];
$sql1 = mysqli_query($con,"UPDATE crop_info_bank set cultivation_process = '".$data1."',irrigation_process = '".$data2."',fertilizer_process = '".$data3."',disease_manage = '".$data4."',insects_manage = '".$data5."',harvest_collection = '".$data6."',seed_manage = '".$data7."',soil_land_select = '".$data8."',interim_caring = '".$data9."' where category_id ='".$category_id."' and crop_id = '".$crop_id."' ");
$sql = $con->query("SELECT * from crop_info_bank where category_id ='".$category_id."' and crop_id = '".$crop_id."' ");
$row= $sql->fetch_array();
echo json_encode(array(
"a" => $row['cultivation_process'],
"b" => $row['irrigation_process'],
"c" => $row['fertilizer_process'],
"d" => $row['disease_manage'],
"e" => $row['insects_manage'],
"f" => $row['harvest_collection'],
"g" => $row['seed_manage'],
"h" => $row['soil_land_select'],
"i" => $row['interim_caring']
)
);
?><file_sep>/getCropName.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category = $_POST['category'];
$sql1 = $con->query("SELECT category_id from categories where category ='".$category."' ");
$row1= $sql1->fetch_array();
$sql2 = $con->query("SELECT crop_id,crop_name from crop_category where category_id ='".$row1['category_id']."' ");
$arr = array();
while($row2 = $sql2->fetch_assoc())
{
$arr[] = $row2;
}
echo json_encode($arr);
?><file_sep>/logout.php
<?php
session_start();
unset($_SESSION['user']);
unset($_SESSION['userlogin']);
$pagename = $_GET['page'] ;
if ($pagename == 'crop_info_bank')
{
header('location:crop_info_bank.php');
}elseif ($pagename == 'crop_tree_nodes')
{
header('location:crop_tree_nodes.php');
}else{
header('location:mainpage.php');
}
?><file_sep>/testPHP.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$sql = $con->query("SELECT news_title FROM recent_news");
$arr = array();
while($row = $sql->fetch_assoc())
{
//$arr[] = $row;
echo $row['news_title'];
echo "<br>";
}
?><file_sep>/district_info_php.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
//query for every district
$result1 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Dhaka'");
$result2 = mysqli_query($con,"SELECT * FROM area_info where district_eng='panchogar'");
$result3 = mysqli_query($con,"SELECT * FROM area_info where district_eng='thakurgaon'");
$result4 = mysqli_query($con,"SELECT * FROM area_info where district_eng='nilphamari'");
$result5 = mysqli_query($con,"SELECT * FROM area_info where district_eng='dinajpur'");
$result6 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Rangpur'");
$result7 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Kurigram'");
$result8 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Lalmonirhat'");
$result9 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Gaibandha'");
$result10 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Joypurhat'");
$result11 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Naogaon'");
$result12 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Bogra'");
$result13 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Jamalpur'");
$result14 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Sherpur'");
$result15 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Nawabganj'");
$result16 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Rajshahi'");
$result17 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Natore'");
$result18 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Sirajganj'");
$result19 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Tangail'");
$result20 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Mymensingh'");
$result21 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Netrokona'");
$result22 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Sunamganj'");
$result23 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Sylhet'");
$result24 = mysqli_query($con,"SELECT * FROM area_info where district_eng='MBazar'");
$result25 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Hobiganj'");
$result26 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Kishoreganj'");
$result27 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Gazipur'");
$result28 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Kushtia'");
$result29 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Pabna'");
$result30 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Manikganj'");
$result31 = mysqli_query($con,"SELECT * FROM area_info where district_eng='NGanj'");
$result32 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Narsingdi'");
$result33 = mysqli_query($con,"SELECT * FROM area_info where district_eng='BBaria'");
$result34 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Comilla'");
$result35 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Chadpur'");
$result36 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Shariatpur'");
$result37 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Madaripur'");
$result38 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Munshiganj'");
$result39 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Faridpur'");
$result40 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Gopalganj'");
$result41 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Magura'");
$result42 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Jhenaidah'");
$result43 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Chuadanga'");
$result44 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Meherpur'");
$result45 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Jessore'");
$result46 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Narail'");
$result47 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Satkhira'");
$result48 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Khulna'");
$result49 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Bagerhat'");
$result50 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Pirojpur'");
$result51 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Jhalokathi'");
$result52 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Barguna'");
$result53 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Patuakhali'");
$result54 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Barisal'");
$result55 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Vola'");
$result56 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Laxmipur'");
$result57 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Noakhali'");
$result58= mysqli_query($con,"SELECT * FROM area_info where district_eng='Feni'");
$result59 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Chittagong'");
$result60 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Khagrachari'");
$result61 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Rangamati'");
$result62 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Bandorban'");
$result63 = mysqli_query($con,"SELECT * FROM area_info where district_eng='CoxBazar'");
$result64 = mysqli_query($con,"SELECT * FROM area_info where district_eng='Rajbari'");
//all fetched text for every district
$dhaka = mysqli_fetch_array($result1);
$Panchogar = mysqli_fetch_array($result2);
$thakurgaon = mysqli_fetch_array($result3);
$nilphamari = mysqli_fetch_array($result4);
$dinajpur = mysqli_fetch_array($result5);
$rangpur = mysqli_fetch_array($result6);
$kurigram = mysqli_fetch_array($result7);
$lalmonirhat = mysqli_fetch_array($result8);
$gaibandha = mysqli_fetch_array($result9);
$joypurhat = mysqli_fetch_array($result10);
$naogaon = mysqli_fetch_array($result11);
$bogra = mysqli_fetch_array($result12);
$jamalpur = mysqli_fetch_array($result13);
$sherpur = mysqli_fetch_array($result14);
$nawabganj = mysqli_fetch_array($result15);
$rajshahi = mysqli_fetch_array($result16);
$natore = mysqli_fetch_array($result17);
$sirajganj = mysqli_fetch_array($result18);
$tangail = mysqli_fetch_array($result19);
$mymensingh = mysqli_fetch_array($result20);
$netrokona = mysqli_fetch_array($result21);
$sunamganj = mysqli_fetch_array($result22);
$sylhet = mysqli_fetch_array($result23);
$mbazar = mysqli_fetch_array($result24);
$hobiganj = mysqli_fetch_array($result25);
$kishoreganj = mysqli_fetch_array($result26);
$gajipur = mysqli_fetch_array($result27);
$kushtia = mysqli_fetch_array($result28);
$pabna = mysqli_fetch_array($result29);
$manikganj = mysqli_fetch_array($result30);
$nganj = mysqli_fetch_array($result31);
$narsingdi = mysqli_fetch_array($result32);
$bbaria = mysqli_fetch_array($result33);
$comilla = mysqli_fetch_array($result34);
$chadpur = mysqli_fetch_array($result35);
$shariatpur = mysqli_fetch_array($result36);
$madaripur = mysqli_fetch_array($result37);
$munsiganj = mysqli_fetch_array($result38);
$faridpur = mysqli_fetch_array($result39);
$gopalganj = mysqli_fetch_array($result40);
$magura = mysqli_fetch_array($result41);
$jhenaidah = mysqli_fetch_array($result42);
$chuadanga = mysqli_fetch_array($result43);
$meherpur = mysqli_fetch_array($result44);
$jessore = mysqli_fetch_array($result45);
$narail = mysqli_fetch_array($result46);
$satkhira = mysqli_fetch_array($result47);
$khulna = mysqli_fetch_array($result48);
$bagerhat = mysqli_fetch_array($result49);
$pirojpur = mysqli_fetch_array($result50);
$jhalokathi = mysqli_fetch_array($result51);
$barguna = mysqli_fetch_array($result52);
$patuakhali = mysqli_fetch_array($result53);
$barishal = mysqli_fetch_array($result54);
$vola = mysqli_fetch_array($result55);
$laxmipur = mysqli_fetch_array($result56);
$noakhali = mysqli_fetch_array($result57);
$feni = mysqli_fetch_array($result58);
$chittagong = mysqli_fetch_array($result59);
$khagrachari = mysqli_fetch_array($result60);
$rangamati = mysqli_fetch_array($result61);
$bandorban = mysqli_fetch_array($result62);
$coxbazar = mysqli_fetch_array($result63);
$rajbari = mysqli_fetch_array($result64);
mysqli_close($con);
/* reserve
$dhaka = mysqli_fetch_array($result1);
$Panchogar = mysqli_fetch_array($result2);
$thakurgaon = mysqli_fetch_array($result3);
$nilphamari
$dinajpur
$rangpur
$kurigram
Lalmonirhat
Gaibandha
Joypurhat
Naogaon
Bogra
Jamalpur
Sherpur
Nawabganj
Rajshahi
Natore
Sirajganj
Tangail
Mymensingh
Netrokona
Sunamganj
Sylhet
MBazar
Hobiganj
Kishoreganj
Gazipur
Kushtia
Pabna
Manikganj
Dhaka
NGanj
Narsingdi
BBaria
Comilla
Chadpur
Shariatpur
Madaripur
Munshiganj
Faridpur
Gopalganj
Magura
Jhenaidah
Chuadanga
Meherpur
Jessore
Narail
Satkhira
Khulna
Bagerhat
Pirojpur
Jhalokathi
Barguna
Patuakhali
Barisal
Vola
Laxmipur
Noakhali
Feni
Chittagong
Khagrachari
Rangamati
Bandorban
CoxBazar
Rajbari */
?><file_sep>/README.md
Agro-Web-Portal
===============
<file_sep>/store_tools_info2.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$title = $_POST['title'];
$description = $_POST['description'];
$filename = $_FILES['photoname']['name'];
$path = 'images/tools_img';
$mysql_path = $path."/".$filename;
$query = $con->query("insert into agri_tools_info(title,post,photo_dir) values ('$title','$description','$mysql_path')");
if ($query)
{
echo 'Insertion Complete';
}else
{
echo mysqli_error($con);
}
?>
<file_sep>/admin_login.php
<!DOCTYPE html>
<html xmlns:xlink="http://www.w3.org/1999/xlink" xml:lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
</head>
<body>
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
session_start();
if (isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
}
$sql=$con->query("select * from users where username = '$username' and password = '$<PASSWORD>'");
$row = $sql->fetch_array();
if ($row['username'] == $username) {
$_SESSION['user'] = $row['username'];
}
else {
$_SESSION['wrong'] = 'Wrong';
}
header('location:mainpage.php');
?>
</body>
</html><file_sep>/crop_tree_nodes.php
<?php
include("district_info_php.php");
header('Content-type: text/html; charset=utf-8');
include("connect.php");
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Agro Search</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- stylesheets -->
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/login.css" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/navstyle.css" />
<link rel="stylesheet" type="text/css" href="css/buttons.css" />
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css' />
<link rel="stylesheet" type="text/css" href="css/popup.css" />
<link href="assets/css/main.css" rel="stylesheet">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/node-style.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="js/all-local.js" charset="utf-8"></script>
<script type="text/javascript" src="js/d3.min.js"></script>
</head>
<body>
<div id="crop-header">
<div id="header">
<div id="logo"></div>
<div id="nav-bar">
<div id="upper-part"></div>
<div id="nav-bar1">
<div class="container">
<section class="main">
<div class="wrapper-demo">
<div id="dd" class="wrapper-dropdown-2" tabindex="1">বাংলার ফসল
<ul class="dropdown">
<?php
if (isset($_SESSION['user'])) {
echo "<li><a href='crop_info_bank.php'><i class='icon-adjust icon-large'></i>ফসলের পাতা</a></li>";
echo "<li><a href='crop_tree_nodes.php'><i class='icon-adjust icon-large'></i>ফসলের পরিচিতি</a></li>";
echo "<li><a href='info_update.php'><i class='icon-adjust icon-large'></i>তথ্য হালনাগাদ</a></li>";
}
else {
echo "<li><a href='crop_info_bank.php'><i class='icon-adjust icon-large'></i>ফসলের পাতা</a></li>";
echo "<li><a href='crop_tree_nodes.php'><i class='icon-adjust icon-large'></i>ফসলের পরিচিতি</a></li>";
}
?>
</ul>
</div>
</div>
</section>
</div>
</div>
<div id="nav-ico1">
<div class="icon-image1">
<a class="button-secondary pure-button" href="#weather-forecast">আবহাওয়া</a>
</div>
</div>
<div id="nav-ico2">
<div class="icon-image2">
<a class="button-secondary pure-button" href="#">আর্কাইভ</a>
</div>
</div>
<div id="nav-bar2">
<div class="container">
<section class="main">
<div class="wrapper-demo">
<div id="dd2" class="wrapper-dropdown-2" tabindex="1">কৃষি উপকরন
<ul class="dropdown">
<li><a href="#agri-tools"><i class="icon-adjust icon-large"></i>কৃষি প্রযুক্তি</a></li>
<li><a href="#"><i class="icon-adjust icon-large"></i>কৃষি প্রতিষ্ঠান</a></li>
</ul>
</div>
</div>
</section>
</div>
</div>
</div>
<div id="login-system">
<?php
if (isset($_SESSION['user'])) {
echo "<a id='admin-welcome' class='button-secondary pure-button' href='#b'>";echo $_SESSION['user'];echo "</a>";
echo "<a id='admin-logout' class='button-secondary pure-button' href='logout.php?page=crop_tree_nodes'>লগআউট</a>";
}
elseif (isset($_SESSION['userlogin'])) {
echo "<a id='admin-welcome' class='button-secondary pure-button' href='#b'>";echo $_SESSION['userlogin'];echo "</a>";
echo "<a id='admin-logout' class='button-secondary pure-button' href='logout.php?page=crop_tree_nodes'>লগআউট</a>";
}
else{
echo "<a id='admin-login' class='button-secondary pure-button' href='#a'>এডমিন প্রবেশ</a>";
echo "<a id='user-login' class='button-secondary pure-button' href='project_reg.php'>সাইট প্রবেশ</a>";
}
?>
</div>
</div>
</div>
<!-- Popup div for login Form -->
<div id="form" >
<form name="login-form" class="login-form" action="admin_login.php" method="post">
<div id="admin-header">
<div class="admin-icon"><img id="img-admin" src="images/admin.png"></div>
<div class="admin-text">Admin Login</div>
</div>
<div id="user-part">
<div class="user-box">
<div class="user-icon"><img id="img-user" src="images/user.png"></div>
<div class="text-box">
<input name="username" type="text" class="input username" required = "required" placeholder="Username"/><!--END USERNAME-->
</div>
</div>
<div class="user-box">
<div class="user-icon"><img id="img-pass" src="images/pass.png"></div>
<div class="text-box">
<input name="password" type="<PASSWORD>" class="input password" required = "required" placeholder="******"/><!--END PASSWORD-->
</div>
</div>
</div>
<div id="admin-footer">
<div class="btn-box1">
<input type="submit" name="submit" value="Login" class="button" /><!--END LOGIN BUTTON-->
</div>
<div class="btn-box2">
<input type="submit" name="submit" value="Close" class="close" /><!--END REGISTER BUTTON-->
</div>
</div>
</form>
</div>
<!--END WRAPPER-->
<!-- load the d3.js library -->
<script>
d3.json("nodes.json", function(error, treeData) {
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
});
// ************** Generate the tree diagram *****************
var zoom = function() {
var scale = d3.event.scale,
translation = d3.event.translate,
tbound = -height * scale,
bbound = height * scale,
lbound = (-width + margin.right) * scale,
rbound = (width - margin.left) * scale;
// limit translation to thresholds
translation = [
Math.max(Math.min(translation[0], rbound), lbound),
Math.max(Math.min(translation[1], bbound), tbound)
];
svg.attr("transform", "translate(" + translation + ")" + " scale(" + scale + ")");
}
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 1200 - margin.right - margin.left,
height = 800- margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//root = treeData[0];
//root.x0 = height / 2;
//root.y0 = 0;
//update(root);
d3.select(self.frameElement).style("height", "800px");
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.attr("xlink:href", function(d) { return d.url; })
.on("click", click);
/*nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });*/
nodeEnter.append("svg:a")
.attr("xlink:href", function(d){return d.url;}) // <-- reading the new "url" property
.append("svg:circle")
.attr("r", 1e-6)
.attr("target", "_blank")
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -13 : 13; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 10)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
d3.select("svg")
.call(d3.behavior.zoom()
.scaleExtent([0.5, 5])
.on("zoom", zoom));
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
</script>
</body>
</html><file_sep>/SQL/agri_forum.sql
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 11, 2014 at 03:44 PM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `agri_forum`
--
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE IF NOT EXISTS `categories` (
`id` smallint(6) NOT NULL,
`name` varchar(256) NOT NULL,
`description` text NOT NULL,
`position` smallint(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`, `description`, `position`) VALUES
(1, 'ধানের পà§à¦°à¦•ারà¦à§‡à¦¦', 'à§§. ধানের জাত\r\n২. ধানের রোগ\r\nà§©. ধানের চাষাবাদ', 1),
(2, 'গমের চাষাবাদ', 'à¦à¦–ানে গমের সব ধরনের চাষাবাদ পদà§à¦§à¦¤à¦¿ আলোচনা করা হবে\r\nধনà§à¦¯à¦¬à¦¾à¦¦ ।', 2);
-- --------------------------------------------------------
--
-- Table structure for table `topics`
--
CREATE TABLE IF NOT EXISTS `topics` (
`parent` smallint(6) NOT NULL,
`id` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`message` longtext NOT NULL,
`authorid` int(11) NOT NULL,
`timestamp` int(11) NOT NULL,
`timestamp2` int(11) NOT NULL,
PRIMARY KEY (`id`,`id2`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `topics`
--
INSERT INTO `topics` (`parent`, `id`, `id2`, `title`, `message`, `authorid`, `timestamp`, `timestamp2`) VALUES
(1, 1, 1, 'Topic-Rice 1', '1.Topic 1<br />\r\n2.Topic 2<br />\r\n3.Topic 3<br />\r\n4.Topic 4', 2, 1401413010, 1401840122),
(1, 1, 3, '', 'আমার কমেনà§à¦Ÿà§‡à¦° রিপà§à¦²à¦¾à¦‡ à¦à¦–নও পেলাম না !', 3, 1401840122, 1401840122),
(1, 1, 2, '', 'It was a nice topic.<br />\r\nThnx for the post :)', 3, 1401694437, 1401694437);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`avatar` text NOT NULL,
`signup_date` int(10) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `email`, `avatar`, `signup_date`) VALUES
(2, 'Ashif', '<PASSWORD>943dc26494f8941b', '<EMAIL>', '', 1401138843),
(3, 'Rocky', '20eabe5d64b0e216796e834f52d61fd0b70332fc', '<EMAIL>', '', 1401838973);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/tools_info_update.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/view-update.css" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css_infoBank/myown.css" />
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js" charset="utf-8"></script>
<script type="text/javascript">
function getdetails() {
$('#loader').hide();
$('#updated').hide();
var box1 = $('#box-1 option:selected').text();
var box2 = $('#box-2 option:selected').text();
if (box1 == '---' || box2 == '---')
{
alert("Select all options from select box");
}
else
{
var boxval1 = $('#box-1').val();
var boxval2 = $('#box-2').val();
$.ajax({
type: "POST",
url: "viewCropBankInfo.php",
data: {categoryID:boxval1,cropID:boxval2},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
document.getElementById("tbox1").value = data.a;
document.getElementById("tbox2").value = data.b;
document.getElementById("tbox3").value = data.c;
document.getElementById("tbox4").value = data.d;
document.getElementById("tbox5").value = data.e;
document.getElementById("tbox6").value = data.f;
document.getElementById("tbox7").value = data.g;
document.getElementById("tbox8").value = data.h;
document.getElementById("tbox9").value = data.i;
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
}
});
}
}
</script>
<script type="text/javascript">
function updatedetails() {
var boxval1 = $('#box-1').val();
var boxval2 = $('#box-2').val();
var data1 = document.getElementById("tbox1").value;
var data2 = document.getElementById("tbox2").value;
var data3 = document.getElementById("tbox3").value;
var data4 = document.getElementById("tbox4").value;
var data5 = document.getElementById("tbox5").value;
var data6 = document.getElementById("tbox6").value;
var data7 = document.getElementById("tbox7").value;
var data8 = document.getElementById("tbox8").value;
var data9 = document.getElementById("tbox9").value;
var district = $('#district-box').val();
$('#loader').show();
$.ajax({
type: "POST",
url: "updateCropBankInfo.php",
data: {categoryID:boxval1,cropID:boxval2,data1:data1,data2:data2,data3:data3,data4:data4,data5:data5,data6:data6,data7:data7,data8:data8,data9:data9},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
$('#loader').hide();
$('#updated').show();
document.getElementById("tbox1").value = data.a;
document.getElementById("tbox2").value = data.b;
document.getElementById("tbox3").value = data.c;
document.getElementById("tbox4").value = data.d;
document.getElementById("tbox5").value = data.e;
document.getElementById("tbox6").value = data.f;
document.getElementById("tbox7").value = data.g;
document.getElementById("tbox8").value = data.h;
document.getElementById("tbox9").value = data.i;
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log("Some error happened");
}
});
}
</script>
<script type="text/javascript">
function showCrops() {
var name = $('#box-1 option:selected').text();
console.log(name);
$.ajax({
type: "POST",
url: "getCropInfo.php",
data: {category:name},
//dataType: 'json',
success: function(data, textStatus, jqXHR)
{
var opts = $.parseJSON(data);
$('#box-2').empty().append('<option value="0">---</option>');
$('#box-3').empty().append('<option value="0">---</option>');
$.each(opts, function(i,d) {
$('#box-2').append('<option value="' + d.crop_id + '">' + d.crop_name + '</option>');
console.log(d.crop_id);
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
}
});
}
</script>
</head>
<body>
<div id="header">
<nav class="navbar navbar-default " role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="mainpage.php">মূলপাতা</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">
<li ><a href="info_update.php">জেলা তথ্য</a></li>
<li ><a href="crop_infobank_update.php">তথ্য ব্যাংক</a></li>
<li><a href="recent_news_update.php">কৃষি নিউজ</a></li>
<li class="active"><a href="#b">প্রযুক্তি তথ্য</a></li>
<!--<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
<li class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li> -->
</ul>
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="খুঁজুন">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><img src="http://placehold.it/20x20" alt="Profile Image" style="display: inline-block !important"/><b class="caret grey"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
<div class="hero-unit">
<div class="container">
<div id="info-title" class="alert alert-success fade in">
<h4>ফসল নির্বাচন করুন তথ্য দেখার এবং হালনাগাদ করবার জন্য</h4>
</div>
<div class="row">
<h3><label class="col-md-3 label label-primary">ফসল নির্বাচন</label></h3>
<div class="col-md-6">
<select id="box-1" class="input-sm" onchange="showCrops()">
<option value="0">---</option>
<?php
$query = $con->query("Select*from categories");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->category_id."'>".$row->category."</option>";
//echo $row['category_id'];
}
?>
</select>
<select id="box-2" class="input-sm" >
<option value="0">---</option>
</select>
<button type="submit" name='submit' id="filter-button" class="btn btn-primary " onclick="getdetails()">তথ্য দেখুন</button>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">চাষাবাদ পদ্ধতি</label></h3>
<div class="col-md-6">
<textarea id="tbox1" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">সেচ ব্যবস্থাপনা</label></h3>
<div class="col-md-6">
<textarea id="tbox2" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">সার ব্যবস্থাপনা</label></h3>
<div class="col-md-6">
<textarea id="tbox3" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">রোগ ব্যবস্থাপনা</label></h3>
<div class="col-md-6">
<textarea id="tbox4" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">পোকা ব্যবস্থাপনা</label></h3>
<div class="col-md-6">
<textarea id="tbox5" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">ফসল সংগ্রহ</label></h3>
<div class="col-md-6">
<textarea id="tbox6" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">বীজ ব্যবস্থাপনা</label></h3>
<div class="col-md-6">
<textarea id="tbox7" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">জমি ও মাটি নির্বাচন</label></h3>
<div class="col-md-6">
<textarea id="tbox8" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label class="label-des col-md-3 label label-primary">অন্তর্বর্তীকালীন পরিচর্যা</label></h3>
<div class="col-md-6">
<textarea id="tbox9" class="form-control" rows="2"></textarea>
</div>
</div>
<div class="row">
<h3><label id="no-label" class="label-des col-md-3 label label-primary">Primary2</label></h3>
<div class="col-md-6">
<button type="submit" name='submit' id="filter-button" class="btn btn-success " onclick="updatedetails()">তথ্য হালনাগাদ</button>
<img id="loader" src="images/loader.gif" style="height:30px; width:30px; display:none;">
<img id="updated" src="images/success.png" style="height:25px; width:25px; display:none;">
</div>
</div>
</div>
</div>
<div id="header">
<nav class="navbar navbar-default " role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="#">Brand</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">
<li class="active"><a href="#">Link</a></li>
<li><a href="#b">Link</a></li>
<li><a href="#c">Link</a></li>
<li><a href="#d">Link</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
</body>
</html><file_sep>/viewCropBankInfo.php
<?php
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category_id = $_POST['categoryID'];
$crop_id = $_POST['cropID'];
$sql = $con->query("SELECT * from crop_info_bank where category_id ='".$category_id."' and crop_id = '".$crop_id."' ");
$row= $sql->fetch_array();
echo json_encode(array(
"a" => $row['cultivation_process'],
"b" => $row['irrigation_process'],
"c" => $row['fertilizer_process'],
"d" => $row['disease_manage'],
"e" => $row['insects_manage'],
"f" => $row['harvest_collection'],
"g" => $row['seed_manage'],
"h" => $row['soil_land_select'],
"i" => $row['interim_caring']
)
);
?><file_sep>/js/weather.js
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position) {
var lat = position.coords.latitude ;
var lon = position.coords.longitude;
xmlDoc=loadXMLDoc('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&mode=xml');
//x1=xmlDoc.getElementsByTagName('city');
x2=xmlDoc.getElementsByTagName('temperature');
x3=xmlDoc.getElementsByTagName('humidity');
x4=xmlDoc.getElementsByTagName('weather');
x5=xmlDoc.getElementsByTagName('sun');
x6=xmlDoc.getElementsByTagName('speed');
x7=xmlDoc.getElementsByTagName('direction');
x8=xmlDoc.getElementsByTagName('pressure');
//att1=x1.item(0).attributes.getNamedItem("name");
att2=x2.item(0).attributes.getNamedItem("value");
att3=x3.item(0).attributes.getNamedItem("value");
att4=x4.item(0).attributes.getNamedItem("value");
att5=x4.item(0).attributes.getNamedItem("icon");
att6=x5.item(0).attributes.getNamedItem("rise");
att7=x5.item(0).attributes.getNamedItem("set");
att8=x6.item(0).attributes.getNamedItem("value");
att9=x7.item(0).attributes.getNamedItem("name");
att10=x2.item(0).attributes.getNamedItem("min");
att11=x2.item(0).attributes.getNamedItem("max");
att12=x8.item(0).attributes.getNamedItem("value");
//var mintemparature = (att10.value - 273.15).toPrecision(3);
//var maxtemparature = (att11.value - 273.15).toPrecision(3);
//$('.min-max').append(' ' + mintemparature + ' °C ~ ' + mintemparature + ' °C' );
//hum translate
var hum = att3.value.split('');
var x = translate(hum[0]);
var y = translate(hum[1]);
var z = translate(hum[2]);
$('.hum').append('<p id="mid-text">' + x + y + z + "%" + '</p>' + '<p id="low-text">আর্দ্রতা</p>' );
//speed translate
var speed = att8.value.split('');
x = translate(speed[0]);
y = translate(speed[1]);
z = translate(speed[2]);
var m = translate(speed[4]);
$('.speed').append('<p id="mid-text">' + x + y + z + m + '</p>' + '<p id="low-text">বাতাসের গতি(Mps)</p>');
//air direction
var air_dir = att9.value;
var dir = translate(air_dir);
$('.direction').empty().append('<p id="mid-text2">' + dir + '</p>' + '<p id="low-text">বাতাসের প্রবাহ</p>');
//air pressure
//air pressure translate
var air = (att12.value*0.000986923266716).toPrecision(4);
var airp = air.split('');
x = translate(airp[0]);
y = translate(airp[1]);
z = translate(airp[2]);
m = translate(airp[4]);
var n = translate(airp[5]);
$('.pressure').append('<p id="mid-text">' + x + y + z + m + n + '</p>' + '<p id="low-text">বাতাসের চাপ(atm)</p>');
$('.icon-type').append('<img id="ic-image" src="images/icons/' + att5.value + '.png" />');
console.log(att5.value);
//weather condition name
var cond_name = translate(att4.value);
$('.sky').append('<p>' + cond_name + '</p>' );
//temparature translate
var temparature = (att2.value - 273.15).toPrecision(3);
var temp = temparature.split('');
x = translate(temp[0]);
y = translate(temp[1]);
z = translate(temp[2]);
m = translate(temp[3]);
$('.temp-value').append(' ' + x + y + z + m + ' °সে' );
//split to eliminate date
var split1 = att6.value.split('T');
var split2 = att7.value.split('T');
//holds UTC time
var timeA = split1[1];
var timeB = split2[1];
//split to convert as locale time
var split3 = timeA.split(':');
var split4 = timeB.split(':');
//converting by substraction as absolute number
var timeC = Math.abs(split3[0]-6);
var timeD = Math.abs(split4[0]-6);
//sun-rise-set translate
var rise1 = timeC;
var rise2 = split3[1].split('');
x = translate(rise1);
y = translate(rise2[0]);
z = translate(rise2[1]);
//join the strings again
//var time1 = timeC + ':' + split3[1] ;
//var time2 = timeD + ':' + split4[1] ;
$('.rise-value').append('ভোর ' + x + ':' + y + z );
var set1 = timeD;
var set2 = split4[1].split('');
x = translate(set1);
y = translate(set2[0]);
z = translate(set2[1]);
$('.set-value').append('সন্ধ্যা ' + x + ':' + y + z );
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
//will be called for loading xml document
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
} //finished of loading xml doc
function translate(str)
{
if (str == 0)
{
return '০' ;
}
else if (str == 1)
{
return '১' ;
}
else if (str == 2)
{
return '২' ;
}
else if (str == 3)
{
return '৩' ;
}
else if (str == 4)
{
return '৪' ;
}
else if (str == 5)
{
return '৫' ;
}
else if (str == 6)
{
return '৬' ;
}
else if (str == 7)
{
return '৭' ;
}
else if (str == 8)
{
return '৮' ;
}
else if (str == 9)
{
return '৯' ;
}
else if (str == 17)
{
return '৫' ;
}
else if (str == undefined)
{
return '' ;
}
else if (str == '.')
{
return '.' ;
}
else if (str == 'North')
{
return 'উত্তর দিকে' ;
}
else if (str == 'North-northeast' || str == 'North-NorthEast' || str == 'North-Northeast')
{
return 'উত্তর-উত্তরপূর্ব দিকে' ;
}
else if (str == 'NorthEast' || str == 'Northeast' || str == 'northeast')
{
return 'উত্তরপূর্ব দিকে' ;
}
else if (str == 'East')
{
return 'পূর্ব দিকে' ;
}
else if (str == 'SouthEast' || str == 'Southeast' || str == 'southeast')
{
return 'দক্ষিন-পূর্ব দিকে' ;
}
else if (str == 'South-SouthEast' || str == 'South-southeast' || str == 'South-Southeast')
{
return 'দক্ষিন-দক্ষিনপূর্ব দিকে' ;
}
else if (str == 'South')
{
return 'দক্ষিন দিকে' ;
}
else if (str == 'South-SouthWest' || str == 'South-southwest' || str == 'South-Southwest')
{
return 'দক্ষিন-দক্ষিনপশ্চিম দিকে' ;
}
else if (str == 'SouthWest' || str == 'Southwest' || str == 'southwest')
{
return 'দক্ষিন-পশ্চিম দিকে' ;
}
else if (str == 'West')
{
return 'পশ্চিম দিকে' ;
}
else if (str == 'NorthWest' || str == 'Northwest' || str == 'northwest')
{
return 'উত্তর-পশ্চিম দিকে' ;
}
else if (str == 'North-NorthWest' || str == 'North-Northwest' || str == 'North-northwest')
{
return 'উত্তর-উত্তরপশ্চিম দিকে' ;
}
else if (str == 'East-SouthEast' || str == 'East-southeast' || str == 'East-Southeast')
{
return 'পূর্ব-দক্ষিনপূর্ব দিকে' ;
}
else if (str == 'Sky is Clear' || str == 'sky is clear')
{
return 'আকাশ পরিষ্কার' ;
}
}
function showWeather()
{
var city = $('#district-list option:selected').val();
var loc = ',bd';
xmlDoc=loadXMLDoc('http://api.openweathermap.org/data/2.5/weather?q=' + city + loc + '&mode=xml');
//x1=xmlDoc.getElementsByTagName('city');
x2=xmlDoc.getElementsByTagName('temperature');
x3=xmlDoc.getElementsByTagName('humidity');
x4=xmlDoc.getElementsByTagName('weather');
x5=xmlDoc.getElementsByTagName('sun');
x6=xmlDoc.getElementsByTagName('speed');
x7=xmlDoc.getElementsByTagName('direction');
x8=xmlDoc.getElementsByTagName('pressure');
//att1=x1.item(0).attributes.getNamedItem("name");
att2=x2.item(0).attributes.getNamedItem("value");
att3=x3.item(0).attributes.getNamedItem("value");
att4=x4.item(0).attributes.getNamedItem("value");
att5=x4.item(0).attributes.getNamedItem("icon");
att6=x5.item(0).attributes.getNamedItem("rise");
att7=x5.item(0).attributes.getNamedItem("set");
att8=x6.item(0).attributes.getNamedItem("value");
att9=x7.item(0).attributes.getNamedItem("name");
att10=x2.item(0).attributes.getNamedItem("min");
att11=x2.item(0).attributes.getNamedItem("max");
att12=x8.item(0).attributes.getNamedItem("value");
//var mintemparature = (att10.value - 273.15).toPrecision(3);
//var maxtemparature = (att11.value - 273.15).toPrecision(3);
//$('.min-max').append(' ' + mintemparature + ' °C ~ ' + mintemparature + ' °C' );
//hum translate
var hum = att3.value.split('');
var x = translate(hum[0]);
var y = translate(hum[1]);
var z = translate(hum[2]);
$('.hum').empty().append('<p id="mid-text">' + x + y + z + "%" + '</p>' + '<p id="low-text">আর্দ্রতা</p>' );
//speed translate
var speed = att8.value.split('');
x = translate(speed[0]);
y = translate(speed[1]);
z = translate(speed[2]);
var m = translate(speed[4]);
$('.speed').empty().append('<p id="mid-text">' + x + y + z + m + '</p>' + '<p id="low-text">বাতাসের গতি(Mps)</p>');
//air direction
var air_dir = att9.value;
var dir = translate(air_dir);
$('.direction').empty().append('<p id="mid-text2">' + dir + '</p>' + '<p id="low-text">বাতাসের প্রবাহ</p>');
//air pressure
//air pressure translate
var air = (att12.value*0.000986923266716).toPrecision(4);
var airp = air.split('');
x = translate(airp[0]);
y = translate(airp[1]);
z = translate(airp[2]);
m = translate(airp[4]);
var n = translate(airp[5]);
$('.pressure').empty().append('<p id="mid-text">' + x + y + z + m + n + '</p>' + '<p id="low-text">বাতাসের চাপ(atm)</p>');
$('.icon-type').empty().append('<img id="ic-image" src="images/icons/' + att5.value + '.png" />');
console.log(att5.value);
$('.sky').empty().append('<p>' + att4.value + '</p>' );
//temparature translate
var temparature = (att2.value - 273.15).toPrecision(3);
var temp = temparature.split('');
x = translate(temp[0]);
y = translate(temp[1]);
z = translate(temp[2]);
m = translate(temp[3]);
$('.temp-value').empty().append(' ' + x + y + z + m + ' °সে' );
//split to eliminate date
var split1 = att6.value.split('T');
var split2 = att7.value.split('T');
//holds UTC time
var timeA = split1[1];
var timeB = split2[1];
//split to convert as locale time
var split3 = timeA.split(':');
var split4 = timeB.split(':');
//converting by substraction as absolute number
var timeC = Math.abs(split3[0]-6);
var timeD = Math.abs(split4[0]-6);
//sun-rise-set translate
var rise1 = timeC;
var rise2 = split3[1].split('');
x = translate(rise1);
y = translate(rise2[0]);
z = translate(rise2[1]);
//join the strings again
//var time1 = timeC + ':' + split3[1] ;
//var time2 = timeD + ':' + split4[1] ;
$('.rise-value').empty().append('ভোর ' + x + ':' + y + z );
var set1 = timeD;
var set2 = split4[1].split('');
x = translate(set1);
y = translate(set2[0]);
z = translate(set2[1]);
$('.set-value').empty().append('সন্ধ্যা ' + x + ':' + y + z );
} | 900317c7b77e22bb14f57d6120404deb162a4794 | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
]
| 26 | PHP | demo-Ashif/Agro-Web-Portal | 91ddd0e6da20315102ce11c7fdf569267240450e | dc19a974fa909e7881a3120fee988032f486110d |
refs/heads/main | <repo_name>armanDark/huzerangner-backend<file_sep>/AdminBroRouter.js
const AdminBro = require('admin-bro');
const AdminBroExpressjs = require('admin-bro-expressjs');
const AdminBroMongoose = require('@admin-bro/mongoose');
const AdminBroOptions = require('./AdminBroOptions');
const bcrypt = require('bcrypt');
const User = require('./models/User');
AdminBro.registerAdapter(AdminBroMongoose);
const adminBro = new AdminBro(AdminBroOptions);
const router = AdminBroExpressjs.buildAuthenticatedRouter(adminBro, {
authenticate: async (email, password) => {
const user = await User.findOne({ email });
if (user) {
// if (password === user.encryptedPassword) {
// return user;
// }
const isMatch = await bcrypt.compare(password, user.encryptedPassword);
if(isMatch === true) {
return user;
}
}
return false;
},
cookiePassword: '<PASSWORD>',
});
module.exports = router;
module.exports.adminBroInstance = adminBro; <file_sep>/controllers/posts/tags.js
const Post = require('../../models/Post');
// tags
const getTags = async (req, res) => {
const allPosts = await Post.find(
{},
{ tags: 1 }
);
// empty labels array
let tags = [];
/* for each post, check if it is already in the labels array,
if it is, increment the number of posts it's been found in, otherwise
create a new tag object in the array
*/
allPosts.forEach((post, index) => {
post.tags.forEach((tag, index) => {
if(tags.length > 0) {
let alreadyFound = false;
tags.forEach((elem, index) => {
if(elem.tag === tag) {
alreadyFound = true;
elem.postsNumber++;
}
});
if(!alreadyFound) {
tags.push({ tag: tag, postsNumber: 1 });
}
}
else tags.push({ tag: tag, postsNumber: 1 });
});
});
res.status(200).json(tags);
};
module.exports.getTags = getTags;<file_sep>/controllers/posts/postsProjection.js
module.exports = {
title: 1,
tags: 1,
createdAt: 1,
lastEdited: 1
};
<file_sep>/AdminBroOptions.js
const bcrypt = require('bcrypt');
const User = require('./models/User');
const Post = require('./models/Post');
const isAdmin = ({ currentAdmin }) => currentAdmin && currentAdmin.role === 'admin';
const contentNavigation = {
name: 'Անձնական բլոգ',
icon: 'Blog'
}
const AdminBroOptions = {
rootPath: '/admin',
branding: {
companyName: 'Հուշերանգներ | ադմինիստրատորի հարթակ',
},
resources: [
// {
// resource: User,
// options: {
// properties: {
// encryptedPassword: { isVisible: false },
// password: {
// type: 'string',
// isVisible: {
// list: false, edit: true, filter: false, show: false,
// },
// },
// },
// actions: {
// new: {
// before: async (request) => {
// if(request.payload.record.password) {
// request.payload.record = {
// ...request.payload.record,
// encryptedPassword: await bcrypt.hash(request.payload.record.password, 12),
// password: <PASSWORD>,
// }
// }
// return request
// },
// },
// edit: { isAccessible: isAdmin },
// delete: { isAccessible: isAdmin },
// new: { isAccessible: isAdmin },
// }
// }
// },
{
resource: Post,
options: {
navigation: contentNavigation,
properties: {
body: {
type: 'richtext'
},
createdAt: {
isVisible: {
list: true, new: false, edit: false, filter: true, show: true,
},
},
lastEdited: {
isVisible: {
list: true, new: false, edit: false, filter: true, show: true,
},
}
},
actions: {
edit: {
isAccessible: isAdmin,
before: async(request) => {
request.payload = {
...request.payload,
lastEdited: new Date(),
}
return request;
}
},
delete: { isAccessible: isAdmin },
new: {
isAccessible: isAdmin,
before: async(request) => {
const date = new Date();
request.payload = {
...request.payload,
createdAt: date,
lastEdited: date,
}
return request;
}
},
}
},
},
],
};
module.exports = AdminBroOptions;
<file_sep>/models/User.js
const mongoose = require('mongoose');
const User = mongoose.model('User', {
email: {
type: String,
required: true,
},
encryptedPassword: {
type: String,
required: true,
},
role: {
type: String,
enum: ['admin', 'member'],
required: true,
}
})
module.exports = User;
<file_sep>/controllers/posts/single.js
const Post = require('../../models/Post');
const postsProjection = require('./postsProjection');
/**
* returns the post given its id
* @param {string} _id
*/
const getSingle = async (_id) => {
const post = await Post.findOne({ _id });
return post;
};
/**
* returns similar posts to a given post,
* does "its best" to return exactly 5 results
* @param {string} _id
*/
const getSimilar = async (_id) => {
// the post found with the _id
const post = await Post.findOne({ _id });
/* array that contains posts with matching tags, if N tags match,
that post will appear in the array N times
*/
let results = [];
// database query for filling the array with matching tags
// ||| EXPERIMENTAL ||| needs improvement, connecting to the db N times is slow
for(let i = 0; i < post.tags.length; i++) {
const similarPosts = await Post.find(
{
tags: post.tags[i]
},
postsProjection
);
results = results.concat(similarPosts);
}
// new array for getting relevance of the match
let resultsMerged = [];
if(results.length) {
/* iterates over the the results array, and removes the repeated
results by instead increasing the result's relevance
each time it's encountered in the array
*/
results.forEach((post, index) => {
let alreadyExistsIndex = resultsMerged.findIndex((elem, index) => {
if(elem._id.equals(post._doc._id)) return true;
else return false;
});
if(alreadyExistsIndex !== -1) {
resultsMerged[alreadyExistsIndex].relevance++;
}
else {
resultsMerged.push({...post._doc, relevance: 2});
}
});
};
// if there are less than 5 results
if(resultsMerged.length < 5) {
let deficit = 5 - resultsMerged.length;
let moreResults = await Post.find(
{
$text: {
$search: post._doc.title,
$language: 'none',
$caseSensitive: false
}
},
postsProjection
).limit(deficit + 1);
moreResults = moreResults.map((elem, index) => {
return {
...elem._doc,
relevance: 1
}
});
resultsMerged = resultsMerged.concat(moreResults);
}
// if there are still less than 5 results
if(resultsMerged.length < 5) {
let randomPosts = await Post.aggregate(
[ {$sample: { size: 10 }}, {$project: postsProjection} ]
);
randomPosts = randomPosts.map((elem, index) => {
return { ...elem, relevance: 0 };
});
resultsMerged = resultsMerged.concat(randomPosts);
}
// removing the item itself from the array
resultsMerged = resultsMerged.filter((elem, index) => {
if(elem._id.equals(post._doc._id)) return false;
else return true;
});
// sort the final array by relevance
resultsMerged = resultsMerged.sort((elem1, elem2) => {
if(elem1.relevance > elem2.relevance) return -1;
else return 1;
});
// trim the array from the end if there are more than 5 results
if(resultsMerged.length > 5) {
resultsMerged = resultsMerged.slice(0, 5);
}
return resultsMerged;
};
// single post
const getPostSingle = async (req, res) => {
const {id: _id, single, similar} = req.query;
let result;
if(single) result = await getSingle(_id);
if(similar) result = await getSimilar(_id);
if(!result) res.status(404).json('Not found');
res.status(200).json(result);
};
module.exports.getPostSingle = getPostSingle;
| 26e203cc0e85a56022272d24af0ba8d45430e4c8 | [
"JavaScript"
]
| 6 | JavaScript | armanDark/huzerangner-backend | 9d1dbab1c29710cc51b8a17e23269b5e865c0e4c | 2aecb45f5f44b3c2c21614ceb943ea21326873d3 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiController extends Controller
{
//
public function index(Request $request){
$url=$request->url;
$end=explode(".",$url);
return $end[1];
}
}
<file_sep>Question 2
Function used is in moviesController@isWatchable git url https://github.com/rakoi/Challange/blob/master/app/Http/Controllers/moviesController.php
To run application run php artisan serve
URL for application https://rakoiappchallange.herokuapp.com/
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class moviesController extends Controller
{
//
public $movies = array(
['name' => 'Pulp fiction', 'length' => '180', 'id' => '1'],
['name' => 'Django Unchained ', 'length' => '120', 'id' => '2'],
['name' => 'The GodFather', 'length' => '120', 'id' => '3'],
['name' => 'Passion Of Christ', 'length' => '120', 'id' => '4'],
['name' => 'Heat', 'length' => '120', 'id' => '5'],
);
public function index()
{
$movies = $this->movies;
return view('welcome')->with('movies', $movies);
}
public function getMovieLength($id)
{
foreach ($this->movies as $movie) {
if ($movie['id'] == $id) {
return $movie['length'];
}
}
}
public function submitMovies(Request $request)
{
$movie1 = $request->movie1;
$movie2 = $request->movie2;
$lenght_of_flight = $request->minutes;
$movie_length1 = $this->getMovieLength($movie1);
$movie_length2 = $this->getMovieLength($movie2);
$movieduaration = array($movie_length1, $movie_length2);
$status = $this->isWatchable($lenght_of_flight, $movieduaration);
$response = array([
'status' => $status
]);
return $response;
}
public function isWatchable($lenght_of_flight, $movieduaration)
{
$sum_of_movies_length = 0;
for ($i = 0; $i < count($movieduaration); $i++) {
$sum_of_movies_length += $movieduaration[$i];
}
if ($sum_of_movies_length <= $lenght_of_flight) {
return true;
} else {
return false;
}
}
}
| decd4bb0543d28a0c5e6964e578bfc3a67ebde19 | [
"Markdown",
"PHP"
]
| 3 | PHP | rakoi/Challange | f02b44a0a3b95a8b1d5d8b88255c5e70ffdb4acf | cd68ea3c9b3c94d3956d737e7ee3a4f0619273af |
refs/heads/master | <repo_name>katerindlc/proyectofinal<file_sep>/controller/controllerc.php
<?php
/*
* 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.
*/
require_once '../model/ClienteModel.php';
session_start();
$clienteModel = new ClienteModel();
$op = $_REQUEST['op'];
//limpiamos cualquier mensaje previo:
unset($_SESSION['mensaj']);
switch ($op) {
case "listarC":
//obtenemos la lista de productos:
$listadoC = $clienteModel->getClientes();
//y los guardamos en sesion:
$_SESSION['listadoclis'] = serialize($listadoC);
//obtenemos el valor total de productos y guardamos en sesion:
header('Location: ../clientes.php');
break;
case "crearC":
header('Location: ../view/crearC.php');
break;
case "guardarC":
$id = $_REQUEST['id'];
$cedula = $_REQUEST['cedula'];
$nombres = $_REQUEST['nombres'];
$apellidos = $_REQUEST['apellidos'];
try {
$clienteModel->crearCliente($id, $cedula, $nombres, $apellidos);
} catch (Exception $e) {
$_SESSION['mensaj'] = $e->getMessage();
header('Location: ../clientes.php');
}
$listadoC = $clienteModel->getClientes();
$_SESSION['listadoclis'] = serialize($listadoC);
header('Location: ../clientes.php');
break;
case "eliminarC":
$id = $_REQUEST['id'];
$clienteModel->eliminarCliente($id);
$listadoC = $clienteModel->getClientes();
$_SESSION['listadoclis'] = serialize($listadoC);
header('Location: ../clientes.php');
break;
case "cargarC":
$id = $_REQUEST['id'];
$cliente = $clienteModel->getCliente($id);
$_SESSION['cliente'] = $cliente;
header('Location: ../view/actualizarC.php');
break;
case "actualizarC":
$id = $_REQUEST['id'];
$cedula = $_REQUEST['cedula'];
$nombres = $_REQUEST['nombres'];
$apellidos = $_REQUEST['apellidos'];
$clienteModel->actualizarCliente($id, $cedula, $nombres, $apellidos);
$listadoC = $clienteModel->getClientes();
$_SESSION['listadoclis'] = serialize($listadoC);
header('Location: ../clientes.php');
break;
default:header('Location: ../clientes.php');
}<file_sep>/view/actualizarF.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Actualizar Proveedor</title>
</head>
<body>
<?php
include '../model/Factura.php';
//obtenemos los datos de sesion:
session_start();
$factura = $_SESSION['factura'];
?>
<form action="../controller/controllerf.php">
<input type="hidden" value="actualizarF" name="opc">
<!-- Utilizamos pequeños scripts PHP para obtener los valores del producto: -->
<input type="hidden" value="
<?php echo $factura->getId(); ?>" name="id">
ID:<b><?php echo $factura->getId(); ?></b><br>
Nombre:<input type="text" name="nombre" value="<?php echo $factura->getNombre(); ?>"><br>
Direccion:<input type="text" name="direccion" value="<?php echo $factura->getDireccion(); ?>"><br>
Telefono:<input type="text" name="telefono" value="<?php echo $factura->getTelefono(); ?>"><br>
Email:<input type="text" name="email" value="<?php echo $factura->getEmail(); ?>"><br>
<input type="submit" value="Actualizar">
</form>
</body>
</html><file_sep>/model/ProductoModel.php
<?php
include 'Database.php';
include 'Producto.php';
/**
* Componente model para el manejo de productos.
*
* @author mrea
*/
class ProductoModel {
/**
* Obtiene todos los productos de la base de datos.
* @return array
*/
public function getValorProductos() {
$listado = $this->getProductos($orden);
$suma = 0;
foreach ($listado as $prod) {
$suma+=$prod->getPrecio() * $prod->getCantidad();
}
return $suma;
}
public function getProductos($orden) {
//obtenemos la informacion de la bdd:
$pdo = Database::connect();
//verificamos el ordenamiento asc o desc:
if ($orden == true)//asc
$sql = "select * from producto order by nombre";
else //desc
$sql = "select * from producto order by nombre desc";
$resultado = $pdo->query($sql);
//transformamos los registros en objetos de tipo Producto:
$listado = array();
foreach ($resultado as $res) {
$producto = new Producto();
$producto->setCodigo($res['codigo']);
$producto->setNombre($res['nombre']);
$producto->setPrecio($res['precio']);
$producto->setCantidad($res['cantidad']);
array_push($listado, $producto);
}
Database::disconnect();
//retornamos el listado resultante:
return $listado;
}
/**
* Obtiene un producto especifico.
* @param type $codigo El codigo del producto a buscar.
* @return \Producto
*/
public function getProducto($codigo) {
//Obtenemos la informacion del producto especifico:
$pdo = Database::connect();
//Utilizamos parametros para la consulta:
$sql = "select * from producto where codigo=?";
$consulta = $pdo->prepare($sql);
//Ejecutamos y pasamos los parametros para la consulta:
$consulta->execute(array($codigo));
//Extraemos el registro especifico:
$dato = $consulta->fetch(PDO::FETCH_ASSOC);
//Transformamos el registro obtenido a objeto:
$producto = new Producto();
$producto->setCodigo($dato['codigo']);
$producto->setNombre($dato['nombre']);
$producto->setPrecio($dato['precio']);
$producto->setCantidad($dato['cantidad']);
Database::disconnect();
return $producto;
}
public function getProduct() {
//Obtenemos la informacion del producto especifico:
$pdo = Database::connect();
//Utilizamos parametros para la consulta:
$sql = "select * from producto";
$consulta = $pdo->prepare($sql);
$produc=array();
include 'Producto.php';
//Ejecutamos y pasamos los parametros para la consulta:
foreach ($consulta as $res) {
$producto = new Producto();
$producto->setCodigo($res['codigo']);
$producto->setNombre($res['nombre']);
array_push($produc, $producto);
}
Database::disconnect();
return $producto;
}
/**
* Crea un nuevo producto en la base de datos.
* @param type $codigo
* @param type $nombre
* @param type $precio
* @param type $cantidad
*/
public function crearProducto($codigo, $nombre, $precio, $cantidad) {
//Preparamos la conexion a la bdd:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Preparamos la sentencia con parametros:
$sql = "insert into producto (codigo,nombre,precio,cantidad) values(?,?,?,?)";
$consulta = $pdo->prepare($sql);
//Ejecutamos y pasamos los parametros:
try {
$consulta->execute(array($codigo, $nombre, $precio, $cantidad));
} catch (PDOException $e) {
Database::disconnect();
throw new Exception($e->getMessage());
}
//$consulta->execute(array($codigo, $nombre, $precio, $cantidad));
Database::disconnect();
}
/**
* Elimina un producto especifico de la bdd.
* @param type $codigo
*/
public function eliminarProducto($codigo) {
//Preparamos la conexion a la bdd:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "delete from producto where codigo=?";
$consulta = $pdo->prepare($sql);
//Ejecutamos la sentencia incluyendo a los parametros:
$consulta->execute(array($codigo));
Database::disconnect();
}
/**
* Actualiza un producto existente.
* @param type $codigo
* @param type $nombre
* @param type $precio
* @param type $cantidad
*/
public function actualizarProducto($codigo, $nombre, $precio, $cantidad) {
//Preparamos la conexión a la bdd:
$pdo = Database::connect();
$sql = "update producto set nombre=?,precio=?,cantidad=? where codigo=?";
$consulta = $pdo->prepare($sql);
//Ejecutamos la sentencia incluyendo a los parametros:
$consulta->execute(array($nombre, $precio, $cantidad, $codigo));
Database::disconnect();
}
}
<file_sep>/model/ClienteModel.php
<?php
include 'Database.php';
include 'Cliente.php';
class ClienteModel {
public function getClientes() {
//obtenemos la informacion de la bdd:
$pdo = Database::connect();
$sql = "select * from clientes;";
$resultadoC = $pdo->query($sql);
//transformamos los registros en objetos de tipo Producto:
$listadoC = array();
foreach ($resultadoC as $re) {
$cliente = new Cliente();
$cliente->setId($re['id']);
$cliente->setCedula($re['cedula']);
$cliente->setNombres($re['nombres']);
$cliente->setApellidos($re['apellidos']);
array_push($listadoC, $cliente);
}
Database::disconnect();
//retornamos el listado resultante:
return $listadoC;
}
public function getCliente($id) {
//Obtenemos la informacion del producto especifico:
$pdo = Database::connect();
//Utilizamos parametros para la consulta:
$sql = "select * from clientes where id=?";
$consulta = $pdo->prepare($sql);
//Ejecutamos y pasamos los parametros para la consulta:
$consulta->execute(array($id));
//Extraemos el registro especifico:
$dato = $consulta->fetch(PDO::FETCH_ASSOC);
//Transformamos el registro obtenido a objeto:
$cliente = new Cliente();
$cliente->setId($dato['id']);
$cliente->setCedula($dato['cedula']);
$cliente->setNombres($dato['nombres']);
$cliente->setApellidos($dato['apellidos']);
Database::disconnect();
return $cliente;
}
public function crearCliente($id, $cedula, $nombres, $apellidos) {
//Preparamos la conexion a la bdd:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Preparamos la sentencia con parametros:
$sql = "insert into clientes (id, cedula, nombres, apellidos) values(?,?,?,?)";
$consulta = $pdo->prepare($sql);
//Ejecutamos y pasamos los parametros:
try {
$consulta->execute(array($id, $cedula, $nombres, $apellidos));
} catch (PDOException $e) {
Database::disconnect();
throw new Exception($e->getMessage());
}
//$consulta->execute(array($codigo, $nombre, $precio, $cantidad));
Database::disconnect();
}
/**
* Elimina un producto especifico de la bdd.
* @param type $codigo
*/
public function eliminarCliente($id) {
//Preparamos la conexion a la bdd:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "delete from clientes where id=?";
$consulta = $pdo->prepare($sql);
//Ejecutamos la sentencia incluyendo a los parametros:
$consulta->execute(array($id));
Database::disconnect();
}
public function actualizarCliente($id, $cedula, $nombres, $apellidos) {
//Preparamos la conexión a la bdd:
$pdo = Database::connect();
$sql = "update clientes set cedula=?,nombres=?,apellidos=? where id=?";
$consulta = $pdo->prepare($sql);
//Ejecutamos la sentencia incluyendo a los parametros:
$consulta->execute(array( $cedula, $nombres, $apellidos,$id));
Database::disconnect();
}
}
<file_sep>/controller/controllerf.php
<?php
require_once '../model/FacturaModel.php';
session_start();
$facturaModel = new FacturaModel();
$opc = $_REQUEST['opc'];
//limpiamos cualquier mensaje previo:
unset($_SESSION['mensaje']);
switch ($opc) {
case "listarF":
$listadof = $facturaModel->getFacturas();
$_SESSION['listadofac'] = serialize($listadof);
header('Location: ../facturas.php');
break;
case "crearF":
header('Location: ../view/crearF.php');
break;
case "guardarF":
$id = $_REQUEST['id'];
$nombre= $_REQUEST['nombre'];
$direccion= $_REQUEST['direccion'];
$telefono= $_REQUEST['telefono'];
$email= $_REQUEST['email'];
try {
$facturaModel->crearFactura($id, $nombre, $direccion,$telefono, $email);
} catch (Exception $e) {
$_SESSION['mensaje'] = $e->getMessage();
header('Location: ../facturas.php');
}
$listadof = $facturaModel->getFacturas();
$_SESSION['listadofac'] = serialize($listadof);
header('Location: ../facturas.php');
break;
case "eliminarF":
$id = $_REQUEST['id'];
$facturaModel->eliminarFactura($id);
$listadof = $facturaModel->getFacturas();
$_SESSION['listadofac'] = serialize($listadof);
header('Location: ../facturas.php');
break;
case "cargarF":
$id = $_REQUEST['id'];
$factura = $facturaModel->getFacturas();
$_SESSION['factura'] = $factura;
header('Location: ../view/actualizarF.php');
break;
case "actualizarF":
$id = $_REQUEST['id'];
$nombre = $_REQUEST['nombre'];
$direccion = $_REQUEST['direccion'];
$telefono = $_REQUEST['telefono'];
$email = $_REQUEST['email'];
$facturaModel->actualizarFactura($id, $nombre, $direccion,$telefono, $email);
$listadof = $facturaModel->getFacturas();
$_SESSION['listadofac'] = serialize($listadof);
header('Location: ../facturas.php');
break;
default:
header('Location: ../facturas.php');
}
<file_sep>/clientes.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CRUD Clientes</title>
<link rel="stylesheet" href="archivo.css">
</head>
<body>
<table width="100%" border="1">
<tr>
<td height="55" colspan="4"><table width="588" border="1" align="center">
<tr>
<td width="25%" align="center"><a href="./clientes.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>CLIENTES</b></font></div></a></td>
<td width="23%" align="center"><a href="./index.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>PRODUCTOS</b></font></div></a></td>
<td width="25%" align="center"><a href="./facturas.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>PROVEEDORES</b></font></div></a></td>
</tr>
</table></td>
</tr>
</table>
<p align="center"><b><font face="Monotype " size="6">Clientes</font></b></p>
<table align="center">
<tr>
<td>
<center><form action="controller/controllerc.php">
<input type="hidden" value="listarC" name="op">
<input type="submit" style="width: 150px; height: 60px;" value="Ver clientes">
</form></center>
</td><td>
<form action="controller/controllerc.php">
<input type="hidden" value="crearC" name="op">
<input type="submit" style="width: 150px; height: 60px;" value="Crear Cliente">
</form>
</td>
</tr>
</table>
<table border="1" align="center">
<tr bgcolor="#F0E68C" bordercolor="#FFFFFF" height="40">
<th><font color="#000">CODIGO</font></th>
<th><font color="#000">CEDULA</font></th>
<th><font color="#000">NOMBRES</font></th>
<th><font color="#000">APELLIDOS</font></th>
<th><font color="#000">ELIMINAR</font></th>
<th><font color="#000">ACTUALIZAR</font></th>
</tr>
<?php
session_start();
include './model/Cliente.php';
//verificamos si existe en sesion el listado de productos:
if (isset($_SESSION['listadoclis'])) {
$listadoC = unserialize($_SESSION['listadoclis']);
foreach ($listadoC as $pro) {
echo "<tr>";
echo "<td>" . $pro->getId() . "</td>";
echo "<td>" . $pro->getCedula() . "</td>";
echo "<td>" . $pro->getNombres() . "</td>";
echo "<td>" . $pro->getApellidos() . "</td>";
//opciones para invocar al controlador indicando la opcion eliminar o cargar
//y la fila que selecciono el usuario (con el codigo del producto):
echo "<td><a href='controller/controllerc.php?op=eliminarC&id=" . $pro->getId() . "'>eliminar</a></td>";
echo "<td><a href='controller/controllerc.php?op=cargarC&id=" . $pro->getId() . "'>actualizar</a></td>";
echo "</tr>";
}
} else {
echo "";
}
?>
</table>
</body>
</html><file_sep>/view/actualizar.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Actualizar producto</title>
<link rel="stylesheet" href="archivo.css">
</head>
<body>
<?php
include '../model/Producto.php';
//obtenemos los datos de sesion:
session_start();
$producto = $_SESSION['producto'];
?>
<form action="../controller/controller.php">
<input type="hidden" value="actualizar" name="opcion">
<!-- Utilizamos pequeños scripts PHP para obtener los valores del producto: -->
<input type="hidden" value="<?php echo $producto->getCodigo(); ?>" name="codigo">
Codigo:<b><?php echo $producto->getCodigo(); ?></b><br>
Nombre:<input type="text" name="nombre" value="<?php echo $producto->getNombre(); ?>"><br>
Precio:<input type="text" name="precio" value="<?php echo $producto->getPrecio(); ?>"><br>
Cantidad:<input type="text" name="cantidad" value="<?php echo $producto->getCantidad(); ?>"><br>
<input type="submit" value="Actualizar">
</form>
</body>
</html><file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CRUD Productos</title>
<link rel="stylesheet" href="archivo.css">
</head>
<body>
<table width="100%" border="1">
<tr>
<td height="55" colspan="4"><table width="588" border="1" align="center">
<tr>
<td width="25%" align="center"><a href="./clientes.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>CLIENTES</b></font></div></a></td>
<td width="23%" align="center"><a href="./index.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>PRODUCTOS</b></font></div></a></td>
<td width="25%" align="center"><a href="./facturas.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>PROVEEDORES</b></font></div></a></td>
</tr>
</table></td>
</tr>
</table>
<p align="center"><b><font color="BLACK" face="Monotype" size="6">Productos</font></b></p>
<table >
<tr><td>
<center> <form action="controller/controller.php">
<input type="hidden" value="listar" name="opcion">
<input type="submit" style="width: 150px; height: 60px;" value="Consultar listado">
</form></center>
</td>
<td>
<center> <form action="controller/controller.php">
<input type="hidden" value="listar_desc" name="opcion">
<input type="submit" style="width: 200px; height: 60px;" value="Consultar listado descendente">
</form></center>
</td><td>
<center> <form action="controller/controller.php">
<input type="hidden" value="crear" name="opcion">
<input type="submit" style="width: 150px; height: 60px;" value="Crear producto">
</form></center>
</td>
<td></tr>
</table>
<table>
<tr bgcolor="#F0E68C" bordercolor="#FFFFFF" height="40">
<th><font color="#000000">CODIGO</font></th>
<th><font color="#000000">NOMBRE</font></th>
<th><font color="#000000">PRECIO</font></th>
<th><font color="#000000">CANTIDAD</font></th>
<th><font color="#000000">ELIMINAR</font></th>
<th><font color="#000000">ACTUALIZAR</font></th>
</tr>
<?php
session_start();
include './model/Producto.php';
//verificamos si existe en sesion el listado de productos:
if (isset($_SESSION['listado'])) {
$listado = unserialize($_SESSION['listado']);
foreach ($listado as $prod) {
echo "<tr>";
echo "<td>" . $prod->getCodigo() . "</td>";
echo "<td>" . $prod->getNombre() . "</td>";
echo "<td>" . $prod->getPrecio() . "</td>";
echo "<td>" . $prod->getCantidad() . "</td>";
//opciones para invocar al controlador indicando la opcion eliminar o cargar
//y la fila que selecciono el usuario (con el codigo del producto):
echo "<td><a href='controller/controller.php?opcion=eliminar&codigo=" . $prod->getCodigo() . "'>eliminar</a></td>";
echo "<td><a href='controller/controller.php?opcion=cargar&codigo=" . $prod->getCodigo() . "'>actualizar</a></td>";
echo "</tr>";
}
} else {
echo "";
}
?>
</table>
<div align="center">
<font color="#FF0000">
<?php
if (isset($_SESSION['valorTotal'])) {
echo "VALOR TOTAL DE PRODUCTOS: <b>" . $_SESSION['valorTotal'] . "</b>";
}
?>
</font>
</div>
</body>
</html><file_sep>/model/conexion.php
<?php
//$conn = pg_connect("host=localhost port=5432 dbname=productos user=postgres password=<PASSWORD>");
$conn = pg_connect("host=ec2-54-204-36-249.compute-1.amazonaws.com port=5432 dbname=d22eokasrcc2a4 user=fwrgdmkgnuxwuv password=<PASSWORD>");
?><file_sep>/model/Factura.php
<?php
/**
* Entidad Producto. Representa a la tabla producto en la base de datos.
*
* @author curso
*/
class Factura {
private $id,$nombre,$direccion,$telefono,$email;
function getId() {
return $this->id;
}
function getNombre() {
return $this->nombre;
}
function getDireccion() {
return $this->direccion;
}
function getTelefono() {
return $this->telefono;
}
function getEmail() {
return $this->email;
}
function setId($id) {
$this->id = $id;
}
function setNombre($nombre) {
$this->nombre = $nombre;
}
function setDireccion($direccion) {
$this->direccion = $direccion;
}
function setTelefono($telefono) {
$this->telefono = $telefono;
}
function setEmail($email) {
$this->email = $email;
}
}<file_sep>/model/FacturaModel.php
<?php
include 'Database.php';
include 'Factura.php';
/**
* Componente model para el manejo de productos.
*
* @author mrea
*/
class FacturaModel {
public function getFacturas() {
//obtenemos la informacion de la bdd:
$pdo = Database::connect();
$sql = "select * from proveedor;";
$resultad = $pdo->query($sql);
$listadof = array();
foreach ($resultad as $res) {
$factura = new Factura();
$factura->setId($res['id']);
$factura->setNombre($res['nombre']);
$factura->setDireccion($res['direccion']);
$factura->setTelefono($res['telefono']);
$factura->setEmail($res['email']);
array_push($listadof, $factura);
}
Database::disconnect();
//retornamos el listado resultante:
return $listadof;
}
public function actualizarFactura($id, $nombre, $direccion,$telefono, $email) {
//Preparamos la conexión a la bdd:
$pdo = Database::connect();
$sql = "update proveedor set nombre=?,direccion=?,telefono=?,email=? where id=?;";
$consulta = $pdo->prepare($sql);
//Ejecutamos la sentencia incluyendo a los parametros:
$consulta->execute(array($nombre, $direccion,$telefono, $email,$id));
Database::disconnect();
}
public function crearFactura($id, $nombre, $direccion,$telefono, $email) {
//Preparamos la conexion a la bdd:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "insert into proveedor (id,nombre,direccion,telefono,email) values(?,?,?,?,?)";
$consulta = $pdo->prepare($sql);
try {
$consulta->execute(array($id, $nombre, $direccion,$telefono, $email) );
} catch (PDOException $e) {
Database::disconnect();
throw new Exception($e->getMessage());
}
Database::disconnect();
}
public function eliminarFactura($id) {
//Preparamos la conexion a la bdd:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "delete from proveedor where id=?";
$consulta = $pdo->prepare($sql);
//Ejecutamos la sentencia incluyendo a los parametros:
$consulta->execute(array($id));
Database::disconnect();
}
}
<file_sep>/view/actualizarC.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Actualizar Cliente</title>
<link rel="stylesheet" href="archivo.css">
</head>
<body>
<?php
include '../model/Cliente.php';
//obtenemos los datos de sesion:
session_start();
$cliente = $_SESSION['cliente'];
?>
<form action="../controller/controllerc.php">
<input type="hidden" value="actualizarC" name="op">
<!-- Utilizamos pequeños scripts PHP para obtener los valores del producto: -->
<input type="hidden" value="
<?php echo $cliente->getId(); ?>" name="id">
Id:<b><?php echo $cliente->getId(); ?></b><br>
Cedula:<input type="text" name="cedula" value="<?php echo $cliente->getCedula(); ?>"><br>
Nombres:<input type="text" name="nombres" value="<?php echo $cliente->getNombres(); ?>"><br>
Apellidos:<input type="text" name="apellidos" value="<?php echo $cliente->getApellidos(); ?>"><br>
<input type="submit" value="Actualizar">
</form>
</body>
</html><file_sep>/controller/controller.php
<?php
require_once '../model/ProductoModel.php';
session_start();
$productoModel = new ProductoModel();
$opcion = $_REQUEST['opcion'];
//limpiamos cualquier mensaje previo:
unset($_SESSION['mensaje']);
switch ($opcion) {
case "listar":
//obtenemos la lista de productos:
$listado = $productoModel->getProductos($orden);
//y los guardamos en sesion:
$_SESSION['listado'] = serialize($listado);
//obtenemos el valor total de productos y guardamos en sesion:
$_SESSION['valorTotal'] = $productoModel->getValorProductos();
header('Location: ../index.php');
break;
case "listar_desc":
//obtenemos la lista de productos:
$listado = $productoModel->getProductos($orden);
//y los guardamos en sesion:
$_SESSION['listado'] = serialize($listado);
//obtenemos el valor total de productos:
$_SESSION['valorTotal'] = $productoModel->getValorProductos();
header('Location: ../index.php');
break;
case "crear":
//navegamos a la pagina de creacion:
header('Location: ../view/crear.php');
break;
case "guardar":
//obtenemos los valores ingresados por el usuario en el formulario:
$codigo = $_REQUEST['codigo'];
$nombre = $_REQUEST['nombre'];
$precio = $_REQUEST['precio'];
$cantidad = $_REQUEST['cantidad'];
//creamos un nuevo producto:
try {
$productoModel->crearProducto($codigo, $nombre, $precio, $cantidad);
} catch (Exception $e) {
//colocamos el mensaje de la excepcion en sesion:
$_SESSION['mensaje'] = $e->getMessage();
header('Location: ../index.php');
}
// $productoModel->crearProducto($codigo, $nombre, $precio, $cantidad);
//actualizamos la lista de productos para grabar en sesion:
$listado = $productoModel->getProductos(true);
$_SESSION['listado'] = serialize($listado);
header('Location: ../index.php');
break;
case "eliminar":
//obtenemos el codigo del producto a eliminar:
$codigo = $_REQUEST['codigo'];
//eliminamos el producto:
$productoModel->eliminarProducto($codigo);
//actualizamos la lista de productos para grabar en sesion:
$listado = $productoModel->getProductos(true);
$_SESSION['listado'] = serialize($listado);
header('Location: ../index.php');
break;
case "cargar":
//para permitirle actualizar un producto al usuario primero
//obtenemos los datos completos de ese producto:
$codigo = $_REQUEST['codigo'];
$producto = $productoModel->getProducto($codigo);
//guardamos en sesion el producto para posteriormente visualizarlo
//en un formulario para permitirle al usuario editar los valores:
$_SESSION['producto'] = $producto;
header('Location: ../view/actualizar.php');
break;
case "actualizar":
//obtenemos los datos modificados por el usuario:
$codigo = $_REQUEST['codigo'];
$nombre = $_REQUEST['nombre'];
$precio = $_REQUEST['precio'];
$cantidad = $_REQUEST['cantidad'];
//actualizamos los datos del producto:
$productoModel->actualizarProducto($codigo, $nombre, $precio, $cantidad);
//actualizamos la lista de productos para grabar en sesion:
$listado = $productoModel->getProductos();
$_SESSION['listado'] = serialize($listado);
header('Location: ../index.php');
break;
default:
//si no existe la opcion recibida por el controlador, siempre
//redirigimos la navegacion a la pagina index:
header('Location: ../index.php');
}
// ---------------------FACTURAS--------------------------<file_sep>/facturas.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CRUD Productos</title>
<link rel="stylesheet" href="archivo.css">
</head>
<body>
<table width="100%" border="1">
<tr>
<td height="55" colspan="4"><table width="588" border="1" align="center">
<tr>
<td width="25%" align="center"><a href="./clientes.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>CLIENTES</b></font></div></a></td>
<td width="23%" align="center"><a href="./index.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>PRODUCTOS</b></font></div></a></td>
<td width="25%" align="center"><a href="./facturas.php" target="cuerpoby"><div style="width: 100%; height: 50px; margin-top: 20px" ><font color="#000000"><b>PROVEEDORES</b></font></div></a></td>
</tr>
</table></td>
</tr>
</table>
<p align="center"><b><font face="Monotype " size="6">Proveedores</font></b></p>
<table align="center">
<tr><td>
<center> <form action="controller/controllerf.php">
<input type="hidden" value="listarF" name="opc">
<input type="submit" style="width: 150px; height: 60px;" value="Ver listado">
</form></center>
</td>
<td>
<form action="controller/controllerf.php">
<input type="hidden" value="crearF" name="opc">
<input type="submit" style="width: 150px; height: 60px;" value="Crear Nuevo">
</form>
</td></tr>
</table>
<table border="1" align="center">
<tr bgcolor="#F0E68C" bordercolor="#FFFFFF" height="40">
<th><font color="#000000">ID</font></th>
<th><font color="#000000">NOMBRE</font></th>
<th><font color="#000000">DIRECCION</font></th>
<th><font color="#000000">TELEFONO</font></th>
<th><font color="#000000">EMAIL</font></th>
<th><font color="#000000">ELIMINAR</font></th>
<th><font color="#000000">ACTUALIZAR</font></th>
</tr>
<?php
session_start();
include './model/Factura.php';
//verificamos si existe en sesion el listado de productos:
if (isset($_SESSION['listadofac'])) {
$listadof = unserialize($_SESSION['listadofac']);
foreach ($listadof as $p) {
echo "<tr>";
echo "<td>" . $p->getId() . "</td>";
echo "<td>" . $p->getNombre() . "</td>";
echo "<td>" . $p->getDireccion() . "</td>";
echo "<td>" . $p->getTelefono() . "</td>";
echo "<td>" . $p->getEmail() . "</td>";
echo "<td><a href='controller/controllerf.php?opc=eliminarF&id=" . $p->getId() . "'>eliminar</a></td>";
echo "<td><a href='controller/controllerf.php?opc=actualizarF&id=" . $p->getId() . "'>actualizar</a></td>";
echo "</tr>";
}
} else {
echo " ";
}
?>
</table>
</font>
</body>
</html> | 272fecc515507b1520eac9d5e417672d3ae60c3b | [
"PHP"
]
| 14 | PHP | katerindlc/proyectofinal | 865182ab8a23e385f0923e1c4458d51a47e07883 | dce63a2d5689df00999dba57d52f8942911ec582 |
refs/heads/master | <repo_name>JGuissart/Js-Games<file_sep>/Nouveau dossier/Pendu.js
/**
* Created by Julien on 27/05/2015.
*/
var mot = new Array();
mot[0] = "coucou";
mot[1] = "Yoloo";
mot[2] = "Bonjour";
var random = Math.floor(Math.random() * mot.length);
var motATrouver = mot[random];
var motTrouve = "";
for(i=0;i<motATrouver.length;i++)
{
document.getElementById("mot1").innerHTML += "<td id=lettre"+i+">_</td>";
}
document.getElementById('btnValiderLettre').addEventListener('click', verifLettre, false);
function verifLettre()
{
var maLettre = document.getElementById('txtLettre').value;
if(maLettre.length > 1 ||!(/[A-Z]|[a-z]/.test(maLettre)))
alert("T'as fait de la merde petit con.");
else
{
document.getElementById('txtLettre').value = "";
for (i = 0; i < motATrouver.length; i++)
{
if(motATrouver[i] == maLettre)
{
document.getElementById("lettre"+i).innerHTML = maLettre;
}
}
}
}<file_sep>/Calculus.js
/**
* Created by Julien on 31/05/2015.
*/
/* Variables */
var EnfantConnecte;
var reponse;
var nbreAllies = 10;
var nbreAdversaires = 10;
window.addEventListener('load', initEventHandlers, false);
function initEventHandlers()
{
var url = document.URL;
var tabUrl = url.split("=");
recuperation(tabUrl[1]);
document.getElementById('btnValiderReponse').addEventListener('click', function() { reponse = verificationReponse() }, false);
document.getElementById('cbxNiveau').addEventListener('change', function() { reponse = genererCalcul(true) }, false);
reponse = genererCalcul(true);
}
function recuperation(Prenom)
{
var monEnfantJSON = localStorage.getItem(Prenom);
EnfantConnecte = JSON.parse(monEnfantJSON);
}
/**
* La fonction va vérifier si la réponse entrée par l'enfant est correcte ou non
* @returns La réponse au calcul généré.
*/
function verificationReponse()
{
var valeurInput = document.getElementById('txtReponse').value;
if(isNaN(valeurInput))
{
alert(valeurInput + " n'est pas un chiffre");
return;
}
else if(valeurInput == reponse) // On élimine un adversaire
{
nbreAdversaires--;
remplirCanvas(false);
if(nbreAdversaires == 0)
{
ecrireGagner();
//alert('Super ! Tu as gagné ' + document.getElementById('cbxNiveau').value + ' jetons !');
EnfantConnecte.NombrePiece += parseInt(document.getElementById('cbxNiveau').value);
sauvegardeEnfantConnecte();
return;
}
}
else // On élimine un allié
{
nbreAllies--;
remplirCanvas(false);
if(nbreAllies == 0)
{
ecrirePerdu();
return;
}
}
return genererCalcul(false);
}
/**
* La fonction va écrire le mot "Gagner" dans le canvas
*/
function ecrireGagner()
{
var cnvAdverse = document.getElementById('cnvMechants');
cnvAdverse.style.backgroundColor = "#F3F4F6";
var ctxAdverse = cnvAdverse.getContext('2d');
ctxAdverse.fillStyle = "#005B12";
ctxAdverse.font = "150px monospace";
ctxAdverse.fillText('Gagné', 200, 150);
document.getElementById('btnValiderReponse').disabled = true;
}
/**
* La fonction va écrire le mot "Perdu" dans le canvas
*/
function ecrirePerdu()
{
var cnvAllie = document.getElementById('cnvGentils');
cnvAllie.style.backgroundColor = "#F3F4F6";
var ctxAllie = cnvAllie.getContext('2d');
ctxAllie.fillStyle = "#F00000";
ctxAllie.font = "150px monospace";
ctxAllie.fillText('Perdu', 200, 150);
document.getElementById('btnValiderReponse').disabled = true;
}
/**
* La fonction va remplir les canvas avec les images des casques à pointe.
* @param nouvellePartie Permet de savoir si on démarre une nouvelle partie en remettant le nombre de soldat à 10
*/
function remplirCanvas(nouvellePartie)
{
if(nouvellePartie == true)
{
nbreAdversaires = 10;
nbreAllies = 10;
}
var cnvAllie = document.getElementById('cnvGentils');
cnvAllie.style.backgroundColor = "#F3F4F6";
var ctxAllie = cnvAllie.getContext('2d');
ctxAllie.clearRect(0, 0, cnvAllie.width, cnvAllie.height);
var soldatAllie = new Image();
soldatAllie.src = "SoldatAllié.png";
soldatAllie.onload = function() {
for (i = 0; i < nbreAllies; i++)
ctxAllie.drawImage(soldatAllie, soldatAllie.width * i, 0);
}
var cnvAdverse = document.getElementById('cnvMechants');
cnvAdverse.style.backgroundColor = "#F3F4F6";
var ctxAdverse = cnvAdverse.getContext('2d');
ctxAdverse.clearRect(0, 0, cnvAdverse.width, cnvAdverse.height);
var soldatAdverse = new Image();
soldatAdverse.src = "SoldatAdverse.png";
soldatAdverse.onload = function() {
for(i = 0; i < nbreAdversaires; i++)
ctxAdverse.drawImage(soldatAdverse, soldatAdverse.width * i, 0);
}
}
function genererCalcul(nouvellePartie)
{
document.getElementById('btnValiderReponse').disabled = false;
if(nouvellePartie == true)
remplirCanvas(nouvellePartie);
document.getElementById('txtReponse').value = "";
var u1, u2, reponse;
switch(document.getElementById('cbxNiveau').value)
{
case '1':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
}
while(u1 + u2 > 10);
reponse = u1 + u2;
document.getElementById('lblCalcul').innerHTML = u1 + "+" + u2;
break;
case '2':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
}
while(u1 + u2 < 10);
reponse = u1 + u2;
document.getElementById('lblCalcul').innerHTML = u1 + "+" + u2;
break;
case '3':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
}
while(u1 + u2 < 0);
reponse = u1 - u2;
document.getElementById('lblCalcul').innerHTML = u1 + "-" + u2;
break;
case '4':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
d1 = Math.floor((Math.random() * 9) + 1);
}
while(u1 + u2 >= 10);
reponse = u1 + ((d1 * 10) + u2);
document.getElementById('lblCalcul').innerHTML = u1 + "+" + ((d1 * 10) + u2);
break;
case '5':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
d1 = Math.floor((Math.random() * 9) + 1);
d2 = Math.floor((Math.random() * 9) + 1);
}
while(u1 + u2 >= 10);
reponse = ((d1 * 10) + u1) + ((d2 * 10) + u2);
document.getElementById('lblCalcul').innerHTML = ((d1 * 10) + u1) + "+" + ((d2 * 10) + u2);
break;
case '6':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
d1 = Math.floor((Math.random() * 9) + 1);
d2 = Math.floor((Math.random() * 9) + 1);
}
while(u1 + u2 <= 10);
reponse = ((d1 * 10) + u1) + (( d2 * 10) + u2);
document.getElementById('lblCalcul').innerHTML = ((d1 * 10) + u1) + "+" + ((d2 * 10) + u2);
break;
case '7':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
d1 = Math.floor((Math.random() * 9) + 1);
}
while(u1 - u2 < 0);
reponse = (((d1 * 10) + u1) - u2);
document.getElementById('lblCalcul').innerHTML = ((d1 * 10) + u1) + "-" + u2;
break;
case '8':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
d1 = Math.floor((Math.random() * 9) + 1);
}
while(u1 - u2 >= 0);
reponse = (((d1 * 10) + u1) - u2);
document.getElementById('lblCalcul').innerHTML = ((d1 * 10) + u1) + "-" + u2;
break;
case '9':
do
{
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
d1 = Math.floor((Math.random() * 9) + 1);
d2 = Math.floor((Math.random() * 9) + 1);
}
while(u1-u2 < 0);
reponse = (((d1 * 10) + u1) - ((d2 * 10) + u2));
document.getElementById('lblCalcul').innerHTML = ((d1 * 10) + u1) + "-" + ((d2 * 10) + u2);
break;
case '10':
u1 = Math.floor((Math.random() * 9) + 0);
u2 = Math.floor((Math.random() * 9) + 0);
d1 = Math.floor((Math.random() * 9) + 1);
d2 = Math.floor((Math.random() * 9) + 1);
reponse = (((d1 * 10) + u1) - ((d2 * 10) + u2));
document.getElementById('lblCalcul').innerHTML = ((d1 * 10) + u1) + "-" + ((d2 * 10) + u2);
break;
}
return reponse;
}
function sauvegardeEnfantConnecte()
{
var monObjetJSON = JSON.stringify(EnfantConnecte);
localStorage.setItem(EnfantConnecte.Prenom, monObjetJSON);
document.getElementById('Jetons').innerHTML = "Jetons : " + EnfantConnecte.NombrePiece;
}<file_sep>/Connexion.js
/**
* Created by Julien on 9/05/2015.
*/
window.addEventListener('load', initEventHandlers, false);
function initEventHandlers()
{
document.getElementById('btnConnexion').addEventListener('click', verification, false);
}
function verification()
{
//alert("Je démarre verification");
var prenom = document.getElementById('txtPrenom').value;
if (localStorage.getItem(prenom) == null) // Si le prénom n'existe pas dans le localStorage, on redirige vers la page d'inscription
document.location.href = "Inscription.html?Prenom=" + prenom;
else // Sinon, on récupère les infos de l'enfant
document.location.href = "Jeux.html?Prenom=" + prenom;
//alert("Je termine verification");
}<file_sep>/Enfant.js
/**
* Created by Julien on 21/04/2015.
*/
var Enfant = function(p, s, a, nbPiece, bestPong) {
this.Prenom = p;
this.Sexe = s;
this.Avatar = a;
this.NombrePiece = nbPiece;
this.BestPong = bestPong;
};
/* Setters */
Enfant.prototype.getPrenom = function() {
return this.Prenom;
};
Enfant.prototype.getSexe = function() {
return this.Sexe;
};
Enfant.prototype.getAvatar = function() {
return this.Avatar;
};
Enfant.prototype.getNombrePiece = function() {
return this.NombrePiece;
};
Enfant.prototype.getBestPong = function() {
return this.BestPong;
}
/* Setters */
Enfant.prototype.setPrenom = function(prenom) {
this.Prenom = prenom;
};
Enfant.prototype.setSexe = function(sexe) {
this.Sexe = sexe;
};
Enfant.prototype.setAvatar = function(avatar) {
this.Avatar = avatar;
};
Enfant.prototype.setNombrePiece = function(nb) {
this.NombrePiece = nb;
};
Enfant.prototype.setBestPong = function(bestPong) {
this.BestPong = bestPong;
}<file_sep>/Pongulus.js
/**
* Created by Julien on 27/05/2015.
*/
var EnfantConnecte;
var nbreParties = 5;
window.addEventListener('load', initEventHandlers, false);
function initEventHandlers()
{
var url = document.URL;
var tabUrl = url.split("=");
recuperation(tabUrl[1]);
}
function recuperation(Prenom)
{
var monEnfantJSON = localStorage.getItem(Prenom);
EnfantConnecte = JSON.parse(monEnfantJSON);
if(EnfantConnecte.NombrePiece < 3)
{
alert('Il te faut au moins 3 pièces pour jouer au Pong.');
nbreParties = 0;
location.href = 'Jeux.html?Prenom=' + EnfantConnecte.Prenom;
}
else
{
EnfantConnecte.NombrePiece -= 3;
sauvegardeEnfantConnecte();
nbreParties = 5;
}
}
var canvas = document.getElementById('cnvPong');
var context = canvas.getContext('2d');
context.fillStyle = "#FFF";
context.font = "60px monospace";
var Pause = 1;
var DebutPartie = 1;
var VitesseBarreGauche = 0;
var VitesseBarreDroite = 0;
var Score = 0;
var BarreGauche = 190;
var BarreDroite = 190;
var BallX = 300;
var BallY = 235;
var VitesseBallX = -5;
var VitesseBallY = 3;
function Pong()
{
if(nbreParties != 0)
{
if (Pause && !DebutPartie)
return;
DebutPartie = 0;
context.clearRect(0, 0, canvas.width, canvas.height);
BarreGauche += VitesseBarreGauche;
BarreDroite += VitesseBarreDroite;
// Délimitation de la barre gauche en fonction de l'axe des y
BarreGauche = BarreGauche < 0 ? 0 : BarreGauche;
BarreGauche = BarreGauche > 380 ? 380 : BarreGauche;
// Délimitation de la barre droite en fonction de l'axe des y
BarreDroite = BarreDroite < 0 ? 0 : BarreDroite;
BarreDroite = BarreDroite > 380 ? 380 : BarreDroite;
// Lance la balle
BallX += VitesseBallX;
BallY += VitesseBallY;
if (BallY <= 0) // Rebond supérieur
{
BallY = 0;
VitesseBallY = -VitesseBallY;
}
if (BallY >= 470) // rebond inférieur
{
BallY = 470;
VitesseBallY = -VitesseBallY;
}
/*
* BallX <= 40 && BallX >= 20 ==> Permet de vérifier si la balle se trouve entre les 2 'x' de la barre
*
* BallY < BarreGauche + 110 && BallY > BarreGauche - 10 ==> Permet de vérifier si la balle se trouve """entre""" les 2 'y' de la barre
* (10 de différences car taille de la balle = 10)
* */
if (BallX <= 40 && BallX >= 20 && BallY < BarreGauche + 110 && BallY > BarreGauche - 10)
{
Score++;
VitesseBallX = -VitesseBallX + 0.4; // Ricochet vers la droite
}
if (BallX <= 610 && BallX >= 590 && BallY < BarreDroite + 110 && BallY > BarreDroite - 10)
{
Score++;
VitesseBallX = -VitesseBallX - 0.4; // Ricochet vers la gauche
}
if (BallX < 0) // Si la balle ne ricoche pas contre la barre gauche
{
BallX = 360;
BallY = 235;
VitesseBallX = 5; // La barre de droite "lance" la balle
Pause = 1;
}
if (BallX > 640) // Si la balle ne ricoche pas contre la barre droite
{
BallX = 280;
BallY = 235;
VitesseBallX = -5; // La barre de gauche "lance" la balle
Pause = 1;
}
if (Pause == 1)
{
if (Score > EnfantConnecte.BestPong)
{
alert('Tu as battu ton meilleur score !');
EnfantConnecte.BestPong = Score;
sauvegardeEnfantConnecte();
}
Score = 0;
nbreParties--;
}
context.fillText(Score, 300, 60); // On écrit le score
context.fillRect(20, BarreGauche, 20, 100); // On dessine la barre de gauche
context.fillRect(600, BarreDroite, 20, 100); // On dessine la barre de droite
context.fillRect(BallX, BallY, 10, 10); // On dessine la boule
}
else
{
alert('Tu as joué tes 5 parties. Si tu souhaites recommencer, clique à nouveau sur le bouton "Pong" un peu plus haut !');
clearInterval(refreshIntervalId);
return;
}
}
var refreshIntervalId = setInterval(Pong, 30);
document.onkeydown = function(e) {
e.preventDefault();
k = e.keyCode;
Pause = Pause ? 0 : k == '27' ? 1 : 0;
VitesseBarreGauche = VitesseBarreDroite = k == '40' ? 5 : k == '38' ? - 5 : VitesseBarreDroite;
}
document.onkeyup = function(e) {
e.preventDefault();
k = e.keyCode;
VitesseBarreGauche = VitesseBarreDroite = k == '38' || k == '40' ? 0 : VitesseBarreDroite;
}
function sauvegardeEnfantConnecte()
{
var monObjetJSON = JSON.stringify(EnfantConnecte);
localStorage.setItem(EnfantConnecte.Prenom, monObjetJSON);
document.getElementById('Jetons').innerHTML = "Jetons : " + EnfantConnecte.NombrePiece;
document.getElementById('Points').innerHTML = "Meilleur score Pong : " + EnfantConnecte.BestPong;
}<file_sep>/Pendulus.js
/**
* Created by Julien on 27/05/2015.
*/
var tabMots = [
"agneau", "aider", "ail",
"aimer", "amie", "ampoule",
"angle", "animal", "appareil",
"araignée", "arrière", "auto",
"avec", "avril", "balance",
"balançoire", "baleine", "banc",
"bateau", "beau", "bec",
"berceau", "bizarre", "blague",
"blanc", "bleu", "blouse",
"bosse", "bouteille", "brouillard",
"bureau", "bébé", "c'est",
"cadeau", "cahier", "caisse",
"calendrier", "camarade", "campagne",
"canaille", "casquette", "cave",
"ceinture", "cercle", "cercueil",
"cerise", "cerise", "chagrin",
"chambre", "champignon", "chandail",
"chante", "chapeau", "Charlène",
"chatouille", "chaud", "chaud",
"chemin", "chemin", "cheminée",
"chemise", "cher", "cher",
"cheveu", "chevreuil", "chez",
"chose", "chère", "ciel",
"cigogne", "cinq", "cinq",
"cinéma", "citron", "citrouille",
"clair", "classe", "classe",
"clé", "collier", "consigne",
"copain", "copie", "copier",
"corbeille", "cousin", "coussin",
"coussin", "couteau", "cravate",
"croissant", "crème", "cuiller",
"cuisinier", "dame", "dans",
"demain", "dernier", "dernier",
"derrière", "dessert", "dessin",
"dessin", "deux", "diable",
"dictée", "difficile", "dimanche",
"dire", "dormir", "douze",
"décembre", "déjà", "désert",
"détail", "eau", "encore",
"enfant", "enfin", "ensemble",
"entend", "escargot", "facile",
"faire", "famille", "farce",
"faute", "fauteuil", "façade",
"femme", "fenouil", "fer",
"fermier", "feu", "feuillage",
"feuille", "feuilleton", "figure",
"figure", "file", "fille",
"fin", "fiole", "flan",
"fleur", "fleur", "fleur",
"flocon", "foire", "forme",
"formule", "fou", "frisson",
"frère", "fée", "fête",
"gagner", "garage", "garde",
"gare", "garçon", "garçon",
"gauche", "genou", "gentil",
"gentil", "gilet", "glace",
"glace", "gland", "glaçon",
"gomme", "gorge", "goutte",
"grand", "grand", "mère",
"grenadine", "grenouille", "groseille",
"grue", "guirlande", "gâteau",
"haut", "herbe", "heure",
"heureux", "hier", "hiver",
"image", "impossible", "industrie",
"insecte", "jamais", "janvier",
"jaune", "jaune", "jeu",
"jeudi", "joli", "jolie",
"Joshua", "jouet", "jour",
"laid", "laine", "lait",
"lampe", "langue", "langue",
"lapin", "lapin", "lecture",
"leçon", "ligne", "limace",
"lire", "livre", "lumière",
"lune", "lutin", "machine",
"magasin", "magasin", "magie",
"mai", "maille", "maillot",
"main", "maintenant", "mais",
"maison", "malade", "maman",
"manger", "mardi", "matin",
"mer", "merci", "mercredi",
"merle", "merle", "merveille",
"minute", "montagne", "moulin",
"mousse", "mur", "musique",
"musique", "mère", "mètre",
"médecin", "neige", "neuf",
"nouilles", "novembre", "nuage",
"oeuf", "oeuf", "offrir",
"oignon", "onze", "orage",
"orange", "oreille", "pain",
"panier", "panier", "parents",
"patins", "peinture", "peluche",
"perle", "peu", "peur",
"phoque", "photo", "piano",
"pie", "pièce", "plage",
"plaisir", "plaisir", "plan",
"plein", "pleurer", "plier",
"pluie", "plume", "pneu",
"poisson", "pommier", "pompier",
"portefeuille", "poussin", "premier",
"printemps", "prochain", "pâtissier",
"père", "quatorze", "quinze",
"quinze", "radio", "raisin",
"raisin", "ratatouille", "rectangle",
"reine", "relier", "rentrer",
"rentrée", "reste", "reçu",
"rivière", "rose", "règle",
"règle", "réunion", "réveil",
"sable", "sac", "sage",
"samedi", "sapin", "sapin",
"saute", "seau", "sec",
"seize", "semaine", "semaine",
"sept", "septembre", "serpent",
"service", "serviette", "seuil",
"signal", "signe", "singe",
"six", "soigner", "soleil",
"sommeil", "sorcier", "sorcière",
"souffler", "souligner", "souvent",
"spécial", "tableau", "taille",
"tasse", "taupe", "temps",
"température", "tempête", "terre",
"timbre", "toujours", "travail",
"treize", "triangle", "vague",
"valise", "veille", "vendredi",
"vent", "ver", "verre",
"vert", "veste", "vieux",
"vigne", "vingt", "vingt",
"vélo", "yeux", "zéro",
"école", "écureuil", "élève",
"éléphant", "émail", "éponge",
"grand-père", "étoile"
];
var EnfantConnecte;
window.addEventListener('load', initEventHandlers, false);
function initEventHandlers()
{
document.getElementById('cnvPendu').style.backgroundColor = "#999";
for(i = 0; i < motCache.length; i++)
document.getElementById("mot1").innerHTML += "<td id=lettre"+i+">_</td>";
document.getElementById('btnValiderLettre').addEventListener('click', verifLettre, false);
var url = document.URL;
var tabUrl = url.split("=");
recuperation(tabUrl[1]);
}
function recuperation(Prenom)
{
var monEnfantJSON = localStorage.getItem(Prenom);
EnfantConnecte = JSON.parse(monEnfantJSON);
}
function sauvegardeEnfantConnecte()
{
var monObjetJSON = JSON.stringify(EnfantConnecte);
localStorage.setItem(EnfantConnecte.Prenom, monObjetJSON);
document.getElementById('Jetons').innerHTML = "Jetons : " + EnfantConnecte.NombrePiece;
}
var random = Math.floor(Math.random() * tabMots.length);
var motCache = tabMots[random];
var trouve = 0;
var nbreEssaisPerdus = 0;
var lettresEntrees = "";
function verifLettre()
{
var maLettre = document.getElementById('txtLettre').value;
if(maLettre.length > 1)
alert("Il faut entrer une seule lettre à la fois.");
else if(!(/[A-Z]|[a-z]|[é]|[è]|[à]|[]/.test(maLettre)))
alert("La lettre entrée est invalide.");
else if(lettresEntrees.indexOf(maLettre) > -1)
alert("La lettre a déjà été essayée.");
else
{
trouve = 0;
document.getElementById('txtLettre').value = "";
for (i = 0; i < motCache.length; i++)
{
if(motCache[i] == maLettre)
{
document.getElementById("lettre" + i).innerHTML = maLettre;
trouve = 1;
}
}
if(trouve == 0)
{
nbreEssaisPerdus++;
lettresEntrees += " " + maLettre;
document.getElementById('lblLettresTentees').innerHTML = lettresEntrees;
dessinerBonhomme();
}
else
{
var cpt = 0;
for(i = 0; i < motCache.length; i++)
if(document.getElementById("lettre" + i).innerHTML == motCache[i])
cpt++;
if(cpt == motCache.length)
{
var canvas = document.getElementById('cnvPendu');
var ctx = canvas.getContext('2d');
ctx.fillStyle = "#005B12";
ctx.font = "150px monospace";
ctx.fillText("Gagné", 0, canvas.height / 2, canvas.width);
EnfantConnecte.NombrePiece += 3;
sauvegardeEnfantConnecte();
}
}
}
}
function dessinerBonhomme()
{
var canvas = document.getElementById('cnvPendu');
var ctx = canvas.getContext('2d');
switch (nbreEssaisPerdus)
{
case 1:
ctx.beginPath();
ctx.moveTo(50, 42);
ctx.lineTo(50, 450);
ctx.stroke();
break;
case 2:
ctx.beginPath();
ctx.moveTo(50, 42);
ctx.lineTo(200, 42);
ctx.stroke();
break;
case 3:
ctx.beginPath();
ctx.moveTo(50, 90);
ctx.lineTo(100, 42);
ctx.stroke();
break;
case 4:
ctx.beginPath();
ctx.moveTo(200, 42);
ctx.lineTo(200, 85);
ctx.stroke();
break;
case 5:
ctx.beginPath();
ctx.arc(200, 115, 30, 0, Math.PI * 2);
ctx.moveTo(180, 105);
ctx.lineTo(190, 105);
ctx.moveTo(185, 100);
ctx.lineTo(185, 110);
ctx.moveTo(220, 105);
ctx.lineTo(210, 105);
ctx.moveTo(215, 100);
ctx.lineTo(215, 110);
ctx.moveTo(185, 125);
ctx.lineTo(215, 125);
ctx.moveTo(195, 125);
ctx.bezierCurveTo(195, 140, 210, 145, 210, 125);
ctx.stroke();
break;
case 6:
ctx.beginPath();
ctx.moveTo(200, 145);
ctx.lineTo(200, 250);
ctx.stroke();
break;
case 7:
ctx.beginPath();
ctx.moveTo(200, 250);
ctx.lineTo(150, 300);
ctx.stroke();
break;
case 8:
ctx.beginPath();
ctx.moveTo(200, 250);
ctx.lineTo(250, 300);
ctx.stroke();
break;
case 9:
ctx.beginPath();
ctx.moveTo(200, 195);
ctx.lineTo(150, 195);
ctx.stroke();
break;
case 10:
ctx.beginPath();
ctx.moveTo(200, 195);
ctx.lineTo(250, 195);
ctx.stroke();
ctx.fillStyle = "#F00000";
ctx.font = "150px monospace";
ctx.fillText("Perdu", 0, canvas.height / 2, canvas.width);
break;
}
}<file_sep>/README.md
# Js-Games
School project about games for children developed in Javascript
<file_sep>/Jeux.js
/**
* Created by Julien on 12/05/2015.
*/
/* Variables */
var EnfantConnecte;
/* Evenement + fonction chargement de la page */
window.addEventListener('load', initEventHandlers, false);
function initEventHandlers()
{
document.getElementById('lienDeconnexion').innerHTML = "Se déconnecter";
var url = document.URL;
var tabUrl = url.split("=");
recuperation(tabUrl[1]);
document.getElementById('infos').style.border = "1px solid black";
document.getElementById('infos').style.width = "200px";
document.getElementById('btnPendu').addEventListener('click', pendu, false)
document.getElementById('btnCalculus').addEventListener('click', calculus, false)
document.getElementById('btnPong').addEventListener('click', pong, false)
}
/* Fonctions de récupération des infos de l'enfant connecté */
function recuperation(Prenom)
{
var monEnfantJSON = localStorage.getItem(Prenom);
EnfantConnecte = JSON.parse(monEnfantJSON);
couleurFond();
document.getElementById('Prenom').innerHTML = EnfantConnecte.Prenom;
var monAvatar = document.getElementById('Avatar');
monAvatar.src = "Avatars/" + EnfantConnecte.Avatar;
document.getElementById('Points').innerHTML = "Meilleur score Pong : " + EnfantConnecte.BestPong;
document.getElementById('Jetons').innerHTML = "Jetons : " + EnfantConnecte.NombrePiece;
}
/* Fonction qui "initialise" le pendu */
function pendu()
{
document.getElementById('ZoneJeu').innerHTML = '<iframe id="Pendu" width="700px" height="480px"></iframe>';
document.getElementById('Pendu').src = "Pendulus.html?Prenom=" + EnfantConnecte.Prenom;
}
/* Fonction qui "initialise" le calculus */
function calculus()
{
document.getElementById('ZoneJeu').innerHTML = '<iframe id="Calculus" width="850px" height="500px"></iframe>';
document.getElementById('Calculus').src = "Calculus.html?Prenom=" + EnfantConnecte.Prenom;
}
/* Fonction qui "initialise" le pong */
function pong()
{
document.getElementById('ZoneJeu').innerHTML = '<iframe id="Pong" width="700px" height="510px"></iframe>';
document.getElementById('Pong').src = "Pongulus.html?Prenom=" + EnfantConnecte.Prenom;
}
function couleurFond()
{
if (EnfantConnecte.Sexe == "M")
document.getElementById('divJumbotron').style.backgroundColor = "#5D98F0";
else
document.getElementById('divJumbotron').style.backgroundColor = "#F05DEB";
} | 02ceff0e9bdd29782c0c35b9804881196b06f1be | [
"JavaScript",
"Markdown"
]
| 8 | JavaScript | JGuissart/Js-Games | 44883f6892bb0642a1c65784c6dcbefef70c0d01 | 4bfc9be7d2132f84f42327664f9997d00a5241f5 |
refs/heads/master | <file_sep>jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc\:mysql\://localhost\:3306/SchoolSource
jdbc.user = root
jdbc.password =<PASSWORD><file_sep># 院校资源库
本项目为学校S2SH实训项目,预计能将功能做得尽可能的做得完善
## 预期功能
- ~~院校管理~~
- ~~用户管理~~
- ~~院校类型管理~~
- ~~专业管理~~
## 预计技术难点
- ~~文件上传~~
- ~~分页查询~~
- ~~Spring框架~~
- ~~Struts2自带标签~~
<file_sep>package com.schsource.school.service;
import com.schsource.school.dao.SchoolDao;
import com.schsource.school.vo.School;
import com.schsource.utils.PageBean;
import java.util.List;
/**
* @author vodka
* @version 1.0 2017-12-29
*/
public class SchoolService {
private SchoolDao schoolDao;
public SchoolDao getSchoolDao() {
return schoolDao;
}
public void setSchoolDao(SchoolDao schoolDao) {
this.schoolDao = schoolDao;
}
/**
*
* @param page
* @return
*/
public PageBean<School> findByPage(int page) {
PageBean<School> pageBean = new PageBean<School>();
pageBean.setPage(page);
int limit = 5;
pageBean.setLimit(limit);
int totalCount = schoolDao.getPageCount();
pageBean.setTotalCount(totalCount);
int totalPage = totalCount % limit == 0 ? totalCount/limit : totalCount/limit+1;
pageBean.setTotalPage(totalPage);
// 每页显示数据的集合
int begin = (page - 1) * limit;
List<School> list = schoolDao.getPageById(begin, limit);
pageBean.setList(list);
return pageBean;
}
/**
* 添加院校信息
* @param school
*/
public void saveSchool(School school) {
schoolDao.saveSchool(school);
}
/**
* 根据Id查询院校信息
* @param schId
* @return
*/
public School findSchoolById(int schId) {
return schoolDao.getSchoolById(schId);
}
/**
* 根据Name查询院校信息
* @param schname
* @return
*/
public School findSchoolByName(String schname) {
return schoolDao.getSchoolByName(schname);
}
/**
* 更新院校信息
* @param school
*/
public void updateSchool(School school) {
schoolDao.updateSchool(school);
}
/**
* 删除院校信息
* @param school
*/
public void deleteSchool(School school) {
schoolDao.deleteSchool(school);
}
/**
* 根据Tname统计院校
* @param tname
* @return
*/
public School countByTname(String tname) {
return schoolDao.countByTname(tname);
}
}
<file_sep>package com.schsource.users.dao;
import com.schsource.users.vo.Users;
import com.schsource.utils.PageHibernateCallBack;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author vodka
* @version 1.0 2017-12-26
*/
public class UsersDao extends HibernateDaoSupport {
/**
* 登录
* @param users
* @return
*/
public boolean login(Users users) {
String hql = "from Users where usersId = ? and upwd = ?";
List<Users> list = (List<Users>)this.getHibernateTemplate().find(hql, users.getUsersId(),
users.getUpwd());
for (Users users1 : list) {
users.setUname(users1.getUname());
users.setUlimit(users1.getUlimit());
}
if (list.size() > 0) {
return true;
} else {
return false;
}
}
/**
* 用户注册/添加
* @param users
*/
@Transactional(readOnly = false)
public void register(Users users) {
this.getHibernateTemplate().save(users);
}
/**
* 删除用户
* @param users
*/
@Transactional(readOnly = false)
public void deleteUsers(Users users) {
this.getHibernateTemplate().delete(users);
}
/**
* 修改用户信息
* @param users
*/
@Transactional(readOnly = false)
public void updateUsers(Users users) {
this.getHibernateTemplate().saveOrUpdate(users);
}
/**
* 根据usersId查询用户信息
* @param usersid
* @return
*/
public Users findUsersById(int usersid) {
return this.getHibernateTemplate().get(Users.class, usersid);
}
/**
* 查询用户信息总数
* @return
*/
public int getUsersPageCount() {
String hql = "select count(*) from Users";
List<Long> list = (List<Long>) this.getHibernateTemplate().find(hql);
if (list != null && list.size() > 0) {
return list.get(0).intValue();
}
return 0;
}
/**
* 查询当前页面用户信息的集合
* @param begin
* @param limit
* @return
*/
public List<Users> getUsersPageById(int begin, int limit) {
String hql = "from Users";
List<Users> list = this.getHibernateTemplate().execute((HibernateCallback<List<Users>>)
new PageHibernateCallBack(hql, new Object[]{}, begin, limit));
if (list != null && list.size() > 0) {
return list;
}
return null;
}
/**
* 根据uname查询用户信息
* @param uname
* @return
*/
public Users getUsersByName(String uname) {
String hql = "from Users where uname = ?";
List<Users> list = (List<Users>) this.getHibernateTemplate().find(hql, uname);
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
}
<file_sep>package com.schsource.type.dao;
import com.schsource.type.vo.Type;
import com.schsource.utils.PageHibernateCallBack;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 院校类型持久化
* @author vodka
* @date 2017-12-30
* @version 1.0
*/
public class TypeDao extends HibernateDaoSupport{
/**
* 查询院校类型信息
* @return
*/
public int getTypePageCount() {
String hql = "select count(*) from Type";
List<Long> list = (List<Long>) getHibernateTemplate().find(hql);
if (list != null && list.size() > 0) {
return list.get(0).intValue();
}
return 0;
}
/**
* 查询当前页面院校类型信息的集合
* @param begin
* @param limit
* @return
*/
public List<Type> getTypePageById(int begin, int limit) {
String hql = "from Type";
List<Type> list = this.getHibernateTemplate().execute((HibernateCallback<List<Type>>)
new PageHibernateCallBack(hql, new Object[]{}, begin, limit));
if (list != null && list.size() > 0) {
return list;
}
return null;
}
/**
* 添加院校类型信息
* @param type
*/
@Transactional(readOnly = false)
public void saveType(Type type) {
this.getHibernateTemplate().save(type);
}
/**
* 删除院校类型信息
* @param type
*/
@Transactional(readOnly = false)
public void removeType(Type type) {
this.getHibernateTemplate().delete(type);
}
/**
* 根据tId查询院校类型信息
* @param tId
* @return
*/
public Type getTypeById(int tId) {
return this.getHibernateTemplate().get(Type.class, tId);
}
/**
* 根据tName查询院校类型信息
* @param tName
* @return
*/
public Type getTypeByName(String tName) {
String hql = "from Type where tname = ?";
List<Type> list = (List<Type>) this.getHibernateTemplate().find(hql, tName);
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
/**
* 更新院校类型信息
* @param type
*/
@Transactional(readOnly = false)
public void updateType(Type type) {
this.getHibernateTemplate().update(type);
}
}
<file_sep>package com.schsource.school.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.schsource.school.service.SchoolService;
import com.schsource.school.vo.School;
import com.schsource.utils.PageBean;
import org.apache.struts2.ServletActionContext;
import org.springframework.transaction.annotation.Transactional;
import sun.jvm.hotspot.debugger.Page;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
/**
* @author vodka
* @version 1.0 2017-12-29
*/
public class SchoolAction extends ActionSupport implements ModelDriven<School>{
private static final int BUFFER_SIZE = 40 * 40;
private School school = new School();
private SchoolService schoolService;
private File upload;
private String uploadContentType;
private String uploadFileName;
private String savePath;
private int page;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public void setSchoolService(SchoolService schoolService) {
this.schoolService = schoolService;
}
@Override
public School getModel() {
return school;
}
/**
* 将源文件复制成目标文件
* @param source 源文件对象
* @param target 目标文件对象
*/
private static void copy(File source, File target) {
// 声明一个输入流
InputStream inputStream = null;
// 声明一个输出流
OutputStream outputStream = null;
try {
// 实例化输入流
inputStream = new BufferedInputStream(new FileInputStream(source),BUFFER_SIZE);
// 实例化输出流
outputStream = new BufferedOutputStream(new FileOutputStream(target), BUFFER_SIZE);
// 定义字节数组buffer
byte[] buffer = new byte[BUFFER_SIZE];
// 定义临时参数变量
int length = 0;
while ((length = inputStream.read(buffer)) > 0){
// 如果上传的文件字节数大于0,将内容以字节的形式写入
outputStream.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
// 关闭输入流
inputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (null != outputStream) {
try {
// 关闭输出流
outputStream.close();
} catch (Exception e3) {
e3.printStackTrace();
}
}
}
}
/**
* 添加院校信息
* @return success
* @throws Exception
*/
public String saveSchool() {
String path = ServletActionContext.getServletContext().getRealPath("/upload")
+ this.getUploadFileName();
school.setSchpic(this.uploadFileName);
File target = new File(path);
copy(this.upload, target);
schoolService.saveSchool(school);
return SUCCESS;
}
/**
* 查看全部院校信息
* @return
*/
public String listAllSchool() {
PageBean<School> pageBean = schoolService.findByPage(page);
ActionContext.getContext().getValueStack().set("PageBean", pageBean);
return SUCCESS;
}
/**
* 根据Id查询院校信息
* @return
*/
public String getSchoolById() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
int schId = Integer.parseInt(request.getParameter("schid"));
School school = schoolService.findSchoolById(schId);
session.setAttribute("schid", school.getSchid());
session.setAttribute("schname",school.getSchname());
session.setAttribute("schpic", school.getSchpic());
session.setAttribute("pname", school.getPname());
session.setAttribute("tname", school.getTname());
session.setAttribute("schaddress", school.getSchaddress());
session.setAttribute("teacher", school.getTeacher());
session.setAttribute("tel", school.getTel());
return SUCCESS;
}
/**
* 根据name查找院校信息
* @return
*/
public String getSchoolByName() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
String name = new String(request.getParameter("schname").getBytes("ISO-8859-1"),"UTF-8");
School school1 = schoolService.findSchoolByName(name);
session.setAttribute("schid", school1.getSchid());
session.setAttribute("schname",school1.getSchname());
session.setAttribute("schpic", school1.getSchpic());
session.setAttribute("pname", school1.getPname());
session.setAttribute("tname", school1.getTname());
session.setAttribute("schaddress", school1.getSchaddress());
session.setAttribute("teacher", school1.getTeacher());
session.setAttribute("tel", school1.getTel());
return SUCCESS;
}
/**
* 根据name查找院校信息
* @return
*/
public String getSchoolByNameT() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
String name = request.getParameter("schname");
School school1 = schoolService.findSchoolByName(name);
session.setAttribute("schid", school1.getSchid());
session.setAttribute("schname",school1.getSchname());
session.setAttribute("schpic", school1.getSchpic());
session.setAttribute("pname", school1.getPname());
session.setAttribute("tname", school1.getTname());
session.setAttribute("schaddress", school1.getSchaddress());
session.setAttribute("teacher", school1.getTeacher());
session.setAttribute("tel", school1.getTel());
return SUCCESS;
}
/**
* 修改院校信息
* @return
*/
public String updateSchool() {
String path = ServletActionContext.getServletContext().getRealPath("/upload")
+ this.getUploadFileName();
school.setSchpic(this.uploadFileName);
File target = new File(path);
copy(this.upload, target);
schoolService.updateSchool(school);
return SUCCESS;
}
/**
* 删除院校信息
* @return
*/
public String removeSchool() {
schoolService.deleteSchool(school);
return SUCCESS;
}
/**
* 根据tname统计院校信息
* @return
*/
public String countSchoolByName() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
String tname = (String) request.getAttribute("tname");
schoolService.countByTname(tname);
return SUCCESS;
}
}
| 84e59c23fd362ddeeb40b38db65e72e957514d6c | [
"Markdown",
"Java",
"INI"
]
| 6 | INI | DefaultStudent/SchoolSource | 6d141d3aa7d4eef46ac150708525e99c769f6948 | ef80f0282d877f783e608010d1ffaa90a3182c6a |
refs/heads/master | <repo_name>christopherjereza/wizards<file_sep>/project_script.py
import random
def wizard(w):
constraints = []
wizdict = {}
for c in range(0, w):
wizdict[c] = random.randint(0, 1000000)
for key in range(0, w):
for key2 in range(key + 1, w, 2):
for key3 in range(key2 + 1, w, 2):
lst = []
lst2 = []
if wizdict[key] not in range(wizdict[key2], wizdict[key3] + 1):
lst = [key2, key3, key]
lst2 = [key3, key2, key]
if lst not in constraints:
constraints.append(lst)
if lst2 not in constraints:
constraints.append(lst2)
print(constraints)
print(len(constraints))
<file_sep>/solver.py
import argparse
import random
import math
import copy
import time
"""
======================================================================
Complete the following function.
======================================================================
"""
def cost(solution, constraints):
return validator(solution, constraints)
#Move a randomly-selected wizard to a random location in the ordering
def neighbor(solution):
temp = copy.deepcopy(solution)
wizToMove = temp.pop(random.randrange(len(temp)))
temp.insert(random.randrange(len(temp)), wizToMove)
return temp
#The probability of accepting a sampled ordering.
def acceptance_probability(old_cost, new_cost, T):
if new_cost < old_cost:
return 1.0
else:
return math.exp((old_cost - new_cost) / T)
#Simulated Annealing main function
def anneal(num_wizards, num_constraints, wizards, constraints):
ageDict = {}
startTime = time.time()
random.shuffle(wizards)
solution = wizards
old_cost = cost(solution, constraints)
new_cost = num_constraints
T = 1.0
T_min = 0.0001
alpha = 0.9
while T > T_min:
currTime = time.time()
if currTime - startTime > num_wizards*2:
return wizards, old_cost
i = 1
while i <= 9000:
new_solution = neighbor(solution)
new_cost = cost(new_solution, constraints)
if new_cost == 0:
return new_solution, new_cost
ap = acceptance_probability(old_cost, new_cost, T)
if ap > random.random():
solution = new_solution
old_cost = new_cost
i += 1
T = T*alpha
return solution, old_cost
def validator(wizards, constraints):
count = 0
for constraint in constraints:
wiz1 = wizards.index(constraint[0])
wiz2 = wizards.index(constraint[1])
wiz3 = wizards.index(constraint[2])
if wiz1 < wiz2:
if wiz3 > wiz1 and wiz3 < wiz2:
continue
else:
count += 1
if wiz2 < wiz1:
if wiz3 < wiz1 and wiz3 > wiz2:
continue
else:
count += 1
return len(constraints) - count
def solve(num_wizards, num_constraints, wizards, constraints):
"""
Write your algorithm here.
Input:
num_wizards: Number of wizards
num_constraints: Number of constraints
wizards: An array of wizard names, in no particular order
constraints: A 2D-array of constraints,
where constraints[0] may take the form ['A', 'B', 'C']
Output:
An array of wizard names in the ordering your algorithm returns
"""
ret = wizards
cost = num_constraints
while cost > 0:
print 'attempt'
print cost
ret, cost = anneal(num_wizards, num_constraints, ret, constraints)
return ret
"""
======================================================================
No need to change any code below this line
======================================================================
"""
def read_input(filename):
with open(filename) as f:
num_wizards = int(f.readline())
num_constraints = int(f.readline())
constraints = []
wizards = set()
for _ in range(num_constraints):
c = f.readline().split()
constraints.append(c)
for w in c:
wizards.add(w)
wizards = list(wizards)
return num_wizards, num_constraints, wizards, constraints
def write_output(filename, solution):
with open(filename, "w") as f:
for wizard in solution:
f.write("{0} ".format(wizard))
if __name__=="__main__":
parser = argparse.ArgumentParser(description = "Constraint Solver.")
parser.add_argument("input_file", type=str, help = "___.in")
parser.add_argument("output_file", type=str, help = "___.out")
args = parser.parse_args()
num_wizards, num_constraints, wizards, constraints = read_input(args.input_file)
solution = solve(num_wizards, num_constraints, wizards, constraints)
write_output(args.output_file, solution)
| 0469b85f07943c0d4afa44cf31b23b1efb03d71b | [
"Python"
]
| 2 | Python | christopherjereza/wizards | 59354f3d4d829d7e4c56a839be11dac677f50c99 | fe0ec5ada04e84f386db1d56a201b95c94e4a1db |
refs/heads/master | <file_sep>use crate::hinge::Hinge;
use crate::hinge::HingeState;
use crate::lock::Lock;
use crate::lock::LockState;
use crate::util::Result;
use rocket::config::Config;
use rocket::config::Environment;
use rocket::http::Status;
use rocket::State;
use rocket_contrib::json::Json;
use std::sync::Arc;
use std::sync::Mutex;
#[derive(Deserialize)]
pub struct ServerSettings {
pub mount_point: String,
pub port: u16,
}
#[derive(Deserialize)]
struct LockInput {
state: Option<LockState>,
}
#[derive(Serialize)]
struct LockOutput {
state: LockState,
last_change: u64,
}
#[derive(Serialize)]
struct HingeOutput {
state: HingeState,
}
pub fn run(settings: ServerSettings, hinge: Arc<Mutex<Hinge>>, lock: Arc<Mutex<Lock>>) {
rocket::custom(
Config::build(Environment::Staging)
.address("localhost")
.port(settings.port)
.unwrap(),
)
.mount(
&settings.mount_point,
routes![put_lock, put_lock_toggle, get_lock, get_hinge],
)
.manage(hinge)
.manage(lock)
.launch();
}
#[put("/lock", data = "<data>")]
fn put_lock(state: State<Arc<Mutex<Lock>>>, data: Json<LockInput>) -> Result<Status> {
let lock = &mut state.inner().lock().unwrap();
let data = data.into_inner();
if let Some(new_state) = data.state {
lock.set_state(new_state)?;
}
Ok(Status::NoContent)
}
#[post("/lock?toggle")]
fn put_lock_toggle(state: State<Arc<Mutex<Lock>>>) -> Result<Status> {
let lock = &mut state.inner().lock().unwrap();
let new_state = match lock.read_state()? {
LockState::Unlocked => LockState::Locked,
LockState::Locked => LockState::Unlocked,
};
lock.set_state(new_state)?;
Ok(Status::NoContent)
}
#[get("/lock")]
fn get_lock(state: State<Arc<Mutex<Lock>>>) -> Result<Json<LockOutput>> {
let lock = &state.inner().lock().unwrap();
let result = LockOutput {
state: lock.read_state()?,
last_change: lock
.last_change()
.duration_since(std::time::UNIX_EPOCH)?
.as_secs(),
};
Ok(Json(result))
}
#[get("/hinge")]
fn get_hinge(state: State<Arc<Mutex<Hinge>>>) -> Result<Json<HingeOutput>> {
let hinge = &mut state.inner().lock().unwrap();
let result = HingeOutput {
state: hinge.read_state()?,
};
Ok(Json(result))
}
<file_sep>#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate serde_derive;
mod hinge;
mod led;
mod lock;
mod server;
mod util;
use crate::util::Result;
use env_logger::Builder;
use env_logger::Env;
use hinge::Hinge;
use led::LedController;
use lock::Lock;
use mcp23x17::Expander;
use server::ServerSettings;
use std::sync::Arc;
use std::sync::Mutex;
#[derive(Deserialize)]
struct Config {
expander_device: String,
output_pins: OutputPinsSettings,
input_pins: InputPinsSettings,
server: ServerSettings,
}
#[derive(Deserialize)]
struct OutputPinsSettings {
green_leds: Vec<u8>,
red_leds: Vec<u8>,
lock: u8,
}
#[derive(Deserialize)]
struct InputPinsSettings {
hinge: u8,
}
fn read_config() -> Result<Config> {
let conf_str = std::fs::read_to_string("castle.toml")?;
toml::from_str(&conf_str).map_err(From::from)
}
fn main() -> Result {
// initialize logger w/ log level "info"
Builder::from_env(Env::new().default_filter_or("info")).init();
let conf = read_config()?;
let expander = Expander::new(&conf.expander_device)?;
let green_leds = conf
.output_pins
.green_leds
.iter()
.map(|&pin| expander.output(pin))
.collect();
let red_leds = conf
.output_pins
.red_leds
.iter()
.map(|&pin| expander.output(pin))
.collect();
let lock = Arc::new(Mutex::new(Lock::new(
expander.output(conf.output_pins.lock),
)?));
let hinge = Arc::new(Mutex::new(Hinge::new(
expander.input(conf.input_pins.hinge),
)));
let mut led_ctrl = LedController::new(green_leds, red_leds, lock.clone(), hinge.clone());
crossbeam::thread::scope(|s| {
// spawn LED controller thread
s.spawn(|_| {
led_ctrl.run();
});
// spawn web server thread
s.spawn(|_| {
server::run(conf.server, hinge, lock.clone());
});
})
.unwrap();
Ok(())
}
<file_sep>use crate::hinge::Hinge;
use crate::hinge::HingeState;
use crate::lock::Lock;
use crate::lock::LockState;
use crate::util::Result;
use mcp23x17::IoValue;
use mcp23x17::Output;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
pub struct LedController {
green_leds: Vec<Output>,
red_leds: Vec<Output>,
lock: Arc<Mutex<Lock>>,
hinge: Arc<Mutex<Hinge>>,
}
impl LedController {
pub fn new(
green_leds: Vec<Output>,
red_leds: Vec<Output>,
lock: Arc<Mutex<Lock>>,
hinge: Arc<Mutex<Hinge>>,
) -> Self {
Self {
green_leds,
red_leds,
lock,
hinge,
}
}
pub fn run(&mut self) {
loop {
let _ = self.try_run().map_err(|err| {
error!("LedController observed: {}", err);
});
}
}
pub fn try_run(&mut self) -> Result {
let mut tick: u64 = 0;
loop {
match {
let lock = &mut self.lock.lock().unwrap();
let hinge = &mut self.hinge.lock().unwrap();
(lock.read_state()?, hinge.read_state()?)
} {
(LockState::Locked, HingeState::Closed) => {
tick = 0;
self.red()?;
}
(LockState::Locked, HingeState::Open) => {
if tick < 5 {
self.red()?;
} else {
self.green()?;
}
tick += 1;
tick %= 10;
}
(LockState::Unlocked, _) => {
tick = 0;
self.green()?;
}
};
std::thread::sleep(Duration::from_millis(50));
}
}
fn red(&mut self) -> Result {
Self::set_values(&mut self.green_leds, IoValue::High)?;
Self::set_values(&mut self.red_leds, IoValue::Low)?;
Ok(())
}
fn green(&mut self) -> Result {
Self::set_values(&mut self.green_leds, IoValue::Low)?;
Self::set_values(&mut self.red_leds, IoValue::High)?;
Ok(())
}
fn set_values(leds: &mut [Output], value: IoValue) -> Result {
for led in leds {
led.set_value(value)?;
}
Ok(())
}
}
<file_sep>use crate::util::Result;
use mcp23x17::Input;
use mcp23x17::IoValue;
#[derive(Serialize, Deserialize, Clone, Copy)]
pub enum HingeState {
Closed,
Open,
}
pub struct Hinge {
in_pin: Input,
}
impl Hinge {
pub fn new(in_pin: Input) -> Self {
Hinge { in_pin }
}
pub fn read_state(&mut self) -> Result<HingeState> {
Ok(match self.in_pin.read_value()? {
IoValue::Low => HingeState::Open,
IoValue::High => HingeState::Closed,
})
}
}
<file_sep>use crate::util::Result;
use mcp23x17::IoValue;
use mcp23x17::Output;
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::time::Duration;
use std::time::SystemTime;
#[derive(Serialize, Deserialize, Clone, Copy)]
pub enum LockState {
Locked,
Unlocked,
}
#[derive(Debug)]
pub struct LockBusy {}
impl Display for LockBusy {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "Lock is busy")
}
}
impl Error for LockBusy {}
pub struct Lock {
out_pin: Output,
last_change: SystemTime,
}
impl Lock {
pub fn new(out_pin: Output) -> Result<Self> {
let mut lock = Lock {
out_pin,
last_change: std::time::UNIX_EPOCH,
};
lock.set_state(LockState::Locked)?;
Ok(lock)
}
pub fn read_state(&self) -> Result<LockState> {
Ok(match self.out_pin.read_value()? {
IoValue::Low => LockState::Locked,
IoValue::High => LockState::Unlocked,
})
}
pub fn set_state(&mut self, state: LockState) -> Result {
let now = SystemTime::now();
if now < self.last_change + Duration::from_millis(250) {
Err(LockBusy {})?;
}
self.last_change = now;
self.out_pin.set_value(match state {
LockState::Locked => IoValue::Low,
LockState::Unlocked => IoValue::High,
})?;
Ok(())
}
pub fn last_change(&self) -> SystemTime {
self.last_change
}
}
<file_sep># castle
A door lock controller to be installed on devices with a connected GPIO
expander.
## Build
```bash
$ cargo build
```
### With Nix
```bash
$ nix-build
```
With Nix you can also easily cross-compile castle:
```bash
$ nix-build '<nixpkgs>' \
--arg crossSystem '{ config = "aarch64-unknown-linux-gnu"; }' \
--arg overlays '[ (self: super: { castle = super.callPackage ./. {}; }) ]' \
-A castle
```
## Configuration
In the working directory where castle is executed, there must be a
`castle.toml` configuration file.
A good start is to copy the `castle.toml.example` from this repository.
### top-level keys
#### `expander_device =`
Path to the expander device. This is usually: `"/dev/spidev0.0"`
### [output_pins] section
#### `green_leds =`
List of output pin numbers where green LEDs are connected.
See [#leds](#leds).
#### `red_leds =`
List of output pin numbers where red LEDs are connected.
See [#leds](#leds).
#### `lock =`
Output pin number where the lock is connected.
### [input_pins] section
#### `hinge =`
Input pin number where the hinge is connected.
The hinge affects the visual feedback on the LEDs; see [#leds](#leds).
### [server] section
#### `mount_point =`
Prefix to the paths where the [REST endpoints](#rest-endpoints) are mounted.
#### `port =`
The port on which the [REST endpoints](#rest-endpoints) are served.
## REST endpoints
castle provides two rest endpoints: `/lock` and `/hinge`.
For example, with `mount_point = "/castle"` and `port = 8020`,
they're accessible at `http://localhost:8020/castle/lock` and
`http://localhost:8020/castle/hinge`, respectively.
We use these configuration values in the further examples.
We have a subsection for each type of supported request:
### `GET` request to the `/lock` endpoint
```bash
$ curl -X GET http://localhost:8020/castle/lock
{"state":"Locked","last_change":1546297200}
```
Hereby `"state"` is one of `"Locked"` and `"Unlocked"`.
`"last_change"` is the timestamp where that state changed lastly.
### `PUT` request to the `/lock` endpoint
Only putting the `"state"` field is supported.
```bash
$ curl -X PUT http://localhost:8020/castle/lock -d '{ "state": "Unlocked" }'
```
### `POST` request to the `/lock?toggle` endpoint
This toggles the `"state"`.
``` bash
$ curl -X POST http://localhost:8020/castle/lock?toggle
```
### `GET` request to the `/hinge` endpoint
```bash
$ curl -X GET http://localhost:8020/castle/hinge
{"state":"Closed"}
```
Hereby `"state"` is one of `"Closed"` and `"Open"`.
## LEDs
* If the lock is `"Unlocked"`, then only the green LEDs are on.
* If the lock is `"Locked"`:
* If the hinge is `"Closed"`, then only the red LEDs are on.
* If the hinge is `"Open"`, then the red and green LEDs alternate.
<file_sep>[package]
name = "castle"
version = "0.1.0"
authors = ["haslersn <<EMAIL>>"]
edition = "2018"
[dependencies]
crossbeam = "0.7"
env_logger = "0.6"
hex = "0.3"
log = "0.4"
mcp23x17 = { git = "https://github.com/haslersn/mcp23x17-rs" }
rocket = "0.4"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
spidev = "0.3"
toml = "0.4"
[dependencies.rocket_contrib]
version = "0.4"
default-features = false
features = ["json"]
| a88d584a6907470122a2e803a5d196b2f5089ce4 | [
"Markdown",
"Rust",
"TOML"
]
| 7 | Rust | stuvusIT/castle | 2de0ee11faecdc4e348857b6a2edd064081e1b8c | 195641e1d9235036eab05561883cb7186043a3f5 |
refs/heads/master | <file_sep>library(shiny)
library(dplyr)
data("iris")
options(shiny.maxRequestSize=30*1024^2)
shinyServer(function(input, output, session) {
df <- reactive({
req(input$uploaded_file)
read.csv(input$uploaded_file$datapath,
header = input$header,
sep = input$sep)
})
output$checkbox <- renderUI({
checkboxGroupInput(inputId = "select_var",
label = "Select variables",
choices = names(df()))
})
df_sel <- reactive({
req(input$select_var)
df_sel <- df() %>% select(input$select_var)
})
output$rendered_file <- DT::renderDataTable({
if(input$disp == "head") {
head(df_sel())
}
else {
df_sel()
}
})
})
<file_sep># Simplr Data Viewer App
A shiny app to sort and filter and show data
<file_sep>library(shiny)
library(DT)
shinyUI(fluidPage(
# Application title
titlePanel("Data Viewer"),
sidebarLayout(
sidebarPanel(
fileInput("uploaded_file", "Choose CSV File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
checkboxInput("header", "Header", TRUE),
radioButtons("sep", "Separator",
choices = c(Semicolon = ";", Comma = ",", Tab = "\t"),
selected = ","),
tags$hr(),
radioButtons("disp", "Display",
choices = c(All = "all",
Head = "head"),
selected = "all"),
uiOutput("checkbox")
),
mainPanel(
tabsetPanel(
id = "dataset",
tabPanel("FILE", DT::dataTableOutput("rendered_file"))
)
)
)
))
| d523f4c661c5088b5b44875e5fb9556fb131c45d | [
"Markdown",
"R"
]
| 3 | R | nemo0702/shiny-app-data-viewer | 229d9a3d9fd535262fe5940c4cd9745667c2a010 | 2dad001948291e1c5b91f0dc7838289e98d6338a |
refs/heads/master | <repo_name>Arios9/Minesweeper<file_sep>/src/MinesweeperFramePackage/HeaderLabel.java
package MinesweeperFramePackage;
import javax.swing.*;
import java.awt.*;
import static MinesweeperFramePackage.MinesweeperFrame.*;
import static MinesweeperFramePackage.RestartButton.buttonWidth;
public class HeaderLabel extends JLabel {
public HeaderLabel() {
setPreferredSize(new Dimension((frameWidth - buttonWidth)/2,headerHeight));
setOpaque(true);
setFont(new Font("Arial", Font.PLAIN, 50));
setHorizontalAlignment(SwingConstants.CENTER);
}
public void reFresh(int number) {
setText(String.valueOf(number));
}
}
<file_sep>/src/mainMenuPackage/GameLevel.java
package mainMenuPackage;
public class GameLevel {
private final String levelText;
private final int numberOfSquaresInHeight, numberOfSquaresInWidth, numberOfBombs;
public GameLevel(String levelText, int numberOfSquaresInHeight, int numberOfSquaresInWidth, int numberOfBombs) {
this.levelText = levelText;
this.numberOfSquaresInHeight = numberOfSquaresInHeight;
this.numberOfSquaresInWidth = numberOfSquaresInWidth;
this.numberOfBombs = numberOfBombs;
}
public String getLevelText() {
return levelText;
}
public int getNumberOfSquaresInHeight() {
return numberOfSquaresInHeight;
}
public int getNumberOfSquaresInWidth() {
return numberOfSquaresInWidth;
}
public int getNumberOfBombs() {
return numberOfBombs;
}
}<file_sep>/src/MinesweeperFramePackage/BoardPanel.java
package MinesweeperFramePackage;
import javax.swing.*;
import java.awt.*;
import static mainCode.MinesweeperGame.*;
public class BoardPanel extends JPanel {
public BoardPanel() {
setPreferredSize(new Dimension(arrayWidth * 50, arrayHeight * 50));
setLayout(new GridLayout(arrayHeight, arrayWidth));
}
public void setTheBoard() {
for(int i = 0; i< arrayHeight; i++)
for(int j = 0; j< arrayWidth; j++)
add(squares[i][j]=new Square(i,j));
}
}
<file_sep>/src/mainCode/AudioManager.java
package mainCode;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class AudioManager {
public static void playAudio(File file) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/mainMenuPackage/RecordLabel.java
package mainMenuPackage;
import javax.swing.*;
import java.awt.*;
public class RecordLabel extends JLabel {
public RecordLabel(String text) {
super(text);
setFont(new Font("Arial",Font.BOLD,20));
setPreferredSize(new Dimension(150 , 60));
setHorizontalAlignment(CENTER);
}
}
| 7caa852a2769c272afc33a85fcf0c750637bb830 | [
"Java"
]
| 5 | Java | Arios9/Minesweeper | a73e369fd023d68863565098059d12a7d5515e20 | e113f4c14b167f784f65162d7189c4624df0d047 |
refs/heads/master | <repo_name>Allasstar/sitehub-location-images-app<file_sep>/src/App.js
import './App.css';
import { Container, Button, Label, TextInput, Divider, ArrayInput } from '@playcanvas/pcui/pcui-react.js';
import { BindingTwoWay, Observer } from '@playcanvas/pcui/pcui-binding.js';
import React, { useState } from 'react';
const observer = new Observer({ status: 'Status: ok', locations: {}, locationImages: {} });
let token;
let projectId;
let locationId = -1;
let addUrls;
function App() {
return (
<Container class={'bgc1'}>
<TopPanel />
<Divider />
<SelectPanel />
<Divider />
<AddPanel />
</Container>
);
}
export default App;
// UI Panels
function TopPanel() {
const statusLink = { observer, path: 'status' };
return (
<Container height={40}>
<Label text='SiteHub' />
<TextInput placeholder='enter project id' onChange={enterProjectId}/>
<TextInput placeholder='enter lambda token' onChange={enterToken}/>
<Button text="Find Location" icon='E129' enabled={true} onClick={loadLocations} />
<Label binding={new BindingTwoWay()} link={statusLink} />
</Container>
);
}
function SelectPanel() {
const [ locations, setLocations ] = useState({});
observer.on('locations:set', setLocations);
const [ locationImages, setLocationImages ] = useState({});
observer.on('locationImages:set', setLocationImages);
return (
<Container class={'col2'}>
<Label text='Locations' />
<Container class={'bgc2'} hidden={false} height={250} scrollable={true}>
{
locations?.value?.map(key => {
return [
<Button text={`Select > id: ${key.id} title: ${key.title}`} icon='E131' width={220} enabled={true} onClick={() => loadLocationImages(key)} />
];
})
}
</Container>
<Label text='Location Images' />
<Container class={'bgc3'} hidden={false} height={250} scrollable={true}>
{
locationImages?.value?.map(key => {
return [
<Container>
<Label text={`id: ${key.id} - Name: ${key.imageURL.split('/').reverse()[0]}`} />
<Button text="Open" icon='E117' width={80} enabled={true} onClick={() => {window.open(key.imageURL)}} />
<Button text="Delete" icon='E124' width={80} enabled={true} onClick={() => deleteLocationImages(key.id)} />
</Container>
];
})
}
</Container>
</Container>
);
}
function AddPanel() {
return (
<Container class={'bgc4'} >
<Label text='Add URLs' />
<ArrayInput enabled={true} width={720} onChange={(value) => changeLocationImageArrayInput(value)} type="string"/>
<Button text="Apply" icon='E133' enabled={true} onClick={() => postLocationImages()} />
</Container>
);
}
// UI Events
const enterToken = (value) => {
token = value;
console.log('token =', token);
};
const enterProjectId = (value) => {
projectId = value;
console.log('projectId =', projectId);
};
const changeLocationImageArrayInput = (key) => {
addUrls = key;
console.log('changeLocationImages', addUrls);
}
// Requests
const locationUrl = "https://o8n4pc42ee.execute-api.eu-north-1.amazonaws.com/dev/core/locations";
const locationImagesUrl = "https://o8n4pc42ee.execute-api.eu-north-1.amazonaws.com/dev/core/location-images";
const loadLocations = () => {
locationId = -1;
observer.set('locations',{});
observer.set('locationImages', {});
observer.set('status', `Status: finding locations for project id: ${projectId}`);
var myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("project_id", projectId);
var requestOptions = {
method: 'GET',
headers: myHeaders
};
fetch(locationUrl, requestOptions)
.then(response => response.text())
.then(result => {
const value = JSON.parse(result);
console.log('Location count:', value?.length);
observer.set('status', `Status: finded [${value?.length}] locations`);
observer.set('locations', {value});
})
.catch(error => {
console.log('error', error);
observer.set('status', `Status: error [${error}]`);
});
console.log('loadLocations =', projectId);
};
const loadLocationImages = (key) => {
locationId = -1;
observer.set('locationImages', {});
observer.set('status', `Status: loading images for location id: ${key.id}`);
var myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("location_id", key.id);
var requestOptions = {
method: 'GET',
headers: myHeaders,
};
fetch(locationImagesUrl, requestOptions)
.then(response => response.text())
.then(result => {
const value = JSON.parse(result);
console.log('Location count:', value?.length);
value?.sort((a,b) => a.id - b.id);
observer.set('locationImages', {value});
observer.set('status', `Status: loaded [${value?.length}] images for location id: ${key.id}`);
locationId = key.id;
})
.catch(error => {
console.log('error', error);
observer.set('status', `Status: error [${error}]`);
});
};
const postLocationImages = () => {
if (addUrls?.length === 0 || addUrls ===null) {
observer.set('status', `Status: need add URLs`);
return;
}
let limg = [];
for (let a of addUrls) {
if (a !== '' & a !==undefined) {
limg.push({
locationId,
imageURL: a,
});
}
}
if (limg?.length === 0) {
observer.set('status', `Status: URL field(s) is empty`);
return;
}
if (locationId < 0) {
observer.set('status', `Status: need select locationId`);
return;
}
observer.set('status', `Status: start adding [${addUrls?.length}] images to locationId: [${locationId}]`);
var myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify(limg);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
};
fetch(locationImagesUrl, requestOptions)
.then(response => response.text())
.then(result => {
observer.set('status', `Status: added [${addUrls?.length}] images to locationId: [${locationId}]`);
console.log(result);
result = JSON.parse(result);
const value = observer.get('locationImages').value;
for (const i of result) {
value.push(i)
}
value?.sort((a,b) => a.id - b.id);
observer.set('locationImages', {});
observer.set('locationImages', {value});
})
.catch(error => {
console.log('error', error);
observer.set('status', `Status: error [${error}]`);
});
}
const deleteLocationImages = (key) => {
console.log('delete img id =', key);
observer.set('status', `Status: start deleting image id [${key}] in locationId: [${locationId}]`);
var myHeaders = new Headers();
myHeaders.append("Authorization", "<KEY>");
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify([{id:key}]);
var requestOptions = {
method: 'DELETE',
headers: myHeaders,
body: raw,
};
fetch(locationImagesUrl, requestOptions)
.then(response => response.text())
.then(result => {
console.log(result);
observer.set('status', `Status: deleted image id [${key}] in locationId: [${locationId}]`);
const value = observer.get('locationImages').value;
const foundIndex = value.findIndex(e => e?.id === key);
delete value[foundIndex];
value?.sort((a,b) => a.id - b.id);
observer.set('locationImages', {});
observer.set('locationImages', {value});
})
.catch(error => {
console.log('error', error);
observer.set('status', `Status: need select locationId`);
});
} | 3d8db7688558076e8ee2b59fd961808194d6701a | [
"JavaScript"
]
| 1 | JavaScript | Allasstar/sitehub-location-images-app | 97c9dd84c270044abd2f2110c0d8ca2ea50eb851 | e23fe78affa85e3ee1916eefa6c3e3c0f76b9cee |
refs/heads/master | <repo_name>reddyalex/struktur-data<file_sep>/BFS/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BFS
{
class Program
{
static int[,] map = new int[9, 9];
static Queue<Node> open;
static Stack<Node> close;
static List<int> historykota;
static Node start;
static Node goal;
static void Main(string[] args)
{
//kota = idkota
//a=0; d=4
//b=1; dst;
//c=2;
/* map = new int[,] { { 0 , 2, -1, 1, -1, -1, -1 },
{ 2 , 0, 5, -1, -1, -1, -1 },
{ -1 , 5, 0, 3, 4, -1, -1 },
{ 1 ,-1, 3, 0, 2, -1, -1 },
{ -1 ,-1, 4, 2, 0, 3, 5 },
{ -1 ,-1, -1, -1, 3, 0, -1 },
{ -1 ,-1, -1, -1, 5, -1, 0 },
};
map = new int[,] { { 0 , 14, 2, 5, -1, -1, -1 },
{ 14 , 0, 1, -1, -1, -1, 2 },
{ 2 , 1, 0, -1, 5, -1, -1 },
{ 5 , -1,-1, 0, 4, -1, -1 },
{ -1 , -1, 5, 4, 0, 8, 2 },
{ -1 , -1,-1, -1, 8, 0, 1 },
{ -1 , 2,-1, -1, 2, 1, 0 },
};
*/
map = new int[,]{ {65,91,58,24},
{0,-84,20,0},
{26,21, 90, -17},
{97,-6,-62,-27}
};
int starty;
int startx;
starty = 1;
startx = 0;
/*
start = new Node(0);
goal = new Node(5);
Console.WriteLine(goal.idtujuan);
open = new Queue<Node>();
close = new Stack<Node>();
historykota = new List<int>();
open.Enqueue(start);
historykota.Add(start.idtujuan);
bool blmketemu = true;
while (open.Count>=0 && blmketemu)
{
Node yangdiexpand = open.Dequeue();
close.Push(yangdiexpand);
//yangdiexpand.idtujuan
List<int> idkotacalonmasukopening = new List<int>();
for (int idkota = 0; idkota < 7; idkota++)
{
if (map[yangdiexpand.idtujuan,idkota]>0 && !historykota.Contains(idkota))
{
Node temp = new Node(idkota,yangdiexpand.idtujuan,map[yangdiexpand.idtujuan,idkota]);
open.Enqueue(temp);
historykota.Add(idkota);
idkotacalonmasukopening.Add(idkota);
}
}
//for (int i = idkotacalonmasukopening.Count-1; i >= 0; i--)
//{
// if (historykota.Contains(idkotacalonmasukopening[i]))
// {
// idkotacalonmasukopening.RemoveAt(i);
// }
// //looping di bawah ini tergantikan oleh if contains
// //for (int j = 0; j < historykota.Count; j++)
// //{
// // if (idkotacalonmasukopening[i] == historykota[j])
// // {
// // idkotacalonmasukopening.RemoveAt(i);
// // //hapus idkota calon masuk opening
// // }
// //}
//}
// looping di bawah ini salah.. karena remove dari bawah, proses remove tidak boleh dari bawah, harus dari belakang!!!
//for (int i = 0; i < idkotacalonmasukopening.Count; i++)
//{
// for (int j = 0; j < historykota.Count; j++)
// {
// if (idkotacalonmasukopening[i] == historykota[j])
// {
// //hapus idkota calon masuk opening
// }
// }
//}
blmketemu = belumketemutujuan();
//expand yang di open
}
Console.WriteLine("tujuan adalah di "+close.Peek().idtujuan + " jalur yang di pilih sebagai berikut");
double totalcost = 0;
goal = close.Peek();
Console.WriteLine(goal.idtujuan + " berasal dari " + goal.idasal + " berjarak " + goal.bobot);
totalcost += goal.bobot;
while (close.Count>0 && close.Peek().idasal!=-1)
{
Node temp = close.Pop();
if (temp.idtujuan == goal.idasal)
{
Console.WriteLine(temp.idtujuan + " berasal dari " + temp.idasal + " berjarak " + temp.bobot);
totalcost += temp.bobot;
goal = temp;
}
}
Console.WriteLine("totalcost jaraknya adalah " + totalcost);
*/
Console.ReadKey();
}
static bool belumketemutujuan()
{
if (close.Count > 0)
{
if (close.Peek().idtujuan == goal.idtujuan)
{
return false;
}
}
return true;
}
}
class Node
{
public int idasal { get; set; }
public int idtujuan { get; set; }
public double bobot { get; set; }
//public Node(int kodetujuan)
//{
// idtujuan = kodetujuan;
// // -1 berarti starting point dengan asumsi kode kota tidak ada yang bernilai -1
// idasal = -1;
// //constructor
//}
public Node(int kodetujuan, int kodeasal= -1, double vbobot = 0)
{
idtujuan = kodetujuan;
// -1 berarti starting point dengan asumsi kode kota tidak ada yang bernilai -1
idasal = kodeasal;
bobot = vbobot;
//constructor
}
}
}
<file_sep>/priorityqueue/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MSDN.FSharp;
namespace priorityqueue
{
class Program
{
class buku
{
public buku()
{
}
public string pengarang { get; set; }
public int tahunterbit { get; set; }
}
static void Main(string[] args)
{
//yang depan adalah keynya
//yang belakang adalah valuenya
PriorityQueue<double, int> pq2 = new PriorityQueue<double, int>();
PriorityQueue<int, buku> pq = new PriorityQueue<int, buku>();
Stack<buku> aa = new Stack<buku>() ;
buku jumbuku = aa.Pop();
PriorityQueue<int, buku> priority = new PriorityQueue<int, buku>();
priority.Enqueue(5, new buku());
KeyValuePair<int, buku> temp = priority.Dequeue();
buku buku1 = new buku();
buku1.pengarang = "aljabar";
buku1.tahunterbit = 1999;
pq.Enqueue(buku1.tahunterbit, buku1);
buku1 = new buku();
buku1.pengarang = "budia";
buku1.tahunterbit = 2019;
pq.Enqueue(buku1.tahunterbit, buku1);
buku1 = new buku();
buku1.pengarang = "budib";
buku1.tahunterbit = 1992;
pq.Enqueue(buku1.tahunterbit, buku1);
buku1 = new buku();
buku1.pengarang = "baljabar";
buku1.tahunterbit = 2015;
pq.Enqueue(buku1.tahunterbit, buku1);
KeyValuePair<int,buku> node;
node = pq.Dequeue();
Console.Write(node.Value.pengarang);
Console.WriteLine(" - " + node.Value.tahunterbit);
Console.WriteLine(pq.Dequeue().Value.pengarang + " - " + pq.Dequeue().Value.tahunterbit);
//string namafile=Console.ReadLine();
//StreamReader sr = new StreamReader(namafile);
//int jumlahkota= Convert.ToInt32( sr.ReadLine());
//double[,] adjmatrix = new double[jumlahkota,jumlahkota];
//for (int i = 1; i <= jumlahkota; i++)
//{
// //masukkan nama kota
// string namakota = sr.ReadLine();
//}
//int jumlahedge = Convert.ToInt32(sr.ReadLine());
////jumlah edge
//for (int i = 0; i < jumlahedge; i++)
//{
// //baca edge
// string baris = sr.ReadLine();
// //baris.Split(" ");
//}
Console.ReadKey();
}
}
}
<file_sep>/DFS/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DFS
{
class Program
{
static int[,] map = new int[11, 11];
static int ukuranmap = 10;
static int maxim = int.MinValue;
class Tdata
{
public int x, y, arah, sum,level;
};
static void gerak(int x, int y, int arah, int sum, int level, List<int> lokasi)
{
if (level > 0)
{
if (y - 1 >= 0 && !lokasi.Contains((y - 1) * ukuranmap + x))
{
//atas
lokasi.Add((y - 1) * ukuranmap + x);
y--;
gerak(x, y, 0, sum + map[x, y], level - 1, lokasi);
lokasi.Remove((y) * ukuranmap + x);
y++;
}
if (x + 1 < ukuranmap && !lokasi.Contains((y) * ukuranmap + x + 1))
{
//kanan
lokasi.Add((y) * ukuranmap + x + 1);
x++;
gerak(x, y, 1, sum + map[x, y], level - 1, lokasi);
lokasi.Remove((y) * ukuranmap + x);
x--;
}
if (y + 1 < ukuranmap && !lokasi.Contains((y + 1) * ukuranmap + x))
{
//bawah
lokasi.Add((y+1)*ukuranmap +x);
y++;
gerak(x, y, 2, sum + map[x, y], level - 1, lokasi);
lokasi.Remove((y) * ukuranmap + x);
y--;
}
if (x - 1 >= 0 && !lokasi.Contains((y) * ukuranmap + x - 1 ))
{
//kiri
lokasi.Add((y) * ukuranmap + x - 1);
x--;
gerak(x, y, 3, sum + map[x, y], level - 1, lokasi);
lokasi.Remove((y) * ukuranmap + x);
x++;
}
}
else
{
if (maxim < sum)
{
maxim = sum;
Console.WriteLine("sum= " + sum);
Console.WriteLine("x= " + x);
Console.WriteLine("y= " + y);
Console.WriteLine("arah= " + arah);
Console.Write("path= ");
for (int i = 0; i < ukuranmap; i++)
{
Console.Write(lokasi[i] + " ");
}
Console.WriteLine();
Console.WriteLine();
}
}
}
/*map = new int[,]{ {65,91,58,24},
{0,-84,20,0},
{26,21, 90, -17},
{97,-6,-62,-27}
};
*/
static void Main(string[] args)
{
map = new int[,] {{69,26,6,64,67,-22,-68,-67,11,-29 },
{38,14,-28,56,44,54,42,60,48,49 } ,
{1,4,37,67,83,71,91,5,90,0},
{31,-12,44,96,-33,-44,37,38,16,-84},
{-82,42,-75,-6,-91,92,-77,22,30,21},
{-2,31,6,99,93,1,30,-61,2,58 },
{-90,-72,36,93,59,47,35,18,43,58 },
{78,34,-79,28,26,37,43,77,27,65 },
{71,83,-7,43,70,54,-84,-73,23,94 },
{47,46,24,27,17,32,11,14,73,82 }
};
int starty;
int startx;
starty = 2;
startx = 9;
List<int> xxx = new List<int>();
for (int arah = 0; arah < 4; arah++)
{
gerak(startx, starty, arah, 0, 11,xxx);
}
Console.ReadLine();
}
/* Stack<Tdata> st = new Stack<Tdata>();
Tdata awal = new Tdata();
awal.arah = 0;
awal.x = startx;
awal.y = starty;
awal.sum = 0;
awal.level = 10;
while (st.Count > 0)
{
Tdata temp = st.Pop();
int level = temp.level ;
while (level <= 0)
{
for (int i = 0; i < 4; i++)
{
}
}
}
*/
}
}
}
| 32a0c334f07f3e62490fdc5c71250ca666ce411a | [
"C#"
]
| 3 | C# | reddyalex/struktur-data | b1dd6499d840829281cdcaf399a687ce4b40a52a | 8730b41a3168702824feef7cfa84b09f8b39d375 |
refs/heads/main | <repo_name>vdmklchv/guessNumberJonasAssignment<file_sep>/script.js
'use strict';
// state vars
let secretNumber;
let score;
let hiScore = 0;
// DOM elements
const body = document.querySelector('body');
const guessInput = document.querySelector('.guess');
const checkButton = document.querySelector('.check');
const message = document.querySelector('.message');
const numberBox = document.querySelector('.number');
const scoreDisplay = document.querySelector('.score');
const againButton = document.querySelector('.again');
const highScoreDisplay = document.querySelector('.highscore');
// Factory UI function
function UI() {};
UI.prototype.setMessage = function (text) {
message.textContent = text;
}
UI.prototype.setBgColor = function (color) {
body.style.backgroundColor = color;
}
UI.prototype.setNumberBoxWidth = function (width) {
numberBox.style.width = width;
}
UI.prototype.setInputsButtons = function (isGameOver) {
if (isGameOver) {
checkButton.disabled = true;
guessInput.disabled = true;
againButton.disabled = false;
} else {
checkButton.disabled = false;
guessInput.disabled = false;
againButton.disabled = true;
}
}
UI.prototype.setScoreDisplay = function (score) {
scoreDisplay.textContent = score;
}
UI.prototype.setHighScore = function (hiscore) {
highScoreDisplay.textContent = hiscore;
}
UI.prototype.clearInput = function () {
guessInput.value = '';
}
UI.prototype.showSecretNumber = function (number) {
numberBox.textContent = number;
}
// Factory score function
const Score = function () {
this.score = 0;
this.highScore = 0;
}
Score.prototype.setScore = function (score) {
this.score = score;
}
Score.prototype.setHighScore = function (score) {
this.highScore = score;
}
Score.prototype.getScore = function () {
return this.score;
}
Score.prototype.getHighScore = function () {
return this.highScore;
}
Score.prototype.decreaseScore = function () {
this.score--;
}
const scoreManager = new Score();
// Functions
const gameOver = function (isWon) {
const ui = new UI();
if (isWon) {
ui.setBgColor("#60b347");
ui.setMessage("Correct number!");
ui.setNumberBoxWidth("30rem");
} else {
ui.setBgColor("#ff1111");
ui.setMessage("You have lost the game!");
}
ui.setInputsButtons(true);
}
const gameStart = function () {
const ui = new UI();
// logic
secretNumber = Math.trunc(Math.random() * 20) + 1;
scoreManager.setScore(20);
// ui
ui.setNumberBoxWidth("15rem");
ui.setScoreDisplay("20");
ui.setMessage("Start guessing...");
ui.setBgColor("#222");
ui.setInputsButtons(false);
ui.clearInput();
ui.showSecretNumber("?");
guessInput.focus();
}
const game = function () {
const ui = new UI();
const guess = Number(guessInput.value);
// When there is no input
if (!guess) {
ui.setMessage("No number (;");
// Guess is correct
} else if (guess === secretNumber) {
if (scoreManager.getHighScore() < scoreManager.getScore()) {
scoreManager.setHighScore(scoreManager.getScore());
}
ui.showSecretNumber(secretNumber);
ui.setHighScore(scoreManager.getHighScore());
gameOver(true);
// Guess is too high
} else if (guess > secretNumber) {
if (scoreManager.getScore() > 1) {
ui.setMessage("Too high!");
scoreManager.decreaseScore();
ui.setScoreDisplay(scoreManager.getScore());
ui.clearInput();
} else {
gameOver(false);
ui.setScoreDisplay(0);
}
// Guess is too low
} else if (guess < secretNumber) {
if (scoreManager.getScore() > 1) {
ui.setMessage("Too low!");
scoreManager.decreaseScore();
ui.setScoreDisplay(scoreManager.getScore());
ui.clearInput();
} else {
gameOver(false);
ui.setScoreDisplay(0);
}
}
}
// Start game
gameStart();
// EventListeners
checkButton.addEventListener('click', game);
guessInput.addEventListener('keypress', function (e) {
if (e.key === "Enter" && guessInput.disabled === false) {
game();
}
})
againButton.addEventListener('click', gameStart);
document.addEventListener('keypress', function (e) {
if (guessInput.disabled === true && e.key === " ") {
gameStart();
}
}) | 1f36ae01199b3526ebb94bac35b627432b890fb5 | [
"JavaScript"
]
| 1 | JavaScript | vdmklchv/guessNumberJonasAssignment | d08437541f5b8eeb30ab6fd45eefa60a798f4875 | 6703d28908b23c07054bee78d066c89240f8c1a4 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace OpenGlTemplateApp
{
public partial class OglControl : UserControl
{
int oglcontext=0;
bool enablePaint;
public bool EnablePaint
{
get { return enablePaint; }
set {
enablePaint = value;
if(enablePaint)
{
if (oglcontext == 0) oglcontext = DllImportFunctions.InitOpenGL((int)Handle);
}
}
}
public OglControl()
{
InitializeComponent();
}
protected override void OnPaintBackground(PaintEventArgs pevent) { }
int renderParameter;
public int RenderParameter
{
get { return renderParameter; }
set { renderParameter = value; }
}
private void OglControl_Paint(object sender, PaintEventArgs e)
{
if(oglcontext != 0) DllImportFunctions.Render((int)Handle, oglcontext, Width, Height, RenderParameter);
}
}
}
public class DllImportFunctions
{
[DllImport("OpenGlCppCode.Dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "InitOpenGL")]
public static extern int InitOpenGL(int hdc);
[DllImport("OpenGlCppCode.Dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Render")]
public static extern void Render(int hdc, int oglcontext, int w, int h, int type);
}
<file_sep>// OpenGlCppCode.cpp: определяет экспортированные функции для приложения DLL.
//
#include "stdafx.h"
#include <windows.h>
#include <gl\GL.h>
#include <exception>
#define CPP_EXPORTS_API
#ifdef CPP_EXPORTS_API
#define CPP_API extern "C" __declspec(dllexport)
#else
#define CPP_API __declspec(dllimport)
#endif
static PIXELFORMATDESCRIPTOR pfdScreen3D = {
sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
1, // version number
PFD_DRAW_TO_WINDOW | // support window
PFD_SUPPORT_OPENGL // support OpenGL
| PFD_DOUBLEBUFFER
,
PFD_TYPE_RGBA, // RGBA type
24, // 24-bit color depth
0, 0, 0, 0, 0, 0, // color bits ignored
0, // no alpha buffer
0, // shift bit ignored
0, // no accumulation buffer
0, 0, 0, 0, // accum bits ignored
32, // 32-bit z-buffer
0, // no stencil buffer
0, // no auxiliary buffer
PFD_MAIN_PLANE, // main layer
0, // reserved
0, 0, 0 // layer masks ignored
};
CPP_API int InitOpenGL(int handle)
{
auto ctx = GetDC((HWND) handle);
PIXELFORMATDESCRIPTOR pxfd = pfdScreen3D;
int pixformatnumber = ::ChoosePixelFormat((HDC) ctx, &pxfd);
if (!pixformatnumber)
{
auto er=GetLastError();
exit(er);// Можно выдать сообщение об ошибке, используя GetLastError()
}
::DescribePixelFormat((HDC) ctx, pixformatnumber, sizeof(PIXELFORMATDESCRIPTOR), &pxfd);
// DoubleBufferOff=false;
if (!::SetPixelFormat((HDC) ctx, pixformatnumber, &pxfd)) exit(-1);// Можно выдать сообщение об ошибке, используя GetLastError();
void* OpenGLContext = wglCreateContext((HDC) ctx);
if (!OpenGLContext)exit(-1);// Можно выдать сообщение об ошибке, используя GetLastError();
ReleaseDC((HWND) handle, ctx);
return (int) OpenGLContext;
}
CPP_API void Render(int handle, int oglcontext, int w, int h, int type)
{
if (oglcontext == NULL)return;
auto ctx = GetDC((HWND) handle);
::wglMakeCurrent((HDC) ctx, (HGLRC) oglcontext);
::glViewport(0, 0, w, h);
::glDrawBuffer(GL_BACK);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::glOrtho(0, w, 0, h, -1, 1);
// ::glOrtho(minp.x(),maxp.x(),minp.y(),maxp.y(),minp.z(),maxp.z());
::glMatrixMode(GL_MODELVIEW);
::glLoadIdentity();
::glClearColor(1, 0 , 1, 1);
::glClearDepth(1.0);
::glDepthFunc(GL_LEQUAL);
::glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
::glBegin(GL_LINES);
::glColor3f(1, 0, 0);
if (type)
{
::glVertex2d(0, 0);
::glVertex2d(w,h);
::glVertex2d(0, h);
::glVertex2d(w, 0);
}
else
{
::glVertex2d(0, h/2);
::glVertex2d(w, h/2);
::glVertex2d(w/2, h);
::glVertex2d(w/2, 0);
}
::glEnd();
::glFlush();
::glFinish();
::SwapBuffers((HDC) ctx);
::wglMakeCurrent(0, 0);
ReleaseDC((HWND) handle, ctx);
}
| 5aa47550ce1bd813c9edc43f42054e1ad31326e8 | [
"C#",
"C++"
]
| 2 | C# | Exsidia/DirectX-IIIIIIII | 0547f602c417d1cfb4a99e430af0bebe1e013b6e | a4c9e9dc78b00f3381e9c3154c882f61927c6751 |
refs/heads/master | <repo_name>sarunyou/SetupGulp<file_sep>/gulpfile.js
var browserSync = require('browser-sync').create();
const gulp = require('gulp');
const sass = require('gulp-sass');
const jade = require('gulp-jade');
const data = require('gulp-data');
var plumber = require('gulp-plumber');
var gutil = require('gulp-util');
const optionJade = require('./app/js/variable.js');
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.sass')
.pipe(sass().on('error', gutil.log))
.pipe(gulp.dest('build/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('templates', function() {
gulp.src('app/template/**/*.jade')
.pipe(jade({
pretty: true
}).on('error', gutil.log))
.pipe(gulp.dest('build'))
})
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: 'build',
},
browser: "google-chrome"
})
})
gulp.task('watch', ['browserSync', 'sass'], function() {
gulp.watch('app/scss/**/*.sass', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/template/**/*.jade', ['templates']);
gulp.watch('app/js/**/*.js', browserSync.reload);
})
<file_sep>/README.md
# SetupGulp
-- you need to instann npm before
| 7f6babe72fcb0cddc247a85f91ff79d1945e6452 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | sarunyou/SetupGulp | fe8484c398cfdac6ed1b4cdf0bb7bcd372075a4a | 3bca32d8ee456821358947323e7b54a2ac79b409 |
refs/heads/master | <file_sep># SIMproject
implementation of the SIM project
<file_sep>#include "viewer.h"
#include <math.h>
#include <iostream>
#include <QTime>
using namespace std;
Viewer::Viewer(char *,const QGLFormat &format)
: QGLWidget(format),
_timer(new QTimer(this)),
_currentshader(0),
_light(glm::vec3(0,0,1)),
_motion(glm::vec3(0,0,0)),
_mode(false),
_showShadowMap(false),
//_ndResol(512) {
_ndResol(1024) {
setlocale(LC_ALL,"C");
_grid = new Grid(_ndResol,-1.0f,1.0f);
_cam = new Camera(1.0f,glm::vec3(0.0f,0.0f,0.0f));
_timer->setInterval(10);
connect(_timer,SIGNAL(timeout()),this,SLOT(updateGL()));
}
Viewer::~Viewer() {
delete _timer;
delete _grid;
delete _cam;
for(unsigned int i=0;i<_shaders.size();++i) {
delete _shaders[i];
}
// delete all GPU objects
deleteVAO();
deleteFBO();
deleteExtraTextures();
}
void Viewer::createFBO() {
// FBOs
glGenFramebuffers(1,&_fboTerrain); // 512: Heighmap
glGenFramebuffers(1,&_fboViewport); // viewport: colormap, normalmap, depthmap
// Textures
glGenTextures(1,&_texHeight);
glGenTextures(1,&_texColor);
glGenTextures(1,&_texNormal);
glGenTextures(1,&_texDepth);
}
void Viewer::deleteFBO() {
// FBOs
glDeleteFramebuffers(1,&_fboTerrain);
glDeleteFramebuffers(1,&_fboViewport);
// Textures
glDeleteTextures(1,&_texHeight);
glDeleteTextures(1,&_texColor);
glDeleteTextures(1,&_texNormal);
glDeleteTextures(1,&_texDepth);
}
void Viewer::createVAO() {
const GLfloat quadData[] = {-1.0f,-1.0f,0.0f, 1.0f,-1.0f,0.0f, -1.0f,1.0f,0.0f,
-1.0f,1.0f,0.0f, 1.0f,-1.0f,0.0f, 1.0f,1.0f,0.0f };
// create the VAO associated with the grid (the terrain)
glGenBuffers(2,_terrain);
glGenVertexArrays(1,&_vaoTerrain);
glBindVertexArray(_vaoTerrain);
glBindBuffer(GL_ARRAY_BUFFER,_terrain[0]); // vertices
glBufferData(GL_ARRAY_BUFFER,_grid->nbVertices()*3*sizeof(float),_grid->vertices(),GL_STATIC_DRAW);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void *)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,_terrain[1]); // indices
glBufferData(GL_ELEMENT_ARRAY_BUFFER,_grid->nbFaces()*3*sizeof(int),_grid->faces(),GL_STATIC_DRAW);
// create the VAO associated with the quad
glGenBuffers(1,&_quad);
glGenVertexArrays(1,&_vaoQuad);
glBindVertexArray(_vaoQuad);
glBindBuffer(GL_ARRAY_BUFFER,_quad); // vertices
glBufferData(GL_ARRAY_BUFFER, sizeof(quadData),quadData,GL_STATIC_DRAW);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void *)0);
glEnableVertexAttribArray(0);
}
void Viewer::deleteVAO() {
glDeleteBuffers(2,_terrain);
glDeleteBuffers(1,&_quad);
glDeleteVertexArrays(1,&_vaoTerrain);
glDeleteVertexArrays(1,&_vaoQuad);
}
void Viewer::updateTex(GLuint tex,GLenum filter,GLenum wrap,unsigned int w,
unsigned int h,GLint iformat, GLenum format,bool isShadowmap) {
glBindTexture(GL_TEXTURE_2D,tex);
glTexImage2D(GL_TEXTURE_2D, 0,iformat,w,h,0,format,GL_FLOAT,NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap);
if(isShadowmap) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
}
}
void Viewer::updateFBO() {
// FBO Terrain
// create the noise texture
updateTex(_texHeight,GL_LINEAR,GL_CLAMP_TO_EDGE,_ndResol,_ndResol,GL_RGBA32F,GL_RGBA);
// attach textures to the FBO dedicated to creating the terrain
glBindFramebuffer(GL_FRAMEBUFFER,_fboTerrain);
glBindTexture(GL_TEXTURE_2D,_texHeight);
glFramebufferTexture2D(GL_FRAMEBUFFER_EXT,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,_texHeight,0);
// FBO Viewport
// create the colormap
updateTex(_texColor,GL_LINEAR,GL_CLAMP_TO_EDGE,width(),height(),GL_RGBA32F,GL_RGBA);
// attach textures to the FBO dedicated to the computation phase
glBindFramebuffer(GL_FRAMEBUFFER,_fboViewport);
glBindTexture(GL_TEXTURE_2D,_texColor);
glFramebufferTexture2D(GL_FRAMEBUFFER_EXT,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,_texColor,0);
// creates the normal texture
updateTex(_texNormal,GL_LINEAR,GL_CLAMP_TO_EDGE,width(),height(),GL_RGBA32F,GL_RGBA);
// attach textures to the FBO dedicated to creating the terrain
glBindFramebuffer(GL_FRAMEBUFFER,_fboViewport);
glBindTexture(GL_TEXTURE_2D,_texNormal);
glFramebufferTexture2D(GL_FRAMEBUFFER_EXT,GL_COLOR_ATTACHMENT1,GL_TEXTURE_2D,_texNormal,0);
// creates the depth map
updateTex(_texDepth,GL_LINEAR,GL_CLAMP_TO_EDGE,width(),height(),GL_DEPTH_COMPONENT24,GL_DEPTH_COMPONENT);
// attach textures to the FBO dedicated to creating the terrain
glBindFramebuffer(GL_FRAMEBUFFER,_fboViewport);
glBindTexture(GL_TEXTURE_2D,_texDepth);
glFramebufferTexture2D(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,_texDepth,0);
// test if everything is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
cout << "Warning: FBO[0] not complete!" << endl;
// disable FBO
glBindFramebuffer(GL_FRAMEBUFFER,0);
}
void Viewer::createExtraTextures() {
// Load the color texture
glGenTextures(1,&_colorTexId);
QImage image0 = QGLWidget::convertToGLFormat(QImage("texture/texturemontagne.png"));
glBindTexture(GL_TEXTURE_2D,_colorTexId);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA32F,image0.width(),image0.height(),0,
GL_RGBA,GL_UNSIGNED_BYTE,(const GLvoid *)image0.bits());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
// cloud texture
glGenTextures(1,&_cloudTexId);
QImage image1 = QGLWidget::convertToGLFormat(QImage("texture/cloudMap.jpg"));
glBindTexture(GL_TEXTURE_2D,_cloudTexId);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA32F,image1.width(),image1.height(),0,
GL_RGBA,GL_UNSIGNED_BYTE,(const GLvoid *)image1.bits());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
// water specular texture
glGenTextures(1,&_specularId);
QImage image2 = QGLWidget::convertToGLFormat(QImage("texture/water_specular.jpg"));
glBindTexture(GL_TEXTURE_2D,_specularId);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA32F,image2.width(),image2.height(),0,
GL_RGBA,GL_UNSIGNED_BYTE,(const GLvoid *)image2.bits());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
}
void Viewer::deleteExtraTextures() {
glDeleteTextures(1,&_colorTexId);
glDeleteTextures(1,&_cloudTexId);
}
void Viewer::createShaders() {
// *** height field ***
_vertexFilenames.push_back("shaders/noise.vert");
_fragmentFilenames.push_back("shaders/noise.frag");
// ******************************
_vertexFilenames.push_back("shaders/show-terrain.vert");
_fragmentFilenames.push_back("shaders/show-terrain.frag");
_vertexFilenames.push_back("shaders/displace-terrain.vert");
_fragmentFilenames.push_back("shaders/displace-terrain.frag");
_vertexFilenames.push_back("shaders/final-renderer.vert");
_fragmentFilenames.push_back("shaders/final-renderer.frag");
}
void Viewer::createHeightMap(GLuint id) {
// send the motion vector
glUniform3fv(glGetUniformLocation(id,"motion"),1,&(_motion[0]));
// draw the quad
glBindVertexArray(_vaoQuad);
glDrawArrays(GL_TRIANGLES,0,6);
glBindVertexArray(0);
}
void Viewer::drawSceneFromCamera(GLuint id) {
// create gbuffers (deferred shading)
// Send uniform variables (view matrix)*
// send the light
glUniform3fv(glGetUniformLocation(id,"light"),1,&(_light[0]));
glUniformMatrix4fv(glGetUniformLocation(id,"mdvMat"),1,GL_FALSE,&(_cam->mdvMatrix()[0][0]));
glUniformMatrix4fv(glGetUniformLocation(id,"projMat"),1,GL_FALSE,&(_cam->projMatrix()[0][0]));
glUniformMatrix3fv(glGetUniformLocation(id,"normalMat"),1,GL_FALSE,&(_cam->normalMatrix()[0][0]));
// send the animation clock
glUniform1f(glGetUniformLocation(id,"animTimer"),(_animTimer));
// Send color texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,_colorTexId);
glUniform1i(glGetUniformLocation(id,"colormap"),0);
// Send cloud texture
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D,_cloudTexId);
glUniform1i(glGetUniformLocation(id,"cloud"),1);
// Send noisemap
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D,_texHeight);
glUniform1i(glGetUniformLocation(id,"noisemap"),2);
// Send specular
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D,_specularId);
glUniform1i(glGetUniformLocation(id,"specmap"),3);
glBindVertexArray(_vaoTerrain);
glDrawElements(GL_TRIANGLES,3*_grid->nbFaces(),GL_UNSIGNED_INT,(void *)0);
glBindVertexArray(0);
}
void Viewer::drawSceneFromLight(GLuint id) {
// create shadowmap
}
void Viewer::renderFinalImage(GLuint id) {
// send the light
glUniform3fv(glGetUniformLocation(id,"light"),1,&(_light[0]));
// Send vawe texture
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D,_texWave);
glUniform1i(glGetUniformLocation(id,"vaweTexture"),3);
// send the textures
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,_texColor);
glUniform1i(glGetUniformLocation(id,"colormap"),0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D,_texNormal);
glUniform1i(glGetUniformLocation(id,"normalmap"),1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D,_texDepth);
glUniform1i(glGetUniformLocation(id,"depthmap"),2);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D,_specularId);
glUniform1i(glGetUniformLocation(id,"specmap"),3);
// Geometry: rectangle
glBindVertexArray(_vaoQuad);
glDrawArrays(GL_TRIANGLES,0,6);
glBindVertexArray(0);
}
void Viewer::pass1() {
glBindFramebuffer(GL_FRAMEBUFFER,_fboTerrain);
// draw into the first buffer
glDrawBuffer(GL_COLOR_ATTACHMENT0);
// viewport at the size of the heightmap
glViewport(0,0,_ndResol,_ndResol);
// disable depth test
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
// clear color buffer
glClear(GL_COLOR_BUFFER_BIT);
// activate the noise shader
glUseProgram(_shaders[0]->id());
// generate the noise texture
createHeightMap(_shaders[0]->id());
// restore previous state
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
}
void Viewer::pass2() {
glBindFramebuffer(GL_FRAMEBUFFER,_fboViewport);
// We want to draw into FBO!!!
GLenum toPrint[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_DEPTH_ATTACHMENT};
glDrawBuffers(2, toPrint);
// restore viewport sizes
glViewport(0,0,width(),height());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(_shaders[2]->id());
drawSceneFromCamera(_shaders[2]->id());
}
void Viewer::pass3() {
// TODO
}
void Viewer::pass4() {
// disable shader
glBindFramebuffer(GL_FRAMEBUFFER,0);
// restore viewport sizes
glViewport(0,0,width(),height());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// activate the buffer shader
glUseProgram(_shaders[3]->id());
//testShowDisp(_shaders[2]->id());
renderFinalImage(_shaders[3]->id());
}
void Viewer::paintGL() {
int freq = 1;
// PASS 1 : Generate noise
pass1();
// PASS 2 : Compute the texture buffers (normals, colors, depth)
pass2();
// PASS 3 : Create the shadowmap (depth from the point of view of light)
pass3();
// PASS 4 : Final render VII
pass4();
// Timer for animations!
_globaltimer++;
if( _globaltimer % freq == 0){
_animTimer += 0.01;
}
glUseProgram(0);
}
void Viewer::resizeGL(int width,int height) {
_cam->initialize(width,height,false);
glViewport(0,0,width,height);
updateFBO();
updateGL();
}
void Viewer::mousePressEvent(QMouseEvent *me) {
const glm::vec2 p((float)me->x(),(float)(height()-me->y()));
if(me->button()==Qt::LeftButton) {
_cam->initRotation(p);
_mode = false;
} else if(me->button()==Qt::MidButton) {
_cam->initMoveZ(p);
_mode = false;
} else if(me->button()==Qt::RightButton) {
_light[0] = (p[0]-(float)(width()/2))/((float)(width()/2));
_light[1] = (p[1]-(float)(height()/2))/((float)(height()/2));
_light[2] = 1.0f-std::max(fabs(_light[0]),fabs(_light[1]));
_light = glm::normalize(_light);
_mode = true;
}
updateGL();
}
void Viewer::mouseMoveEvent(QMouseEvent *me) {
const glm::vec2 p((float)me->x(),(float)(height()-me->y()));
if(_mode) {
// light mode
_light[0] = (p[0]-(float)(width()/2))/((float)(width()/2));
_light[1] = (p[1]-(float)(height()/2))/((float)(height()/2));
_light[2] = 1.0f-std::max(fabs(_light[0]),fabs(_light[1]));
_light = glm::normalize(_light);
} else {
// camera mode
_cam->move(p);
}
updateGL();
}
void Viewer::keyPressEvent(QKeyEvent *ke) {
const float step = 0.05;
if(ke->key()==Qt::Key_Z) {
glm::vec2 v = glm::vec2(glm::transpose(_cam->normalMatrix())*glm::vec3(0,0,-1))*step;
if(v[0]!=0.0 && v[1]!=0.0) v = glm::normalize(v)*step;
else v = glm::vec2(0,1)*step;
_motion[0] += v[0];
_motion[1] += v[1];
}
if(ke->key()==Qt::Key_S) {
glm::vec2 v = glm::vec2(glm::transpose(_cam->normalMatrix())*glm::vec3(0,0,-1))*step;
if(v[0]!=0.0 && v[1]!=0.0) v = glm::normalize(v)*step;
else v = glm::vec2(0,1)*step;
_motion[0] -= v[0];
_motion[1] -= v[1];
}
if(ke->key()==Qt::Key_Q) {
_motion[2] += step;
}
if(ke->key()==Qt::Key_D) {
_motion[2] -= step;
}
// key a: play/stop animation
if(ke->key()==Qt::Key_A) {
if(_timer->isActive())
_timer->stop();
else
_timer->start();
}
// key i: init camera
if(ke->key()==Qt::Key_I) {
_cam->initialize(width(),height(),true);
}
// key f: compute FPS
if(ke->key()==Qt::Key_F) {
int elapsed;
QTime timer;
timer.start();
unsigned int nb = 500;
for(unsigned int i=0;i<nb;++i) {
paintGL();
}
elapsed = timer.elapsed();
double t = (double)nb/((double)elapsed);
cout << "FPS : " << t*1000.0 << endl;
}
// key r: reload shaders
if(ke->key()==Qt::Key_R) {
for(unsigned int i=0;i<_vertexFilenames.size();++i) {
_shaders[i]->reload(_vertexFilenames[i].c_str(),_fragmentFilenames[i].c_str());
}
}
// key S: show the shadow map
if(ke->key()==Qt::Key_S) {
_showShadowMap = !_showShadowMap;
}
updateGL();
}
void Viewer::initializeGL() {
// make this window the current one
makeCurrent();
// init and chack glew
if(glewInit()!=GLEW_OK) {
cerr << "Warning: glewInit failed!" << endl;
}
if(!GLEW_ARB_vertex_program ||
!GLEW_ARB_fragment_program ||
!GLEW_ARB_texture_float ||
!GLEW_ARB_draw_buffers ||
!GLEW_ARB_framebuffer_object) {
cerr << "Warning: Shaders not supported!" << endl;
}
// init OpenGL settings
glClearColor(0.0,0.0,0.0,1.0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glViewport(0,0,width(),height());
// initialize camera
_cam->initialize(width(),height(),true);
// load shader files
createShaders();
// init and load all shader files
for(unsigned int i=0;i<_vertexFilenames.size();++i) {
_shaders.push_back(new Shader());
_shaders[i]->load(_vertexFilenames[i].c_str(),_fragmentFilenames[i].c_str());
}
// init shaders
createShaders();
// init VAO/VBO
createVAO();
// create/init FBO
createFBO();
updateFBO();
createExtraTextures();
// starts the timer
_timer->start();
_animTimer = 0;
_globaltimer = 0;
_isAnimForward = 1;
}
| d265bdd975f36f2dfcb4d9ac7c9c261142e076e8 | [
"Markdown",
"C++"
]
| 2 | Markdown | PierreBanwarth/SIMproject | 916c175bed9645d7cbda93d3b15aa80acdc16e72 | 7b0b568f846880b8414982468434710ff9befced |
refs/heads/master | <repo_name>MartinL123/07-07-2020<file_sep>/Ruby_07-07-2020/exo_14.rb
puts "Donne moi un nombre Narvalo"
print ">"
number = gets.chomp.to_i
number.times do |i|
puts "#{number - i }"
end
puts "0"<file_sep>/Ruby_07-07-2020/exo_20.rb
user_number = 0
puts "Salut, bienvenue dans ma super pyramide ! Combien d'étages veux-tu ?"
until user_number.between?(1,25)
print ">"
user_number = gets.chomp.to_i
if user_number < 1
puts "ça va pas le faire ça..."
elsif user_number > 25
puts "T'en a trop mis gros !"
else
puts "Good choice !"
end
end
for n in 1.. user_number
puts "" * (user_number - n) + "#" * n
end<file_sep>/Ruby_07-07-2020/exo_19.rb
i = 1
emails_list = Array.new()
while (i <= 50)
if (i < 10)
email = "Christine.<EMAIL>"
else
email = "<EMAIL>"
end
emails_list.push(email)
if (i.to_i.even?)
puts email
end
i = i+1
end<file_sep>/Ruby_07-07-2020/exo_11.rb
puts "Bonjour, peux-tu me donner un chiffre?"
print ">"
number = gets.chomp.to_i
number.times do
puts "Salut ça farte?"
end<file_sep>/Ruby_07-07-2020/exo_16.rb
puts "Quel est ton année de naissance?"
print ">"
birthdate = gets.chomp.to_i
date2020 = 2020
difference = date2020 - birthdate
difference.times do |i|
puts "il y a #{difference-i} ans tu avais #{i} an(s)"
end
puts "il y a 0 an tu avais #{difference} an(s)"<file_sep>/Ruby_07-07-2020/exo_07.rb
puts "Bonjour, c'est quoi ton blase ?"
user_name = gets.chomp
puts user_name
#Pose une question et l'utilisateur doit répondre
<file_sep>/Ruby_07-07-2020/exo_13.rb
puts "Quel est ton année de naissance?"
print ">"
birthdate = gets.chomp.to_i
date2020 = 2020
difference = date2020 - birthdate
difference.times do |i|
puts "#{birthdate+i}"
end
puts "#{date2020}"<file_sep>/Ruby_07-07-2020/exo_17.rb
puts "Quel est ton année de naissance?"
print ">"
birthdate = gets.chomp.to_i
date2020 = 2020
difference = date2020 - birthdate
difference.times do |i|
puts "il y a #{difference-i} ans tu avais #{i} an(s)"
if
else
end
end
puts "il y a 0 an tu avais #{difference} an(s)"<file_sep>/Ruby_07-07-2020/exo_12.rb
puts "Choisis un nombre et je vais compter jusqu'à celui-ci Morray"
print ">"
number=gets.chomp.to_i
number.times do |i|
puts "#{i+1}"
end | 16600d6785e9622181871e35f9ed2d80848a6ec3 | [
"Ruby"
]
| 9 | Ruby | MartinL123/07-07-2020 | 3f5ad643028be32f1598e24e279ff4a6411599f0 | 0fb7f6a4997679161424f8bdb9c03078018749cc |
refs/heads/master | <repo_name>cary1234/Game_Subscription<file_sep>/Game_Subscription/nbproject/project.properties
file.reference.Projects-Game_Subscription=.
files.encoding=UTF-8
site.root.folder=${file.reference.Projects-Game_Subscription}
<file_sep>/Game_Subscription/about-us.php
<?php require("navbar.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Game Subscription - About Us</title>
<link rel="shortcut icon" href="images/icon_gomeco.ico">
<link rel="stylesheet" href="css/panelTab.css">
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css"><!-- Bootstrap core CSS -->
<link rel="stylesheet" href="css/styles.css"><!--Personal CSS-->
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script><!-- Jquery -->
</head>
<body>
<br><br>
<br><br>
<div class="container">
<div class="row">
<div class="col-md-12 col-md-offset-0">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">About Us</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active"><a href="#tab1" data-toggle="tab">About Us</a></li>
<!--
<li><a href="#tab2" data-toggle="tab">Subscriptions</a></li>
-->
</ul>
</span>
</div>
<div class="panel-body col-md-offset-0">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="col-md-12">
<div class="row">
<div class="col-sm-6">
<img class="img-responsive" src="images/about_company_logo.jpg" width='520' height='360'
onerror="this.src='images/default_QK.png';">
</div>
<div class="col-sm-6">
<p align="justify">
<strong>IP E-Games</strong><br><br>
IP E-Games, also known as E-Games, is the leading online game publisher in the Philippines under IPVG Corporation. IP E-Games is also an F2P(Free-To-Play)-based-company, meaning every one can play their titles freely also they ceased all operations in line with their merger with Level Up! Games Incorporated (Under licence of Playweb Games Inc.).
<br><br>
For any inquiries call us at 09351445091 or 09351167360, or email us at <EMAIL>
</p>
<br><br>
</div>
<div class="col-sm-2">
<img class="img-responsive" src="images/about_picture-1.jpg"
width='150' height='130' onerror="this.src='images/default_QK.png';">
</div>
<div class="col-sm-2">
<img class="img-responsive" src="images/about_picture-2.jpg"
width='150' height='130' onerror="this.src='images/default_QK.png';">
</div>
<div class="col-sm-2">
<img class="img-responsive" src="images/about_picture-3.jpg"
width='150' height='130' onerror="this.src='images/default_QK.png';">
</div>
</div>
</div>
</div>
<!--
<div class="tab-pane" id="tab2">
<div class="col-md-12">
<div class="row">
<div class="col-sm-6">
<img class="img-responsive" src="images/default_QK.png" width='520' height='320'
onerror="this.src='images/default_QK.png';">
</div>
<div class="col-sm-6">
<p align="justify">
<strong>
Lorem ipsum dolor sit amet,
</strong>
<br><br>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Perferendis sit iusto omnis aliquid nesciunt atque nostrum
maiores culpa quisquam voluptates? Perferendis sit iusto
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Perferendis sit iusto omnis aliquid nesciunt atque nostrum
maiores culpa quisquam voluptates? Perferendis sit iusto
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Perferendis sit iusto omnis aliquid nesciunt atque nostrum
maiores culpa quisquam voluptates? Perferendis sit iusto.
</p>
<br><br>
<a href="products.php" class="btn btn-primary btn-lg center-block">
Subscribe Now!
</a>
</div>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="js/bootstrap.js"></script>
</body>
</html><file_sep>/Game_Subscription/index.php
<?php require("navbar.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<div name="top"></div>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Subscription - Home Page</title>
<link href="css/bootstrap.css" rel="stylesheet"><!-- Bootstrap Core -->
<link href="css/carousel.css" rel="stylesheet"><!-- Carousel -->
<link href="css/spacer.css" rel="stylesheet"><!-- Spacer -->
<link href="css/styles.css" rel="stylesheet"><!-- Personal CSS -->
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row spacer">
</div>
<?php require_once("carousel_index.php"); ?>
<div class="row spacer">
</div>
<div class="container marketing">
<div class="container-fluid">
<div class="row-fluid">
<div class="col-xs-4">
<img class="img-responsive" src="images/Feature_Logo.jpg" />
</div>
<div class="col-xs-8">
<img class="img-responsive" src="images/Feature_Banner.jpg" />
</div>
</div>
</div>
<div class="row spacer">
</div>
<!-- Three columns of text below the carousel -->
<div class="row">
<div class="col-sm-4">
<img class="img-circle img-responsive center-block" src="images/customer_1.jpg" alt="Generic placeholder image" style="width: 140px; height: 140px;">
<h2 class="text-center">Intense</h2>
<p class="text-justify">"Your games are awesome! So intense that I can't stop myself from playing it."</p>
</div>
<div class="col-sm-4">
<img class="img-circle img-responsive center-block" src="images/customer_2.jpg" alt="Generic placeholder image" style="width: 140px; height: 140px;">
<h2 class="text-center">Heartwarming</h2>
<p class="text-justify">"It moved me when I play your RPG games! It feels like I'm in the actual game, thanks!"</p>
</div><!-- /.col-lg-4 -->
<div class="col-sm-4">
<img class="img-circle img-responsive center-block" src="images/customer_3.jpg" alt="Generic placeholder image" style="width: 140px; height: 140px;">
<h2 class="text-center">Secured</h2>
<p class="text-justify">"I totally feel secured whenever I top up my cards, thanks to the security of your website."</p>
</div><!-- /.col-lg-4 -->
</div><!-- /.row -->
<!-- START THE FEATURETTES -->
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-7">
<h2 class="featurette-heading">600 Pesos
<br />
<span class="text-muted">
3 Months Subscription
</span>
</h2>
<p class="lead">3 months subscription is equivalent to 90 days, which will cost you 600 PHP. Concentrate on playing your games and don't be afraid to win!</p>
</div>
<div class="col-md-5">
<img class="featurette-image img-responsive" src="images/featurette_1.jpg" alt="Generic placeholder image">
</div>
</div>
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-5">
<img class="featurette-image img-responsive" src="images/featurette_2.jpg" alt="Generic placeholder image">
</div>
<div class="col-md-7">
<h2 class="featurette-heading">1,000 Pesos
<br />
<span class="text-muted">
6 Months Subscription
</span>
</h2>
<p class="lead">6 months subscription is equivalent to 180 days, which will cost you 1,000 PHP. Life is a game, all you need to do is to know how to play it.</p>
</div>
</div>
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-7">
<h2 class="featurette-heading">1,500 Pesos
<br />
<span class="text-muted">
1 Year Subscription
</span>
</h2>
<p class="lead">1 year subscription if equivalent to 365 days, which will cost you 1,500 PHP. If you have a good time playing the game, you're a winner even if you lose!</p>
</div>
<div class="col-md-5">
<img class="featurette-image img-responsive" src="images/featurette_3.jpg" alt="Generic placeholder image">
</div>
</div>
<!-- /END THE FEATURETTES -->
</div>
</div>
<?php require_once("modal_index.php"); ?>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
<script src="js/smooth-scroll.js"></script><!--This is the function for the going back to top-->
<script src="js/holder.js"></script><!--This is to hold images like the one in the header (140x140)-->
<?php require("footer.php"); ?>
</body>
</html><file_sep>/Game_Subscription/subscription_points.php
<?php
session_start();
require_once ('config.php');
$points_convert = filter_input(INPUT_POST, 'points_convert');
$users_id = $_SESSION['id'];
$dbh = mysqli_connect($host, $username, $password, $database) or die("Error " . mysqli_error($dbh));
$stmt = $dbh->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
$stmt->bind_param("s", $users_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$prev_points_rec = $row['points'];
$prev_subscription_rec = $row['rem_subscription'];
$row_cnt = mysqli_num_rows($result);
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
//
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if ($prev_points_rec < 30) {
$errors['points_convert'] = 'Not enough points';
}
if (($points_convert == 'convert_60') && ($prev_points_rec < 60)) {
$errors['points_convert'] = 'Not enough points';
}
if (($points_convert == 'convert_90') && ($prev_points_rec < 90)) {
$errors['points_convert'] = 'Not enough points';
}
if ($points_convert == "convert_0") {
$errors['points_convert'] = 'Please select convertion.';
}
if ($row_cnt == 0) {
$errors['query'] = 'Invalid card, please try again.';
}
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
if ($points_convert == 'convert_30') {
$subs_reward = "30";
$points_deduct = "30";
} else if ($points_convert == 'convert_60') {
$subs_reward = "65";
$points_deduct = "60";
} else if ($points_convert == 'convert_90') {
$subs_reward = "100";
$points_deduct = "90";
} else {
$subs_reward = "0";
$points_deduct = "0";
}
$total_rem_subs = $prev_subscription_rec + $subs_reward;
$total_points = $prev_points_rec - $points_deduct;
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = $points_deduct . " points successfully converted to " . $subs_reward . " days subscription!";
$data['subs_status'] = $total_rem_subs;
$data['points_status'] = $total_points;
$query_users = "UPDATE users SET rem_subscription='$total_rem_subs', points='$total_points' WHERE id = '$users_id' ";
mysqli_query($dbh, $query_users);
date_default_timezone_set("Asia/Taipei");
$date = date('M d, Y H:i:s');
$user_id = ($_SESSION['id']);
$action = "INSERT INTO actions(user_id,action,Date_Time) values ('$user_id','Converted $points_deduct points to $subs_reward days of subscription','$date')";
$action_result = mysqli_query($dbh, $action);
}
// return all our data to an AJAX call
echo json_encode($data);
<file_sep>/Game_Subscription/signup_result.php
<?php require("navbar.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<div name="top"></div>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Subscription - Signup</title>
<link href="css/bootstrap.css" rel="stylesheet"><!-- Bootstrap Core -->
<link href="css/carousel.css" rel="stylesheet"><!-- Carousel -->
<link href="css/spacer.css" rel="stylesheet"><!-- Spacer -->
<link href="css/styles.css" rel="stylesheet"><!-- Personal CSS -->
</head>
<body>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="container">
<div class="col-md-12">
<?php
include ('config.php');
$error = array(); //Declare An Array to store any error message
if (empty($_POST['fname']) or empty($_POST['lname'])) {//if no name has been supplied
$error[] = 'Please Enter a name '; //add to array "error"
} else {
$fname = $_POST['fname']; //else assign it a variable
$lname = $_POST['lname']; //else assign it a variable
}
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
//regular expression for email validation
$email = mysqli_real_escape_string($db_link, strip_tags(stripslashes($_POST['email'])));
} else {
$error[] = 'Your Email Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} elseif ($_POST['password'] != $_POST['confirmpassword']) {
$error[] = 'The Password You Enter Do Not Match ';
} else {
$password = mysqli_real_escape_string($db_link, strip_tags(stripslashes($_POST['password'])));
function generateRandomString($length = 10) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$rand = generateRandomString(); //Generates 10 random characters
$str = substr($rand, 0, 6); //Shortens the 10 random generated string to 6
$salt = <PASSWORD>' . $str . '$'; //Creates a random salt (DO NOT CHANGE THIS VERY IMPORTANT)
//You can how ever change the part where is says 07 to 12 you can use 1 - 12 [12 being more secure and 1 being least secure]
//How ever the more secure it is - the slower it will take to generate the hash
//When you use 1 - 9 make sure to put a 0 infront of e.g 6 will be 06 :D
$cryptpass = crypt($password, $salt); //Hashes the password they entered!
}
if (empty($error)) {//send to Database if there's no error '
// If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM users WHERE email ='$email'";
$result_verify_email = mysqli_query($db_link, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
?>
<h3 class="text-center text-danger">
An error occurred, please try again.
</h3>
<?php
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = "activated"; //md5(uniqid(rand(), true));
$accesstype = $_POST['accesstype'];
$query_insert_user = "INSERT INTO `users` (`fname`, `lname`, `email`, `password`, `salt`, `activation`, `access`) VALUES ( '$fname', '$lname', '$email', '$cryptpass', '$salt', '$activation', '$accesstype')" or die("Error" . mysqli_errno($db_link));
$result_insert_user = mysqli_query($db_link, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed';
}
if (mysqli_affected_rows($db_link) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n" . "http://localhost/projects/Game_Subscription/" . "activate.php?email=" . urlencode($email) . "&key=" . $activation . "\n\n If the url above is not clickable, kindly copy the url and paste it to the address bar.";
mail($email, 'Quickitchen - Confirm Email', $message, 'From: Quickitchen Admin');
date_default_timezone_set("Asia/Taipei");
$date = date('M d, Y H:i:s');
if (isset($_SESSION['id'])) {
$user_id = ($_SESSION['id']);
$action = "INSERT INTO actions(user_id,action,Date_Time) values ('$user_id','Registered $email','$date')";
$action_result = mysqli_query($db_link, $action);
}
// Flush the buffered output.
// Finish the page:
?>
<h3 class="text-center text-success">
<!-- Thank you for registering! A confirmation email has been sent to <?php echo $email ?></br>Please click on the Activation Link to Activate your account. -->
Thank you for registering!<br>Please sign in <a href="signin_form.php">here</a>
</h3>
<?php
} else { // If it did not run OK.
?>
<h3 class="text-center text-danger">
You could not be registered due to a system error. We apologize for any inconvenience.
</h3>
<?php
}
} else { // The email address is not available.
?>
<h3 class="text-center text-danger">
The email address you entered is not available. Sorry. Please try again.
</h3>
<?php
}
} else {//If the "error" array contains error msg , display them
if (!isset($_SESSION['access'])) {
require("timer_index.php");
} elseif ($_SESSION['access'] == "root") {
header("Location: admin_lists.php");
} else {
require("timer_index.php");
}
?>
<div class="errormsgbox text-center"><?php
foreach ($error as $key => $values) {
echo $values;
}
?>
</div><?php
}
mysqli_close($db_link); //Close the DB Connection
?>
</h3>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
<script src="js/smooth-scroll.js"></script><!--This is the function for the going back to top-->
<script src="js/holder.js"></script><!--This is to hold images like the one in the header (140x140)-->
</body>
</html><file_sep>/Game_Subscription/PayPal/ipn.php
<?php
session_start();
require_once ('../config.php');
$db_link = mysqli_connect($host, $username, $password, $database);
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs($fp, $header . $req);
while (!feof($fp)) {
$res = fgets($fp, 1024);
if (strcmp($res, "VERIFIED") == 0) {
$users_id = $_SESSION['id'];
$stmt = $dbh->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
$stmt->bind_param("s", $users_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$subs_type_rec = $row['subs_type'];
$prev_subscription_rec = $row['rem_subscription'];
if ($subs_type_rec == '1') {
$subs_type = "90";
} else if ($row['subs_type' == '2']) {
$subs_type = "180";
} else if ($row['subs_type' == '3']) {
$subs_type = "365";
} else {
$subs_type = "Error";
}
$total_rem_subs = $subs_type + $prev_subscription_rec;
$query_users = "UPDATE users SET rem_subscription='$total_rem_subs' WHERE id = '$users_id' ";
mysqli_query($dbh, $query_users);
// PAYMENT VALIDATED & VERIFIED!
} else if (strcmp($res, "INVALID") == 0) {
// PAYMENT INVALID & INVESTIGATE MANUALY!
}
}
fclose($fp);
}<file_sep>/Game_Subscription/config.php
<?php
/*
$host = "172.16.58.3";
$username ="a3925237_admin1";
$password = "<PASSWORD>";
$database = "a3925237_game";
*/
$host = "localhost";
$username ="root";
$password = "";
$database = "game_subscription";
$db_link = mysqli_connect($host, $username, $password, $database) or die("Error " . mysqli_error($db_link));
<file_sep>/Game_Subscription/admin_card_modal.php
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form role="form" name="loginForm" id="loginForm" method="post" action="admin_card_register.php">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Create Card</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<?php
require_once 'config.php';
$stmt = $db_link->prepare("SELECT * FROM subs_card ORDER BY id DESC
LIMIT 1");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$last_row = $row['id'];
$card_no = str_pad($last_row + 1, 16, '0', STR_PAD_LEFT);
?>
<div class="form-group">
<input type="text" readonly="" class="form-control input-lg" tabindex="1" value="<?php echo $card_no; ?>" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<input type="text" minlength="4" maxlength="4" required name="pin_no" id="pin_no" class="form-control input-lg" placeholder="Enter Pin #" tabindex="1">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<select name="subs_type" name="subs_type" id="subs_type" class="form-control">
<option value="1">90 Days</option>
<option value="2">180 Days</option>
<option value="3">365 Days</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Create Card</button>
</div>
</form>
</div>
</div><file_sep>/Game_Subscription/subscription.php
<?php require("navbar.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<div name="top"></div>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Subscription - Subscription</title>
<link href="css/bootstrap.css" rel="stylesheet"><!-- Bootstrap Core -->
<link href="css/carousel.css" rel="stylesheet"><!-- Carousel -->
<link href="css/spacer.css" rel="stylesheet"><!-- Spacer -->
<link href="css/styles.css" rel="stylesheet"><!-- Personal CSS -->
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row spacer"></div>
<div class="row spacer"></div>
<div class="row spacer"></div>
<?php
require_once("config.php");
$db_link = mysqli_connect($host, $username, $password, $database);
if (!isset($_SESSION['id'])) {
} else {
$query = "SELECT fname, lname, rem_subscription, points, image_path FROM users WHERE id = " . "'" . $_SESSION['id'] . "'" . " LIMIT 1";
$result = mysqli_query($db_link, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="container text-center">
<div class="row">
<div class="col-md-12">
<div class="col-md-3">
<h2>
<img class="img-circle" src="<?php echo $row['image_path']; ?>" onerror="this.src='images/default_picture.jpg';" width="160" height="180"><br>
<?php echo $row['fname'] . " " . $row['lname']; ?>
<span class="text-muted">
<h3 id="subs-status_group">
<?php
if (!$row['rem_subscription']) {
echo "<p id='subs_status'>You does not have any subscription</p>";
} else {
echo "<p id='subs_status'>You have " . $row['rem_subscription'] . " days of subscription.</p>";
}
?>
</h3>
</span>
</h2>
</div>
<div class="col-md-3">
<span class="text-muted">
<h3 id="points-status_group">
<?php
if (!$row['points']) {
echo "<p class='text-danger' id='points_status'>0 Points</p>";
} else {
echo "<p class='text-success' id='points_status'>" . $row['points'] . " Points</p>";
}
?>
</h3>
</span>
<form id="points_convert" action="subscription_points.php" method="POST">
<div id="points-no_group" class="form-group">
<select class="form-control" id="searchType" name="points_convert">
<option value="convert_0">Convert the Points</option>
<option value="convert_30">30 Points = Free 30 Days</option>
<option value="convert_60">60 Points = Free 65 Days</option>
<option value="convert_90">90 Points = Free 100 Days</option>
</select>
<br>
<button type="submit" class="btn btn-success">Convert<span class="fa fa-arrow-right"></span></button>
</div>
</form>
</div>
<div id="game-status_group" class="col-md-6">
<?php
if ($row['rem_subscription'] <= "0") {
echo "<div id='game_status'><h2 class='text-danger'>You does not have any subscription.<br/>Please subscribe to play games.</h2></div>";
} else {
?>
<div id="game_status">
<div class="row">
<h2>
Games:
</h2>
</div>
<div class="row">
<h4>
<a href="games\game-off-2012\index.php" target="_blank">Game Off</a>
</h4>
</div>
<div class="row">
<h4>
<a href="games\CrappyBird\index.php" target="_blank">Crappy Bird</a>
</h4>
</div>
<div class="row">
<h4>
<a href="games\AlienInvasion\index.php" target="_blank">Alien Invasion</a>
</h4>
</div>
</div><?php
}
?>
</div>
</div>
</div>
<div class="row spacer"></div>
<div class="row">
<div class="col-md-6">
<div class="col-md-6">
<form id="card_subs" action="subscription_result.php" method="POST">
<!--Card Number-->
<div id="card-no_group" class="form-group">
<label for="card_no">Card Number</label>
<input minlength="16" maxlength="16" type="text" class="form-control" required name="card_no" placeholder="XXXXXXXXXXXXXXXX">
<!-- errors will go here -->
</div>
<!--Pin Number-->
<div id="pin-no_group" class="form-group">
<label for="pin_no">Pin Number</label>
<input type="text" minlength="4" maxlength="4" class="form-control" required name="pin_no" placeholder="XXXX">
<!-- errors will go here -->
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
</div>
<div class="col-md-6">
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="NS7WC3SKY3ZZL">
<table>
<tr><td><input type="hidden" name="on0" value="Subscriptions">Subscriptions</td></tr><tr><td><select name="os0">
<option value="3 Months">3 Months P600.00 PHP</option>
<option value="6 Months">6 Months P1,000.00 PHP</option>
<option value="12 Months">12 Months P1,500.00 PHP</option>
</select> </td></tr>
</table>
<input type="hidden" name="currency_code" value="PHP">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
</div>
</div>
<?php
}
}
?>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
<script src="js/holder.js"></script><!--This is to hold images like the one in the header (140x140)-->
<script src="js/subscription_ajax.js"></script> <!-- load our javascript file -->
<script src="js/subscription_points.js"></script> <!-- load our javascript file -->
</body>
</html>
<file_sep>/nbproject/private/private.properties
index.file=index.php
url=http://localhost/Game_Subscription/
<file_sep>/Game_Subscription/games/game-off-2012/index.php
<?php
session_start();
$access = $_SESSION['access'];
if (isset($access)) {
} else {
header('Location: ../../not_allowed.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link media="screen" href="css/main.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico">
<link rel="apple-touch-icon" sizes="114x114" href="img/touch-icon-114x114.png" />
<link rel="apple-touch-icon" sizes="72x72" href="img/touch-icon-72x72.png" />
<link rel="apple-touch-icon" href="img/touch-icon-iphone.png" />
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/gamejs/yabble.js"></script>
<script type="text/javascript" src="js/gamejs/gamejs.min.js"></script>
<script type="text/javascript" src="js/lib/utils.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var gamejs;
require.setModuleRoot('./js/');
require.run('main');
});
</script>
<title>Alge's Escapade</title>
</head>
<body>
<div id="preload">
<img src="img/loading.gif" />
<img src="img/loading-text.png" />
</div>
<div id="gameWindow">
<canvas id="gjs-canvas"></canvas>
<div id="gameEnd"></div>
</div>
</body>
</html><file_sep>/Game_Subscription/signin_result.php
<?php require("navbar.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<div name="top"></div>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Subscription - Sign In</title>
<link href="css/bootstrap.css" rel="stylesheet"><!-- Bootstrap Core -->
<link href="css/carousel.css" rel="stylesheet"><!-- Carousel -->
<link href="css/spacer.css" rel="stylesheet"><!-- Spacer -->
<link href="css/styles.css" rel="stylesheet"><!-- Personal CSS -->
</head>
<body>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="container">
<div class="col-md-12">
<h3 class="text-center text-danger">
<?php
include ('config.php');
// Initialize a session:
$error = array(); //this aaray will store all error messages
if (empty($_POST['email'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
$email = mysqli_real_escape_string($db_link, strip_tags(stripslashes($_POST['email'])));
} else {
$error[] = 'Your Email Address is invalid ';
}
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = mysqli_real_escape_string($db_link, strip_tags(stripslashes($_POST['password'])));
}
if (empty($error)) { //if the array is empty , it means no error found
$query = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($db_link, $query);
$row = mysqli_fetch_assoc($result);
$get_email = $row['email'];
$get_password = $row['password'];
$get_salt = $row['salt'];
//This is vital for Bcyrpt to work so leave it!
if (CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
//This is hashing the password with the salt we used. The salt is generated on the register page!
$cryptpass = crypt($password, $get_salt);
$query_check_credentials = "SELECT * FROM users WHERE (email='$email' AND password='$<PASSWORD>') AND Activation='activated'";
$result_check_credentials = mysqli_query($db_link, $query_check_credentials);
if (!$result_check_credentials) {//If the QUery Failed
echo 'Query Failed ';
}
if (@mysqli_num_rows($result_check_credentials) == 1) { //if Query is successfull
// A match was made.
//Assign the result of this query to SESSION Global Variable
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
header("Location: index.php");
date_default_timezone_set("Asia/Taipei");
$date = date('M d, Y H:i:s');
$user_id = ($_SESSION['id']);
$action = "INSERT INTO actions(user_id,action,Date_Time) values ('$user_id','Sign in','$date')";
$action_result = mysqli_query($db_link, $action);
} else {
$msg_error = 'Either Your Account is inactive or Email address / Password is Incorrect.</br>Please try again.';
}
} else {
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
if (isset($msg_error)) {
echo '<div class="warning">' . $msg_error . ' </div>';
}
/// var_dump($error);
mysqli_close($db_link);
?>
</h3>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
<script src="js/smooth-scroll.js"></script><!--This is the function for the going back to top-->
<script src="js/holder.js"></script><!--This is to hold images like the one in the header (140x140)-->
</body>
</html>
<file_sep>/Game_Subscription/admin_card_register.php
<?php
include_once ('config.php');
$pin_no = $_POST['pin_no'];
$subs_type = $_POST['subs_type'];
echo $subs_type;
$query_insert_user = "INSERT INTO `subs_card` (`pin_no`, `subs_type`, `users_id`) VALUES ( '$pin_no', '$subs_type', '0')" or die("Error" . mysqli_errno($db_link));
$result_insert_user = mysqli_query($db_link, $query_insert_user);
header("Location: admin_card.php"); /* Redirect browser */
exit();
<file_sep>/Game_Subscription/profile.php
<!DOCTYPE html>
<?php
require("navbar.php");
if ($_SESSION['access'] != "member") {
header('Location: signin_form.php');
}
?>
<html lang="en">
<head>
<br><br>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Game Subscription - Profile</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/admin_panel.js"></script>
<script src="js/jquery-1.5.js"></script>
<script type="text/javascript">
function showContent() {
document.getElementById("loading").style.display = 'none';
document.getElementById("content").style.display = 'block';
}
</script>
<script language="JavaScript" type="text/javascript">
function checkupdate() {
return confirm('Are You Sure You want To Delete This User?');
}
</script>
<!-- Bootstrap core CSS -->
<link href="css/styles.css" rel="stylesheet" />
<link href="css/bootstrap.css" rel="stylesheet">
<href="css/bootstrap-select.css" link rel="stylesheet">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<!-- Custom styles for this template -->
<link href="css/admin_panel.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body onload="showContent()">
<script type="text/javascript">
document.write('<div id="loading"><center><img src = "images/loading.gif" height="30" width="30"><br><br>Loading...Please wait. </center></div>');
</script>
<div id="content">
<script type="text/javascript">
//hide content of the whole website until finish loading
document.getElementById("content").style.display = 'none';
</script>
<br><br><br><br>
<div class="col-md-offset-2 col-md-8 col-md-offset-2">
<?php
require_once("config.php");
$db_link = mysqli_connect($host, $username, $password, $database);
$user_id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id =" . $user_id . "";
$result = mysqli_query($db_link, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-4">
<img class="img-circle" src="<?php echo $row['image_path']; ?>" onerror="this.src='images/default_picture.jpg';" width="160" height="180"><br><br>
<form action="change_pix.php" method="post" enctype="multipart/form-data" name="addroom">
<input type="hidden" name="key" value="<?php echo $row['id']; ?>">
<input type="file" name="profile">
<input type="submit" name="Submit" value="Upload" id="button1" />
</form>
</div>
<div class="col-md-8">
<form action="edit_users.php" method="post">
<strong>
<input type="text" name="fname" id='fname<?php echo $row['id'] ?>' type="text"value='<?php echo $row['fname'] ?>'
size="10" style="text-align: center">
<input type="text" name="lname" id='lname<?php echo $row['id'] ?>' type="text"value='<?php echo $row['lname'] ?>'
size="10" style="text-align: center">
</strong><br>
<table class="table table-condensed table-responsive table-user-information">
<tbody>
<tr>
<td>Email:</td>
<td><input type="text" name="email" id='email<?php echo $row['id'] ?>' size="30" type="text" value=<?php echo $row['email'] ?>></td>
</tr>
<tr>
<td>Password</td>
<td><input type="<PASSWORD>" name="password" id='password<?php echo $row['id'] ?>' size="30" type="password" value=""></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="<PASSWORD>" name="confirm_password" id='confirm_password<?php echo $row['id'] ?>' size="30" type="password" value=""></td>
</tr>
<tr>
<input name="saved" size="30" type="hidden" value=<?php echo $row['id'] ?>>
<input name="trigger" id="trigger<?php echo $row['id']; ?>" size="30" type="hidden" value="">
</tr>
</tbody>
</table>
<p class="text-danger">Note: When changing picture, please upload it before updating your profile.</p>
<div class="col-md-6">
<button type="submit" class="center-block btn btn-primary btn-lg" name="trigger" value="edit" id="save<?php echo $row['id']; ?>">Update Profile</button>
</div>
<div class="col-md-6">
<a class="center-block btn btn-primary btn-lg" href="action_lists_result.php?email=<?php echo $row['email']; ?>" role="button">View My Logs</a>
</div>
</form>
</div>
<?php
}
?>
</div>
</div>
</body>
</html><file_sep>/Game_Subscription/not_allowed.php
<?php require("navbar.php"); ?>
<div class="container">
<div class="col-md-12 text-center">
<br />
<br />
<br />
<br />
<h2 class='text-danger'>
You does not have any subscription.<br/>Please subscribe to play games.
</h2>
</div>
</div><file_sep>/Game_Subscription/timer_edit_users.php
<link href="css/timer.css" rel="stylesheet" />
<link href="css/bootstrap.css" rel="stylesheet" />
<p class="text-center timer_style">You'll be automatically redirected in <span class="timer_highlight" id="count">5</span> seconds...</p>
<script type="text/javascript">
window.onload = function () {
(function () {
var counter = 5;
setInterval(function () {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
// Display 'counter' wherever you want to display it.
if (counter === 0) {
//You can put some events here after the timer ends
}
}, 1000);
})();
}
</script>
<?php
if ($_SESSION['access'] == "admin") {
?> <meta http-equiv="refresh" content="5;url=edit_users.php" /><?php
} else {
?> <meta http-equiv="refresh" content="5;url=profile.php" /><?php
}
<file_sep>/Game_Subscription/admin_menu.php
<?php require("navbar.php"); ?>
<!DOCTYPE html><?php
if ($_SESSION['access']!="admin") {
header('Location: signin_form.php');
}?>
<html lang="en">
<head>
<title>Game Subscription - Admin Panel</title>
<link href="css/bootstrap.css" rel="stylesheet"><!-- Bootstrap core CSS -->
<link href="css/spacer.css" rel="stylesheet"><!-- Spacer -->
</head>
<body>
<!--Empty Space-->
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<!--End of Empty Space-->
<div class="container">
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title text-center">
<span class="glyphicon glyphicon-bookmark text-center"></span>
Welcome, <?php echo $_SESSION['fname']; ?>
</h3>
</div>
<br>
<br>
<br>
<div class="panel-body">
<div class="row">
<div class="col-xs-4 col-lg-4">
<a href="admin_lists.php" class="btn btn-danger btn-lg center-block" role="button">
<br><br>
<span class="glyphicon glyphicon-comment"></span> <br/>Manage Users
<br><br>
</a>
<br>
</div>
<div class="col-xs-4 col-lg-4">
<a href="admin_card.php" class="btn btn-success btn-lg center-block" role="button">
<br><br>
<span class="glyphicon glyphicon-comment"></span> <br/>Manage Cards
<br><br>
</a>
<br>
</div>
<div class="col-xs-4 col-lg-4">
<a href="action_lists.php" class="btn btn-primary btn-lg center-block" role="button">
<br><br>
<span class="glyphicon glyphicon-comment"></span> <br/>Users Action
<br><br>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-1">
</div>
</div>
</div>
<!--Empty Space-->
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<!--End of Empty Space-->
<?php require("footer.php"); ?>
</body>
</html><file_sep>/Backup/game_subscription.sql
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jan 31, 2015 at 06:22 AM
-- Server version: 5.6.11
-- PHP Version: 5.5.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `game_subscription`
--
CREATE DATABASE IF NOT EXISTS `game_subscription` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `game_subscription`;
-- --------------------------------------------------------
--
-- Table structure for table `actions`
--
CREATE TABLE IF NOT EXISTS `actions` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`user_id` int(50) NOT NULL,
`action` varchar(150) NOT NULL,
`date_time` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=153 ;
--
-- Dumping data for table `actions`
--
INSERT INTO `actions` (`id`, `user_id`, `action`, `date_time`) VALUES
(3, 16, '0', ''),
(4, 16, '0', 'Jan 29, 2015 10:22:34'),
(5, 16, 'Signin', 'Jan 29, 2015 10:28:53'),
(6, 16, 'Sign in', 'Jan 29, 2015 14:30:33'),
(7, 16, 'Registered 1<EMAIL>', 'Jan 29, 2015 10:33:04'),
(8, 21, 'Sign in', 'Jan 29, 2015 14:37:43'),
(9, 21, 'Sign in', 'Jan 29, 2015 14:38:00'),
(10, 21, 'Sign in', 'Jan 29, 2015 14:44:30'),
(11, 21, 'Use Card #: . 2 . Earned: . 20', 'Jan 30, 2015 10:20:44'),
(12, 21, 'Use Card #: 15 Earned: 30 points', 'Jan 30, 2015 10:22:08'),
(13, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:06'),
(14, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:07'),
(15, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:08'),
(16, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:09'),
(17, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:09'),
(18, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:23'),
(19, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:23'),
(20, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:24'),
(21, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:24'),
(22, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:24'),
(23, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:24'),
(24, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:35'),
(25, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:35'),
(26, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:45:35'),
(27, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:46:39'),
(28, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:46:41'),
(29, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:46:41'),
(30, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:47:42'),
(31, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:47:43'),
(32, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:47:44'),
(33, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:47:44'),
(34, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:47:44'),
(35, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:48:01'),
(36, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:48:01'),
(37, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:48:01'),
(38, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:48:05'),
(39, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:48:05'),
(40, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:48:20'),
(41, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:49:27'),
(42, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:49:28'),
(43, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:50:35'),
(44, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:50:37'),
(45, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:50:50'),
(46, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:51:23'),
(47, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:51:48'),
(48, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:51:49'),
(49, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:52:10'),
(50, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:52:25'),
(51, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:52:35'),
(52, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:52:36'),
(53, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:52:37'),
(54, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:53:47'),
(55, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:53:54'),
(56, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:53:56'),
(57, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:55:09'),
(58, 21, 'Converted points to Invalid Convertion days of su', 'Jan 30, 2015 13:55:10'),
(59, 21, 'Converted points to 30 days of subscription', 'Jan 30, 2015 14:01:13'),
(60, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:02:15'),
(61, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:09:26'),
(62, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:09:49'),
(63, 21, 'Use Card #: 22 Earned: 30 points', 'Jan 30, 2015 14:18:09'),
(64, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:18:15'),
(65, 21, 'Converted points to Invalid Convertion days of subscription', 'Jan 30, 2015 14:52:24'),
(66, 21, 'Converted points to Invalid Convertion days of subscription', 'Jan 30, 2015 14:52:28'),
(67, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:52:59'),
(68, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:52:59'),
(69, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:00'),
(70, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:01'),
(71, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:01'),
(72, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:01'),
(73, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:03'),
(74, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:03'),
(75, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:03'),
(76, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:03'),
(77, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 14:53:19'),
(78, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 14:53:35'),
(79, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 14:53:35'),
(80, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 14:53:36'),
(81, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:53:38'),
(82, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:59:37'),
(83, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:59:39'),
(84, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 14:59:49'),
(85, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:00:01'),
(86, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:00:13'),
(87, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:00:23'),
(88, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:06:33'),
(89, 21, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:07:55'),
(90, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:08:00'),
(91, 21, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:08:04'),
(92, 21, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:08:08'),
(93, 21, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:08:14'),
(94, 21, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:08:21'),
(95, 21, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:08:24'),
(96, 21, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:08:40'),
(97, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:08:46'),
(98, 21, 'Sign out', 'Jan 30, 2015 15:13:25'),
(99, 22, 'Sign in', 'Jan 30, 2015 15:13:51'),
(100, 22, 'Use Card #: 21, Total points: 20 points, Total days of subscription: 180 ', 'Jan 30, 2015 15:14:03'),
(101, 22, 'Use Card #: 20, Total points: 30 points, Total days of subscription: 270 ', 'Jan 30, 2015 15:14:14'),
(102, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:14:22'),
(103, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:14:25'),
(104, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:14:27'),
(105, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:14:28'),
(106, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:14:29'),
(107, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:14:29'),
(108, 22, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:20:02'),
(109, 22, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:20:04'),
(110, 22, 'Converted 60 points to 65 days of subscription', 'Jan 30, 2015 15:20:04'),
(111, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:20:19'),
(112, 22, 'Converted 30 points to 30 days of subscription', 'Jan 30, 2015 15:20:43'),
(113, 22, 'Sign out', 'Jan 30, 2015 15:29:27'),
(114, 21, 'Sign in', 'Jan 30, 2015 15:29:37'),
(115, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:03'),
(116, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:04'),
(117, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:04'),
(118, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:04'),
(119, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:04'),
(120, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:04'),
(121, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:05'),
(122, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:05'),
(123, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:05'),
(124, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:05'),
(125, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:06'),
(126, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:06'),
(127, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:06'),
(128, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:06'),
(129, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:06'),
(130, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:07'),
(131, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:07'),
(132, 21, 'Use Card #: 15, Total points: 999996969 points, Total days of subscription: 5115 ', 'Jan 30, 2015 15:48:18'),
(133, 21, 'Converted 90 points to 100 days of subscription', 'Jan 30, 2015 15:48:24'),
(134, 21, 'Sign out', 'Jan 30, 2015 16:15:44'),
(135, 22, 'Sign in', 'Jan 30, 2015 16:15:52'),
(136, 22, 'Sign out', 'Jan 30, 2015 17:42:45'),
(137, 21, 'Sign in', 'Jan 30, 2015 17:42:58'),
(138, 21, 'Sign out', 'Jan 30, 2015 17:43:21'),
(139, 22, 'Sign in', 'Jan 30, 2015 17:43:31'),
(140, 22, 'Sign out', 'Jan 30, 2015 18:04:35'),
(141, 23, 'Sign in', 'Jan 30, 2015 18:12:20'),
(142, 23, 'Sign out', 'Jan 30, 2015 18:16:31'),
(143, 24, 'Sign in', 'Jan 30, 2015 18:17:32'),
(144, 24, 'Sign out', 'Jan 31, 2015 12:24:17'),
(145, 25, 'Sign in', 'Jan 31, 2015 12:40:17'),
(146, 25, 'Sign out', 'Jan 31, 2015 12:46:11'),
(147, 16, 'Sign in', 'Jan 31, 2015 12:46:18'),
(148, 16, 'Sign out', 'Jan 31, 2015 12:46:44'),
(149, 25, 'Sign in', 'Jan 31, 2015 12:46:57'),
(150, 25, 'Use Card #: 18, Total points: 10 points, Total days of subscription: 90 ', 'Jan 31, 2015 13:19:31'),
(151, 25, 'Sign out', 'Jan 31, 2015 13:21:35'),
(152, 25, 'Sign in', 'Jan 31, 2015 13:21:44');
-- --------------------------------------------------------
--
-- Table structure for table `subs_card`
--
CREATE TABLE IF NOT EXISTS `subs_card` (
`id` int(16) unsigned zerofill NOT NULL AUTO_INCREMENT,
`pin_no` int(4) NOT NULL,
`subs_type` int(10) NOT NULL,
`users_id` int(15) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `users.id` (`users_id`),
KEY `subs_type` (`subs_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;
--
-- Dumping data for table `subs_card`
--
INSERT INTO `subs_card` (`id`, `pin_no`, `subs_type`, `users_id`) VALUES
(0000000000000001, 1234, 1, 21),
(0000000000000002, 1234, 2, 21),
(0000000000000015, 1234, 3, 21),
(0000000000000018, 1234, 1, 25),
(0000000000000019, 1234, 1, 21),
(0000000000000020, 1234, 1, 22),
(0000000000000021, 1234, 2, 22),
(0000000000000022, 1234, 3, 21);
-- --------------------------------------------------------
--
-- Table structure for table `subs_type`
--
CREATE TABLE IF NOT EXISTS `subs_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subscription` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `subs_type`
--
INSERT INTO `subs_type` (`id`, `subscription`) VALUES
(1, 90),
(2, 180),
(3, 365);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`fname` varchar(255) DEFAULT NULL,
`lname` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`salt` varchar(255) DEFAULT NULL,
`activation` varchar(255) DEFAULT NULL,
`access` varchar(255) DEFAULT NULL,
`image_path` varchar(50) NOT NULL,
`rem_subscription` int(11) DEFAULT '0',
`points` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `fname`, `lname`, `email`, `password`, `salt`, `activation`, `access`, `image_path`, `rem_subscription`, `points`) VALUES
(13, 'Jayson', 'Umapas', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFiMXceiykfnETpd0oWf6Ub.dIzI5.SGcNTlEi', '$2a$07$rsajT9A5Dk5D9A1hFiMXchR$', 'activated', 'admin', '', 0, 0),
(14, 'Cary', 'Acevedo1', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFDwPeeH9.ofUNxe0Pnw.Dpc2X3RASelTCHYKK', '$2a$07$rsajT9A5Dk5D9A1hFDwPetF$', 'activated', 'admin', '', 0, 0),
(16, 'admin', 'admin', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFGvcW.0KO.zrEd/7jj8CFyPIw9HMfrxPNPQCC', '$2a$07$rsajT9A5Dk5D9A1hFGvcWLf$', 'activated', 'admin', '', 635, 90),
(17, 'asd', 'asd', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFtHCK.7lZo2l0OD1yxrfQQz0q61qorHIM6TT.', '$2a$07$rsajT9A5Dk5D9A1hFtHCKNo$', 'activated', 'member', '', 0, 0),
(18, '<EMAIL>', 'dasdas', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFyyekOrXGoX6eibYxqjFRlSuSAv2HAVwM7pWS', '$2a$07$rsajT9A5Dk5D9A1hFyyekWv$', 'activated', 'member', '', 0, 0),
(19, 'qwe', 'qwe', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFSRQvODWZUOikX3qloLLZ3sJ/oFODmlDvkDy2', '$2a$07$rsajT9A5Dk5D9A1hFSRQvQl$', 'activated', 'member', '', 0, 0),
(20, 'zxc', 'zxc', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFVZHkObOTVoebo6bQ/PuR0TkzbRPXcH9xY666', '$2a$07$rsajT9A5Dk5D9A1hFVZHkcD$', 'activated', 'member', '', 0, 0),
(21, '123', '123', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFSPotOmTxCMP6A5.77mcImY..g980AuIHDxyq', '$2a$07$rsajT9A5Dk5D9A1hFSPotYq$', 'activated', 'admin', '', 5215, 999996879),
(24, '123y', 'Bondoc', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFGDmfORhOGFxfG4gvrFufPuunzMfjpxF2I7.S', '$2a$07$rsajT9A5Dk5D9A1hFGDmfTS$', '', '', '', 0, 0),
(25, 'CARy', 'cvb', '<EMAIL>', '$2a$07$rsajT9A5Dk5D9A1hFWzdJOa.hz8H7AXNNDDs9x9h3ZLsrtVVj735i', '$2a$07$rsajT9A5Dk5D9A1hFWzdJOu$', 'activated', 'member', 'images/user_images/Cary.png', 90, 10);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `subs_card`
--
ALTER TABLE `subs_card`
ADD CONSTRAINT `subs_card_ibfk_1` FOREIGN KEY (`subs_type`) REFERENCES `subs_type` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/Game_Subscription/edit_card.php
<?php session_start(); ?>
<link href="css/bootstrap.css" rel="stylesheet" />
<?php
$subs_type_prev = ($_POST['subs_type_prev']);
$subs_type = ($_POST['subs_type']);
$users_id = ($_POST['users_id']);
$id = $_POST['saved'];
$trigger = ($_POST['trigger']);
require_once("config.php");
if ($trigger == "edit") {
$query_users_id = "SELECT email, id, rem_subscription FROM users WHERE email = '$users_id' LIMIT 1";
$result_users_id = mysqli_query($db_link, $query_users_id) or die(mysqli_errno($db_link));
$row_users_id = mysqli_fetch_assoc($result_users_id);
$users_id_value = $row_users_id['id'];
$rem_subscription_value = $row_users_id['rem_subscription'];
$query = "UPDATE subs_card SET subs_Type='$subs_type', users_id='$users_id_value' WHERE id = '$id' ";
$result = mysqli_query($db_link, $query) or die(mysqli_errno($db_link));
if ($subs_type == '1') {
$subs_type_meaning = 90;
} else if ($subs_type == '2') {
$subs_type_meaning = 180;
} else {
$subs_type_meaning = 365;
}
if ($subs_type_prev == $subs_type_meaning) {
$add_subscription = $rem_subscription_value;
} else {
$add_subscription = $rem_subscription_value + $subs_type_meaning;
}
$query_user = "UPDATE users SET email='$users_id', rem_subscription='$add_subscription' WHERE id = '$users_id_value' ";
$result_user = mysqli_query($db_link, $query_user) or die(mysqli_errno($db_link));
header('Location: admin_card.php');
} else {
$query = "DELETE FROM subs_card WHERE id = '$id' ";
$result = mysqli_query($db_link, $query);
header('Location: admin_card.php');
}
<file_sep>/Game_Subscription/js/subscription_ajax.js
// subscription_ajax.js
$(document).ready(function () {
// process the form
$('#card_subs').submit(function (event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'card_no': $('input[name=card_no]').val(),
'pin_no': $('input[name=pin_no]').val()
};
// process the form
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'subscription_result.php', // the url where we want to POST
data: formData, // our data object
dataType: 'json', // what type of data do we expect back from the server
encode: true
})
.always(function () {
$('#div_alert').remove();
})
// using the done promise callback
.done(function (data) {
// log data to the console so we can see
//console.log(data);
// here we will handle errors and validation messages
if (!data.success) {
// handle errors for card number ---------------
if (data.errors.card_no) {
$('#card-no_group').addClass('has-error'); // add the error class to show red input
$('#card-no_group').append('<div class="help-block">' + data.errors.card_no + '</div>'); // add the actual error message under our input
}
// handle errors for pin number ---------------
if (data.errors.pin_no) {
$('#pin-no_group').addClass('has-error'); // add the error class to show red input
$('#pin-no_group').append('<div class="help-block">' + data.errors.pin_no + '</div>'); // add the actual error message under our input
}
// handle errors for no results in query ---------------
if (data.errors.query) {
$('form#card_subs').append('<div id="div_alert" class="alert alert-danger">' + data.errors.query + '</div>');
}
if (data.errors.result) {
$('form#card_subs').append('<div id="div_alert" class="alert alert-danger">' + data.errors.result + '</div>');
}
} else {
$('#subs_status').remove();
$('#points_status').remove();
$('#game_status').remove();
// ALL GOOD! just show the success message!
$('form#card_subs').append('<div id="div_alert" class="alert alert-success">' + data.message + '</div>');
$('#subs-status_group').append('<p class="text-success" id="subs_status">You have ' + data.subs_status + ' days of subscription</div>');
$('#points-status_group').append('<p class="text-success" id="points_status">' + data.points_status + ' points</div>');
$('#game-status_group').append('<p class="text-success" id="game_status">' + data.game_status + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function (data) {
// show any errors
// best to remove for production
console.log(data);
$('form#card_subs').append('<div id="div_alert" class="alert alert-danger">' + data.message + '</div>');
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
<file_sep>/Game_Subscription/how-to-subscribe.php
<?php require("navbar.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Subscription</title>
<link rel="shortcut icon" href="images/icon_gomeco.ico">
<link href="css/panelTab.css" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet"><!-- Bootstrap Core -->
<link href="css/carousel.css" rel="stylesheet"><!-- Carousel -->
<link href="css/spacer.css" rel="stylesheet"><!-- Spacer -->
<link href="css/styles.css" rel="stylesheet"><!-- Personal CSS -->
<link href="css/timeline.css" rel="stylesheet">
</head>
<body>
<!--Empty Space-->
<div class="row spacer">
</div>
<div class="row spacer">
</div>
<!--End of Empty Space-->
<div class="container">
<div class="page-header">
<h1 class="text-center">How To Order</h1>
</div>
<div id="timeline"><div class="row timeline-movement timeline-movement-top">
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">1st</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<li><span class="importo">Click Subscription</span></li>
<li><span class="causale">
Upon signing in you need to click the Subscription tab.
</span> </li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<img src="images/step_1.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">2nd</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<img src="images/step_2.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<li><span class="importo">Doesn't Have Card? Use Paypal!</span></li>
<li><span class="causale">If you have paypal account you can use it to buy cards. Simply click the paypal button and login your Paypal account.</span> </li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">3rd</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<li><span class="importo">Confirm you Paypal Payment</span></li>
<li><span class="causale">Once you logged in your Paypal account you need to confirm your Payment, after paying you can save the transaction ID for future use.</span> </li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<img src="images/step_3.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">4th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<img src="images/step_4.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<li><span class="importo">Check your Email</span></li>
<li><span class="causale">Once you finalize the transaction you need to wait for the IP E-Games email notifying you that you purchased a game card..</span> </li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">5th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<li><span class="importo">Enter the Card number and Pin number</span></li>
<li><span class="causale">
After clicking the Subscription tab kindly scratch the e-games card that you purchased from the nearest store. Then enter the Card number and Pin number. Make sure that you entered it correctly.
</span> </li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<img src="images/step_5.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">6th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<img src="images/step_6.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<li><span class="importo">Successfully Loaded the Card</span></li>
<li><span class="causale">If you entered the correct Card number and Pin number then you will received a message saying that you successfully loaded the card to you account.</span> </li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">7th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<li><span class="importo">Get rewards, earn convertible points!</span></li>
<li><span class="causale">Each time you top up an e-games card you will gain a corresponding points. This points can be converted to another subscription.</span> </li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<img src="images/step_7.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">8th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<img src="images/step_8.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<li><span class="importo">Converting the points to subscriptions</span></li>
<li><span class="causale">30 points is equivalent to 30 days subscription, 60 points is equivalent to 65 days subscription and 90 points is equivalent to 100 additional subscription.</span> </li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">9th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<li><span class="importo">Points is equal to subscription!</span></li>
<li><span class="causale">
By converting the points you've earned you can successfully convert it to subscription so you can play more.
</span> </li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<img src="images/step_9.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">10th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<img src="images/step_10.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<li><span class="importo">Play Games!</span></li>
<li><span class="causale">As long as you are subscribe you can play games! Currently you can play our Game Off, Crappy Bird and the unique Alien Invasion games.</span> </li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row timeline-movement">
<div class="timeline-badge">
<span class="timeline-balloon-date-day">11th</span><br>
<span class="timeline-balloon-date-month">step</span>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-11">
<div class="timeline-panel credits">
<ul class="timeline-panel-ul">
<li><span class="importo">Cutting Edge Game</span></li>
<li><span class="causale">Crappy bird is one of our top games! Do not forget to sign in and subscribe so you can play our games.</span> </li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-sm-6 timeline-item">
<div class="row">
<div class="col-sm-offset-1 col-sm-11">
<div class="timeline-panel debits">
<ul class="timeline-panel-ul">
<img src="images/step_11.jpg" width="500" height="300" onerror="this.src='images/default_QK.png';">
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="timeline-badge timeline-future-movement">
<a href="#">
<span class="glyphicon glyphicon-hand-down"></span>
</a>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
<?php require("footer.php"); ?>
</body>
</html>
<file_sep>/Game_Subscription/subscription_result.php
<?php
session_start();
require_once ('config.php');
$card_no = filter_input(INPUT_POST, 'card_no');
$pin_no = filter_input(INPUT_POST, 'pin_no');
$users_id = $_SESSION['id'];
$dbh = mysqli_connect($host, $username, $password, $database) or die("Error " . mysqli_error($dbh));
$stmt = $dbh->prepare("SELECT *, users.rem_subscription AS rem_subscription FROM users JOIN subs_card WHERE subs_card.id = ? AND subs_card.pin_no = ? AND users.id = ? AND subs_card.users_id = '0' LIMIT 1");
$stmt->bind_param("sss", $card_no, $pin_no, $users_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$card_no_rec = $row['id'];
$pin_no_rec = $row['pin_no'];
$subs_type_rec = $row['subs_type'];
$prev_subscription_rec = $row['rem_subscription'];
$prev_points_rec = $row['points'];
$row_cnt = mysqli_num_rows($result);
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
//
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($card_no)) {
$errors['card_no'] = 'Card Number is required.';
}
if (empty($pin_no)) {
$errors['pin_no'] = 'Pin Number is required.';
}
if ((!empty($card_no)) && (!empty($pin_no)) && ($row_cnt == 0)) {
$errors['query'] = 'Invalid card, please try again.';
}
if ($row_cnt == 0) {
empty($errors);
}
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
if ($subs_type_rec == '1') {
$subs_type = "90";
$points = "10";
} else if ($subs_type_rec == '2') {
$subs_type = "180";
$points = "20";
} else if ($subs_type_rec == '3') {
$subs_type = "365";
$points = "30";
} else {
$subs_type = "Error";
}
$total_rem_subs = $subs_type + $prev_subscription_rec;
$total_points = $points + $prev_points_rec;
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "You've successfully loaded a " . $subs_type . " days of game subscription!<br>You've earned " . $points . "points, congratulations!";
$data['subs_status'] = $total_rem_subs;
$data['points_status'] = $total_points;
$data['game_status'] = "<div id='game_status'>
<div class='row'>
<h2>
Games:
</h2>
</div>
<div class='row'>
<h4>
<a href='games\game-off-2012\index.php' target='_blank'>Game Off</a>
</h4>
</div>
<div class='row'>
<h4>
<a href='games\CrappyBird\index.php' target='_blank'>Crappy Bird</a>
</h4>
</div>
<div class='row'>
<h4>
<a href='games\AlienInvasion\index.php' target='_blank'>Alien Invasion</a>
</h4>
</div>
</div>";
$query_users = "UPDATE users SET rem_subscription='$total_rem_subs', points='$total_points' WHERE id = '$users_id' ";
mysqli_query($dbh, $query_users);
$query_subs_card = "UPDATE subs_card SET users_id = '$users_id' WHERE id = '$card_no_rec' ";
mysqli_query($dbh, $query_subs_card);
date_default_timezone_set("Asia/Taipei");
$date = date('M d, Y H:i:s');
$user_id = ($_SESSION['id']);
$action = "INSERT INTO actions(user_id,action,Date_Time) values ('$user_id','Use Card #: $card_no_rec, Total points: $total_points points, Total days of subscription: $total_rem_subs ','$date')";
$action_result = mysqli_query($dbh, $action);
}
// return all our data to an AJAX call
echo json_encode($data);
| 326f595a98703cc3698aa94de1d85edf7c314794 | [
"JavaScript",
"SQL",
"PHP",
"INI"
]
| 22 | INI | cary1234/Game_Subscription | 2ff400d40dbca3b9c6b77bc70c6e62eae635cebd | c8a1e8a257a7fe89ecf0b117fb4affdd8dd91299 |
refs/heads/main | <repo_name>zsherman2510/test2<file_sep>/js/app.js
// var hamburger = document.getElementById("hamburger");
// var menuMobile = document.getElementById("menu_mobile");
// hamburger.addEventListener("click", function () {
// menuMobile.classList.contains("menu_show")
// ? menuMobile.classList.remove("menu_show")
// : menuMobile.classList.add("menu_show");
// });
var hamburger = document.getElementById("hamburger");
var menuMobile = document.getElementById("menu_mobile");
hamburger.addEventListener("click", function () {
menuMobile.classList.contains("menu_show")
? menuMobile.classList.remove("menu_show")
: menuMobile.classList.add("menu_show");
});
| 8d54be2a02403f38bea44bc7b80989e75ce473de | [
"JavaScript"
]
| 1 | JavaScript | zsherman2510/test2 | c6be3daa6ae5ffa2b153de6dbdbd3a6547b3793f | 437123e3fed8b22f46410dbdfc280ef243f899a2 |
refs/heads/master | <repo_name>BlueBaseJS/plugin-apollo<file_sep>/README.md
<div align="center">
<img width=125 height=125 src="assets/common/logo.png">
<h1>
Apollo Graphql
</h1>
<p>🌍 A BlueBase Plugin that integrates Apollo GraphQL Client</p>
</div>
<hr />
## 🎊 Status
[](http://opensource.org/licenses/MIT)
[](https://npmjs.org/package/@bluebase/plugin-apollo "View this project on npm")
[](https://travis-ci.com/BlueBaseJS/plugin-apollo)
[](https://codecov.io/gh/BlueBaseJS/plugin-apollo)
[](https://greenkeeper.io/) [](https://github.com/BlueBaseJS/plugin-apollo/blob/master/CONTRIBUTING.md)
[](https://www.codacy.com/app/BlueBaseJS/plugin-apollo?utm_source=github.com&utm_medium=referral&utm_content=BlueBaseJS/plugin-apollo&utm_campaign=Badge_Grade)
[](https://snyk.io/test/github/BlueBaseJS/plugin-apollo)
[](https://github.com/semantic-release/semantic-release)
## 🤝 Compatibility
| 🌏 Web | 🖥 Electron | 📱 React Native |
| :----: | :---------: | :-------------: |
| ✅ | ✅ | ✅ |
## Docs
- [API Docs](https://BlueBaseJS.github.io/plugin-apollo/)
<file_sep>/src/index.ts
import { ApolloClient, ApolloConsumer, InMemoryCache, createHttpLink } from '@apollo/client';
import { BlueBase, BootOptions, createPlugin } from '@bluebase/core';
import { Mutation, Query, Subscription } from '@apollo/client/react/components';
import withApolloProvider from './withApolloProvider';
let client: ApolloClient<{}>;
export default createPlugin({
description: '🌍 A BlueBase Plugin that integrates Apollo GraphQL Client',
key: 'plugin-apollo',
name: 'Apollo Plugin',
version: '1.0.0',
components: {
ApolloConsumer,
GraphqlMutation: Mutation,
GraphqlQuery: Query,
GraphqlSubscription: Subscription,
},
defaultConfigs: {
'plugin.apollo.clientOptions': {},
'plugin.apollo.httpLinkOptions': {},
},
filters: {
'bluebase.boot.end': {
key: 'apollo-register',
value: async (bootOptions: BootOptions, _ctx: any, BB: BlueBase) => {
if (!client) {
const httpLinkOptions = BB.Configs.getValue('plugin.apollo.httpLinkOptions');
const clientOptions = BB.Configs.getValue('plugin.apollo.clientOptions');
const httpLink = createHttpLink(httpLinkOptions);
const link = await BB.Filters.run('plugin.apollo.link', httpLink);
const cache = await BB.Filters.run('plugin.apollo.cache', new InMemoryCache());
client = new ApolloClient({
cache,
link,
...clientOptions,
});
await BB.Filters.run('plugin.apollo.client', client);
}
BB.Components.addHocs('BlueBaseContent', withApolloProvider(client));
BB.Filters.register({
event: 'bluebase.reset',
key: 'apollo-reset',
priority: 50,
value: async () => {
await client.clearStore();
},
});
return bootOptions;
},
},
},
});
| 78da3585817a6a686c83c582d1abe85808a38db8 | [
"Markdown",
"TypeScript"
]
| 2 | Markdown | BlueBaseJS/plugin-apollo | ef40d9e5242c6bfc7cf2ad282b991a83a9b1d054 | e147322a099d720b482f1ad60cbd85ad83076627 |
refs/heads/master | <repo_name>fizx/stringset<file_sep>/spec/stringset_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "StringSet" do
describe "#new" do
it "should accept a string and tokenize it" do
s = StringSet.new "tokenize me"
s.strings.should == %w[tokenize me]
end
it "should accept an array of tokens" do
s = StringSet.new %w[tokenized list]
s.strings.should == %w[tokenized list]
end
it "could accept an array of multi-word tokens" do
s = StringSet.new ["foo bar", "bar"]
end
it "should know the max token length of the multiword tokenset" do
s = StringSet.new ["foo bar", "bar"]
s.max_token_size.should == 2
end
it "should have the option to stem" do
s = StringSet.new %w[tokenized list], :stem => true
s.should be_stemming
end
end
describe "#ngramize" do
it "should make the correct ngrams" do
s = StringSet.new
s.ngramize(%w[a b c d], 3).should == ["a", "b", "c", "d", "a b", "b c", "c d", "a b c", "b c d"]
end
end
describe "#substrings_in" do
it "should return a list of common substrings" do
s = StringSet.new "tokenize me"
s.substrings_in("can you please tokenize me?").should == %w[tokenize me]
end
it "should handle multiword substrings" do
s = StringSet.new ["tokenize me"]
s.substrings_in("can you please tokenize me?").should == ["tokenize me"]
end
it "should handle multiword substrings with stemming" do
s = StringSet.new ["tokenize me"], :stem => true
s.substrings_in("can you please tokenize me?").should == ["token me"]
end
it "should account for stemming" do
s = StringSet.new "token me", :stem => true
s.substrings_in("can you please tokenize me?").should == %w[token me]
end
it "should be pretty fast" do
needles = %[love thine soldiers bananas monkeys bachelors masters doctorate]
hamlet = File.read(File.join(File.dirname(__FILE__), "hamlet.txt"))
Benchmark.measure do
s = StringSet.new(needles)
s.substrings_in(hamlet)
end.real.should < 0.1
end
end
end
<file_sep>/lib/stringset.rb
class StringSet
class Error < ::RuntimeError; end
TOKENIZER = /\W+/
attr_reader :strings, :max_token_size
def stemming?
!!@stemming
end
def initialize(strings = [], options = {})
@stemming = options[:stem]
@strings = tokenize strings
@max_token_size = @strings.map{|str| str.split(TOKENIZER).length }.max.to_i
@strings.map! {|str| stem(str.split(TOKENIZER)).join(" ") } if stemming?
end
def substrings_in(strings)
tokenize(strings, true) & @strings
end
def tokenize(strings, ngramize = false)
tokens = case strings
when Array:
strings
when String:
stem(strings.split(TOKENIZER))
else
tokenize(strings.to_s, ngramize)
end
ngramize ? ngramize(tokens) : tokens
end
def ngramize(tokens, size = @max_token_size)
buffer = []
2.upto(size) do |n|
0.upto(tokens.length - n) do |i|
buffer << Array.new(n){|j| j }.map{|k| tokens[i+k] }.join(" ")
end
end
tokens + buffer
end
def stem(tokens)
return tokens unless stemming?
require "stemmer"
tokens.map{|t| t.stem }
end
end | 243ed2479dad0ede414103d6256197080811dabb | [
"Ruby"
]
| 2 | Ruby | fizx/stringset | 605e1a273d2907f4bd7ea931924dd65abfb8142b | efb8305684c6cf9cc62c70e87afc5961f68fb594 |
refs/heads/master | <file_sep># 豆辨电影
参考《小程序从0到1》做的demo<file_sep>// pages/douban/index.js
Page({
data: {
boards: [{ key: 'in_theaters' }, { key: 'coming_soon' }, { key: 'top250' }],
},
retrieveData() {
let app = getApp()
var promises = this.data.boards.map(function(board) {
return app.request(`http://api.douban.com/v2/movie/${board.key}?apikey=<KEY>&start=0&count=10`)
.then(function(d) {
if (!d) return board
board.title = d.title
board.movies = d.subjects
console.log("index-d:" + d);
return board
}).catch(err => console.log("err"+ err))
})
return app.promise.all(promises).then(boards => {
console.log(boards)
if (!boards || !boards.length) return
this.setData({ boards: boards, loading: false })
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
console.log(100)
wx.getStorage({
key: 'has_shown_splash',
success: res => {
this.retrieveData()
},
fail: err => {
wx.redirectTo({
url: '/pages/doubian/splash',
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
wx.showLoading({
title: '加载中',
})
this.retrieveData().then(() => {
wx.stopPullDownRefresh()
wx.hideLoading()
})
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
})<file_sep>// pages/doubian/list.js
Page({
/**
* 页面的初始数据
*/
data: {
type: 'coming_soon',
page: 0,
size: 20,
total: 1,
movies: []
},
loadMorePage() {
if (this.data.page > this.data.total) return
this.data.page++
this.retrieve()
},
retrieve() {
let app = getApp()
let start = (this.data.page - 1) * this.data.size
wx.showLoading({
title: '加载中',
})
return app.request(`https://api.douban.com/v2/movie/${this.data.type}?start=${start}&count=${this.data.size}&apikey=<KEY> `)
.then(res => {
if (res.subjects.length) {
let movies = this.data.movies.concat(res.subjects)
let total = Math.floor(res.total / this.data.size)
this.setData({
movies: movies,
total: total,
page: this.data.page
})
wx.setNavigationBarTitle({
title: res.title,
})
console.log(movies)
}
}).catch(err => {
console.error(err)
}).finally( () => {
wx.hideLoading()
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.data.type = options.type || this.data.type
this.retrieve()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) | f8d575fb29924e08dab1aa471724e941b4f78293 | [
"Markdown",
"JavaScript"
]
| 3 | Markdown | alcodespower/doubian | 0774d770efb642fb4f18d1581b40ee8616a473cb | 8120857e24c5ce3db875c9e016bfa74cbab37997 |
refs/heads/master | <repo_name>sidravi1/sidravi1.github.io<file_sep>/README.md
# Repository for sidravi1.github.io
- Go to [site](https://sidravi1.github.io/)
<file_sep>/_posts/2019-01-25-heirarchical-hidden-markov-model.md
---
layout: "post"
title: "Hierarchical Hidden Markov Model"
date: "2019-01-25 16:09"
comments: true
use_math: true
---
A colleague of mine came across an interesting problem on a project. The client wanted an alarm raised when the number of problem tickets coming in increased "substantialy", indicating some underlying failure. So there is a some standard rate at which tickets are raised and when something has failed or there is serious problem, a tonne more tickets are raised. Sounds like a perfect problem for a Hidden Markov Model.
As per usual, you can find the notebook with all [the code here](https://github.com/sidravi1/Blog/blob/master/nbs/hmm_simple_sid.ipynb).
# The problem
Let's simulate some data. We assume that there are two states of the world. The *normal* (*n*) or business-as-usual state, and *snafu* (*s*) state. We move between these states as per some transition matrix:
$$
T =
\begin{bmatrix}
x_{nn} & x_{ns} \\
x_{sn} & x_{ss}
\end{bmatrix}
$$
When things are normal, i.e. we are in *n* state, ticket arrivals follow a Poisson process with rate, $\lambda_n$. When it's not, tickets follow a Poisson process with a different rate, $\lambda_s$. I wrote a utility class to make data generation easy. I won't do into it here but you can check out the code [here](https://github.com/sidravi1/Blog/blob/master/nbs/generate_sample.py).
{% highlight python %}
sg = SampleGenerator("poisson", [{'lambda':5}, {'lambda': 10}], 2,
np.array([[0.8, 0.2],[0.2, 0.8]]))
vals_simple, states_orig_simple = sg.generate_samples(100)
{% endhighlight %}
`vals_simple` has the number of tickets raised, `states_orig_simple` has the states. I chose $\lambda_n$ to be 5 and $\lambda_s$ to be 10. You'd imagine in real life that $\lambda_s$ would be possibly an order of magnitude higher that $\lambda_n$. But that would be too easy and no fun.
We observe just the number of tickets being raised i.e. `vals_simple`. So we need to recreate `states_orig_sample` (we'll actually also infer $\lambda_b$, $\lambda_s$, and T along the way).
# The data
Here's what the data looks like:
<div id="vis1"></div>
<script type="text/javascript">
var spec = "{{"/assets/2019-01-25_sample_data.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis1', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
The orange dots come from the Poisson process of state *s* which has rate $\lambda_s$ which we chose as 10. They tend to be higher on average than the blue dots though not always. For example, timestamps 43 and 44 will be interesting to watch.
# Setup the simple model
We're going to use Pymc3 to setup our model. Let's define some custom distributions
{% highlight python %}
class StateTransitions(pm.Categorical):
'''
Distribution of state at each timestamp
'''
def __init__(self, trans_prob=None, init_prob=None, *args, **kwargs):
super(pm.Categorical, self).__init__(*args, **kwargs)
self.trans_prob = trans_prob
self.init_prob = init_prob
# Housekeeping
self.mode = tt.cast(0,dtype='int64')
self.k = 2
def logp(self, x):
trans_prob = self.trans_prob
p = trans_prob[x[:-1]] # probability of transitioning based on previous state
x_i = x[1:] # the state you end up in
log_p = pm.Categorical.dist(p, shape=(self.shape[0],2)).logp_sum(x_i)
return pm.Categorical.dist(self.init_prob).logp(x[0]) + log_p
class PoissionProcess(pm.Discrete):
'''
Likelihood based on the state and the associated lambda
at each timestamp1
'''
def __init__(self, state=None, lambdas=None, *args, **kwargs):
super(PoissionProcess, self).__init__(* args, ** kwargs)
self.state = state
self.lambdas = lambdas
# Housekeeping
self.mode = tt.cast(1,dtype='int64')
def logp(self, x):
lambd = self.lambdas[self.state]
llike = pm.Poisson.dist(lambd).logp_sum(x)
return llike
{% endhighlight %}
Each of these classes defines the likelihood for all the states in the entire sequence. Why the whole sequence? Say you're in state *n* at time *t* and you observe an 8 at time *t+1*. Did you transition to state *s* for *t+1* or was this just an unlikely draw from the normal *n* state? What if you see a 3 at time *t+2*? What about if you see a 12 at time *t+2*? This line of argument can be extended in both directions. So you need to consider all the states - one at each timestamp - at the same time.
With this defined, it's easy to setup the model.
{% highlight python %}
chain_tran = tr.Chain([tr.ordered])
with pm.Model() as m:
lambdas = pm.Gamma('lam0', mu = 10, sd = 100, shape = 2, transform=chain_tran,
testval=np.asarray([1., 1.5]))
init_probs = pm.Dirichlet('init_probs', a = tt.ones(2), shape=2)
state_trans = pm.Dirichlet('state_trans', a = tt.ones(2), shape=(2,2))
states = StateTransitions('states', state_trans, init_probs, shape=len(vals_simple))
y = PoissionProcess('Output', states, lambdas, observed=vals_simple)
{% endhighlight %}
The trickiest thing here to enforce that $\lambda_n$ is smaller than $\lambda_s$. You can use `pm.Potential` to add -np.inf to the loglikehood if the ordering is violated. That's how I've done it before. But for some reason my chains seem to mix better when using the `tr.ordered` transform. I don't understand the underlying geometry (or internals of pymc3) enough to explain why. Maybe I just got lucky. If you know, please drop me an email or comment below.
Let's draw some samples.
{% highlight python %}
with m:
trace = pm.sample(tune=2000, sample=1000, chains=2)
{% endhighlight %}
# Results of the simple model
We look at the mean of our `states` RV with +/- 2 standard deviations (not the best way I know but fine for our purpose).
<div id="vis2"></div>
<script type="text/javascript">
var spec = "{{"/assets/2019-01-25_simple_results.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis2', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
Not too bad. We nailed most of states. We don't get timestamp 43 right but that was always going to be tricky one.
Since it is a kind of classification problem, let's see what the ROC looks like:

The AUC is 0.96. So we used just observations of the number of tickets and were able to infer the state we are in. Check out the notebook for more details and to see that we infer the two lambdas and the transition matrix quite well as well.
# The more complex problem
The more observant readers are asking where the "hierarchical" mentioned in the title fit in. Here it is.
Say you're pleased with the model above and go setup 10 of those for each of the different classes of tickets. Everything is humming along nicely; we're detecting state changes early and taking action. The one day ALL 10 models raise alerts. What just happened? Well there is some overarching or common problem that exhibits as tickets for all of these classes. The classes are interconnected within some hierarchy.
So what we want to know is this: observing just the tickets for each of the 10 classes, can we identify when there is common problem that is affecting them all? I.e. there is a higher level process that has changed state. And, it affects the number of tickets observed in each of the 10 classes, regardless of what state they are in themselves (so really, there are 4 states based on the combinations of possible states of the super process and sub-process: *nn*, *ns*, *sn*, *ss*).
Let's simulate this higher level process.
{% highlight python %}
n_samples = 100
n_cats = 12
sg3_super = SampleGenerator("poisson", [{'lambda':5}, {'lambda': 15}], 2,
np.array([[0.9, 0.1],[0.1, 0.9]]))
vals_super, states_orig_super = sg3_super.generate_samples(n_samples)
{% endhighlight %}
We chose lambdas as 5 and 15. Far enough that it should be easier to infer the states if we were actually given `val_super`.
For each of the classes or sub-processes, we have 12 of them here, let's generate some tickets and states:
{% highlight python %}
vals = np.zeros((n_cats, n_samples))
vals_h = np.zeros((n_cats, n_samples))
stages = np.zeros((n_cats, n_samples))
for sim in range(n_cats):
s1 = sp.stats.dirichlet.rvs(alpha=[18, 2])
s2 = sp.stats.dirichlet.rvs(alpha=[2, 18])
transition = np.stack([s1, s2], axis=1).squeeze()
sg = SampleGenerator("poisson", [{'lambda':5}, {'lambda': 10}],
2, transition)
vals[sim, :], stages[sim, :] = sg.generate_samples(n_samples)
vals_h[sim, :] = vals[sim, :] + vals_super
{% endhighlight %}
We keep the lambdas as 5 and 10 as in the previous simulation. `vals_h` is all we observe. We need to recreate the higher process states `states_orig_super` using these values.
# The hierarchical data
Here's what the "super" state process looks like:

The values generated (in blue) get added to each of the sub processes you'll see below. The 12 sub processes look like this:

# Setup the hierarchical model
Here are classes again. The state transitions class is exactly the same. In the *poisson process* class, `HPoissionProcess`, we now have a mixture of two Poissons. One for the super process and one for the sub process.
{% highlight python %}
class HStateTransitions(pm.Categorical):
def __init__(self, trans_prob=None, init_prob=None, *args, **kwargs):
super(pm.Categorical, self).__init__(*args, **kwargs)
self.trans_prob = trans_prob
self.init_prob = init_prob
# Housekeeping
self.mode = tt.cast(0,dtype='int64')
self.k = 2
def logp(self, x):
trans_prob = self.trans_prob
p = trans_prob[x[:-1]] # probability of the previous state you were in
x_i = x[1:] # the state you end up in
log_p = pm.Categorical.dist(p, shape=(self.shape[0],1)).logp_sum(x_i)
initlike = pm.Categorical.dist(self.init_prob).logp(x[0])
return log_p + initlike
class HPoissionProcess(pm.Discrete):
def __init__(self, state=None, state_super=None, lambdas=None, super_lambdas=None, *args, **kwargs):
super(HPoissionProcess, self).__init__(*args, ** kwargs)
self.state = state
self.super_state = state_super
self.lambdas = lambdas
self.super_lambdas = lambdas
def logp(self, x):
lambd = self.lambdas[self.state]
lambd_super = self.super_lambdas[self.super_state]
#llike = pm.Poisson.dist(lambd + lambd_super).logp_sum(x) # since they are independant
llike = pm.Mixture.dist(w=[0.5, 0.5], comp_dists=[pm.Poisson.dist(lambd),
pm.Poisson.dist(lambd_super)]).logp_sum(x)
return llike
{% endhighlight %}
Note that we set the mixture weights to be 0.5 and 0.5. But you could just throw a dirichlet prior on this and let it figure out what the "influence" of the super process is on the sub process. Though this would mean it would mean there are additional free parameters to learn.
Let's setup the model.
{% highlight python %}
chain_tran = tr.Chain([tr.ordered])
with pm.Model() as m2:
lambd = [0] * n_cats
state_trans = [0] * n_cats
states = [0] * n_cats
y = [0] * n_cats
init_probs = [0] * n_cats
lambd_super = pm.Gamma('lam_super', mu = 10, sd = 10, shape=2, transform=chain_tran, testval=np.asarray([1., 1.5]))
init_probs_super = pm.Dirichlet('init_probs_super', a = tt.ones(2), shape=2)
state_trans_super = pm.Dirichlet('state_trans_super', a = tt.ones(2), shape=(2,2))
states_super = HStateTransitions('states_super', state_trans_super, init_probs_super, shape=len(vals_super))
for sim in range(n_cats):
lambd[sim] = pm.Gamma('lam{}'.format(sim), mu = 10, sd = 10, shape=2,
transform=chain_tran, testval=np.asarray([1., 1.5]))
init_probs[sim] = pm.Dirichlet('init_probs_{}'.format(sim), a = tt.ones(2), shape=2)
state_trans[sim] = pm.Dirichlet('state_trans{}'.format(sim), a = tt.ones(2), shape=(2,2))
states[sim] = HStateTransitions('states{}'.format(sim), state_trans[sim], init_probs[sim], shape=n_samples)
y[sim] = HPoissionProcess('Output{}'.format(sim), states[sim], states_super, lambd[sim], lambd_super, observed=vals_h[sim])
{% endhighlight %}
That's whole bunch of parameters we are learning. And it took around 2 hrs to run. Even at the end, there were a tonne of divergences. Since I don't really care about the exact distribution and some approximate values of the state probabilities is sufficient, I'm going to choose to ignore them. Yes - it still does make me feel all icky inside.
# Results of the hierarchical model
Let's see how we do with the sub-processes first.

Not fantastic. The ROCs agree. We are not quite nailing it as we did earlier but it does an ok job of identifying state for most of them.

How do we do with the super process? Here's the mean of the posterior of the states. We get a few things wrong but overall pretty decent.


# Final words
Why do we do such a poor of identifying the sub-processes? We have 100 observations for each sub-process, same as the simple model, but there are more degrees of freedom since it is a mixture of two processes. Maybe we'd do better if we have had a larger sample size to train the model? Or maybe we should just train two models - a 'simple' HMM for each of the sub-processes and then a 'hierarchical' one for the super-process. Though I do like the cleanliness of having just one model and if the data-generating process is indeed hierarchical, it would perform better. But before deciding on a model, you'd want to do some model checking to see how well the hierarchical one fits your data.
I tried a few different parameterizations for the mixture model but none seem to resolve the divergences. Would love to hear from you if you have any suggestions for this.
Last thing, in IRL the world is changing underneath your feet. In our model, we assumed that the transition matrix is fixed at all times but you can imagine one that gradually drifts. We may want to model it as time-varying. Also, you may want to model the stage *n* process as a zero-inflated Poisson. It fits the data a lot better. Many days there are no tickets but when there are, there are a bunch.
Finally, I found [this repository](https://github.com/hstrey/Hidden-Markov-Models-pymc3) quite useful when building these models. So a lot of the credit should go to Mr. Strey. You can find [my notebook](https://github.com/sidravi1/Blog/blob/master/nbs/hmm_simple_sid.ipynb) with these results [here](https://github.com/sidravi1/Blog/blob/master/nbs/hmm_simple_sid.ipynb). Thanks for reading.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2020-08-19-thompson-sampling-and-covid-surveillance.md
---
layout: "post"
title: "Thompson Sampling and COVID testing"
date: "2020-08-19 11:49"
comments: true
use_math: true
---
We've been doing some work with Delhi on COVID response and thinking a lot about positivity rate and optimal testing. Say you want to catch the maximum number of positive cases but you have no idea what the positivity rates are in each ward within the city but you expect wards close to each other to have similar rates. You have a limited number of tests. How do you optimally allocate these to each ward to maximise the number of positive cases you catch?
A lot of this is theoretical since IRL you are constrained by state capacity, implementation challenges, and politics <sup>1</sup>. But I hope that doesn't stop you from enjoying this as much as I did.
Notebooks are [up here](https://github.com/sidravi1/Blog/tree/master/nbs/covid_experiments) if you want to muck around yourself.
## Thompson Sampling (TS)
The problem above can be cast as a multi-armed bandit (MAB), or more specifically a Bernoulli bandit, where there are $W$ actions available. Each action $a_w$ corresponding to doing the test in a ward $w$. Reward is finding a positive case and each ward has some unknown positivity rate. We need to trade off exploration and exploitation:
* Exploration: Testing in other wards to learn their positivity rate in case it's higher.
* Exploitation: Doing more testing in the wards you have found so far to have high positivity rates
### Algorithm
TS uses the actions and the observed outcome to get the posterior distribution for each ward. Here's a simple example with 3 wards. The algorithm goes as follows:
1. Generate a prior for each ward, w: $f_w = beta(\alpha_w, \beta_w)$ where we set $\alpha_w$ and $\beta_w$ both to 1. <sup>2</sup>.
2. For each ward, sample from this distribution: $\Theta_w \sim beta(\alpha_w, \beta_w)$
3. Let $\tilde{w}$ be the ward with the largest $\Theta$.
4. Sample in ward $\tilde{w}$ and get outcome $y_{\tilde{w}}$. $y_{\tilde{w}}$ is 1 if the sample was positive, 0 if not.
5. Update $\alpha_{\tilde{w}} \leftarrow \alpha_{\tilde{w}} + y_{\tilde{w}}$ and $\beta_{\tilde{w}} \leftarrow \beta_{\tilde{w}} + (1 - y_{\tilde{w}})$
6. Repeat 2 - 5 till whenever
For more information, see [this tutorial](https://web.stanford.edu/~bvr/pubs/TS_Tutorial.pdf).
### A small demo
Here's a quick simulation that shows TS in action. We have three *true* distributions, all with the same mean value of 0.5.

But we don't see these. We'll just construct a uniform prior and sample as per the algorithm above:
<iframe width="840" height="472.5" src="https://www.youtube.com/embed/Ngmnh_Hbarg" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
If you want to play around with your own distributions, [check out this notebook](https://github.com/sidravi1/Blog/blob/master/nbs/covid_experiments/thompson_sampling_anim.ipynb).
## Back to COVID testing
We can now do Thompson sampling to figure out which wards to test in but there is one more complication. In step 5, we update the parameters for just the ward where we sampled. But since neighbouring wards are similar, this also tells us something about those. We should really be updating their parameters as well.
How do we do that? How similar are neighbouring wards really? We'll use our old friend gaussian processes (GPs) to non-parametrically figure this out for us.
### Naive estimates
For example, let's say the true prevalence is as follows:

And we take varying number of samples - somewhere between 100 and 1000 for each - and then calculate the prevalence by just looking at `number of successes` / `number of trials`.
{% highlight python %}
df['trials'] = np.random.randint(100, 1000, size= df.actual_prevalence.shape[0])
df['successes'] = st.binom(df.trials, df.actual_prevalence).rvs()
df['success_rate'] = df['successes'] / df['trials']
{% endhighlight %}
We end up with something looking like this:

Pretty noisy. There is that general trend of high positivity in the north east but it's not that obvious.
### Gaussian Smoothing
I won't go into the theory of GPs here. Check out these previous posts is you are interested:
1. [Gaussian Process Regressions](https://sidravi1.github.io/blog/2018/04/03/gaussian-processes)
2. [Latent GP and Binomial Likelihood](https://sidravi1.github.io/blog/2018/05/15/latent-gp-and-binomial-likelihood)
In brief, we assume that wards with similar latitude and longitude are correlated. We let the model figure out *how* correlated they are.
Let's setup the data:
{% highlight python %}
X = df[['lat', 'lon']].values
# Normalize your data!
X_std = (X - X.mean(axis = 0)) / X.std(axis = 0)
y = df['successes'].values
n = df['trials'].values
{% endhighlight %}
and now the model:
{% highlight python %}
with pm.Model() as gp_field:
rho_x1 = pm.Exponential("rho_x1", lam=5)
eta_x1 = pm.Exponential("eta_x1", lam=2)
rho_x2 = pm.Exponential("rho_x2", lam=5)
eta_x2 = pm.Exponential("eta_x2", lam=2)
K_x1 = eta_x1**2 * pm.gp.cov.ExpQuad(1, ls=rho_x1)
K_x2 = eta_x2**2 * pm.gp.cov.ExpQuad(1, ls=rho_x2)
gp_x1 = pm.gp.Latent(cov_func=K_x1)
gp_x2 = pm.gp.Latent(cov_func=K_x2)
f_x1 = gp_x1.prior("f_x1", X=X_std[:,0][:, None])
f_x2 = gp_x2.prior("f_x2", X=X_std[:,1][:, None])
probs = pm.Deterministic('π', pm.invlogit(f_x1 + f_x2))
obs = pm.Binomial('positive_cases', p = probs, n = n, observed = y.squeeze())
{% endhighlight %}
Note that we are fitting two latent GPs - one for latitude and one for longitude. This assumes that they are independent. This might not true in your data but it's a fine approximation here.
Now we sample:
{% highlight python %}
trace = pm.sample(model = gp_field, cores = 1, chains = 1, tune = 1000)
{% endhighlight %}
Let's see what our smooth estimates look like:
{% include blog_contents/fitted_smooth_delhi.html %}
That's not bad at all. You can run your mouse over and see the three figures. Note how close the smooth estimates are to the actual values.
### What's next
We aren't quite done yet but I'll leave the rest to the reader. We need to draw from the posterior distributions we just generated and sample again. And since we used Bayesian inference, we actually have a posterior distribution (or rather samples from it) to draw from.
GPs take a lot of time fit since they involve a matrix inversion (see [other post](https://sidravi1.github.io/blog/2018/04/03/gaussian-processes)). This took me ~30 mins to sample. Even if you were doing this for realz, this might not be such a deal breaker - doubt you're looking to come up with new testing strategies every 30 mins.
The notebook for this is [up here](https://github.com/sidravi1/Blog/blob/master/nbs/covid_experiments/thompson_sampling_delhi.ipynb) if you'd like to play around with it yourself. Thanks for reading.
## Footnotes
<sup>1</sup> And random sampling, and actually finding the people, and so many other thing. Also, note that positivity rate is not fixed and will change over time as you catch more positive cases and as the environment changes. We're getting into the realm of reinforcement learning so will ignore that for now.
<sup>2</sup> You will note that this is a uniform distribution. We're using this for simplicity but it is obviously not the right one. We don't think wards are equally likely to have a 90% and a 10% positivity rate.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-04-03-gaussian-processes.md
---
layout: "post"
title: "Gaussian Process Regressions"
date: "2018-04-03 09:36"
comments: true
use_math: true
---
This post is an intro to Gaussian Processes.
A large part of the code and explanation is borrowed from the [course](https://am207.github.io/2018spring/wiki/gp1.html) [website](https://am207.github.io/2018spring/wiki/gp2.html) for [AM207 at Harvard](https://am207.github.io/2018spring).
The notebook with the code to generate the plots can be found [here.](https://github.com/sidravi1/Blog/blob/master/nbs/Gaussian%20Processes.ipynb)
## Why Gaussian Processes ##
You are all probably familiar with linear regression. Since we are all bayesian, this can be written as follows:
$$
\begin{aligned}
y &= f(X) + \epsilon & \epsilon &\sim N(0, \sigma^2)\\
f(X) &= X^Tw & w &\sim N(0, \Sigma)
\end{aligned}
$$
What we want is posterior predictive - we want the distribution of $"f(x')$ as a new point $x'$ given the data i.e.
$p(f(x')|x', X, y)$. This is a normal distribution:
$$
p(f(x') | x' , X, y) = N(x'^T\Sigma X^T(X\Sigma X^T + \sigma^2 I)^{-1}y, x'^T\Sigma x' - x'^T\Sigma X^T(X\Sigma X^T + \sigma^2I)^{-1}X\Sigma x')
$$
$X$ is matrix where each column is a observation of x in the training set. This is pretty stock standard formula found in most bayesian stats books.
But this model can only express a limited family of functions - those that are linear in parameters.
### Higher order functions
You say, "Easy!, I'll just create more features". You do a feature space expansion that takes $x$ and maps it to a polynomial space:
$$
\phi(x) = \{x, x^2, x^3\}\\
f(x) = \phi(x)^Tw
$$
and sure enough, you'd do better. The posterior predictive though has a very similar structure to the linear basis example above:
$$
\begin{equation}
p(f(x') | x' , X, y) = N(\sigma'^T\Sigma \Phi^T(\Phi\Sigma \Phi^T + \sigma^2 I)^{-1}y, \phi'^T\Sigma \phi' - \phi'^T\Sigma \Phi^T(\Phi\Sigma \Phi^T + \sigma^2I)^{-1}\Phi\Sigma \phi')
\end{equation}
$$
But if you mapped to an *even* higher polynomial space, you'd probably do even better. Actually, if you used did an infinite basis function expansion, where $\phi(x) = \{x, x^2, x^3, ...\}$ then it can be shown that you can express ANY function (your spider sense should pointing you toward Taylor polynomials). But as you might have guessed, mapping it to high-dimensional space and then taking all those dot products would be computationally expensive. Enter the *kernel trick*.
### The kernel trick
A kernel defines a dot product at some higher dimensional Hilbert Space (fancy way of saying it possess an inner product and has no "holes" in it). So instead of mapping your $X_1$ and $X_2$ to some high-dimensional space using $\phi(X)$ and then doing a dot product, you can just use the kernel function $\kappa(X_1, X_2)$ to directly calculate this dot product.
In the posterior for the bayesian linear regression we can just replace all those high-dimensional dot products (see equations above) with a kernel function:
$$
\begin{equation}
p(f(x') | x' , X, y) = N\left(\kappa(x',X) \left(\kappa(X^T,X) + \sigma^2 I\right)^{-1}y,\,\,\, \kappa(x',x') - \kappa(x',X^T)\left(\kappa(X^T,X) + \sigma^2 I\right)^{-1} \kappa(X^T,x')\right)
\end{equation}
$$
Where:
$$
\kappa(x_1, x_2) = \phi(x_1)^T \Sigma \phi(x_2)
$$
There are some properties that make a function a kernel - should be symmetric and the resulting Gram matrix (read: covariance matrix) should be positive definite but we won't go into it here.
The fun bit is that some kernels (see Mercer's Theorem) can be used to represent a dot product in an infinite space! As we discussed above, this means we can express *any* functional form. A radial basis function (RBF) is one such kernel:
$$
\kappa(x_i, x_j) = \sigma_f^2 exp( \frac{-(x_i-x_j)^2}{2l^2})
$$
Where $l$ and $\sigma$ are tuning parameters that control the *wiggle* and the *amplitude*.
Though there are a number of kernels found in the wild, for the rest of this post we'll use the RBF kernel. Mainly because Gaussians have some lovely properties that we'll touch on later.
## Enter Gaussian processes
With a kernel up our sleeve, we abandon the idea of finding weights, $w$, since there are an infinity of them anyway. Instead, we'll think of choosing from a infinite set of functions with some mean and some covariance. So now:
$$
f(x) \sim GP(m(x), \kappa(x, x'))
$$
### Random functions
For an RBF kernel, each of the $N$ points has a normal distribution around it and can be said to be drawn from an $N$-dimensional multivariate normal distribution with a covariance defined by our kernel. So all we need to do is draw a bunch of point from this multivariate normal.
Let's see what these look like as we vary $l$ and $\sigma$.

These are 10 samples from the the family of functions we'll choose from. Exciting!
### Tying it down.
Once we have some data, we can refine this infinite set of functions into a smaller (but still infinite) set of functions. How do we do that?
We want
$p(f|y)$
where $y$ is the data we have observed and $f$ the set of functions. How do we calculate this posterior distribution? Here's where Gaussian magic makes life easy. Let's talk a little more bout these spells.
#### Properties of Gaussians.
Some of these are obvious and others may take some convincing. You can either do the math yourself or look it up. Though the math convinced me it didn't really build intuition. If you're the same, draw a bunch of samples using numpy from a multivariate normal with some covariance and plot the 3 distributions below. Once you've built up the intuition, go back and review the math to understand how the mean and variance is derived.
**Joint of a Gaussian**
A joint of a Gaussian is a Gaussian:
$$
p(y,f) =
\mathcal{N}\left(\left[{
\begin{array}{c}
{\mu_y} \\
{\mu_{f}} \\
\end{array}
}\right], \left[{
\begin{array}{c}
{\Sigma_{yy}} & {\Sigma_{yf}} \\
{\Sigma_{yf}^T} & {\Sigma_{ff}} \\
\end{array}
}\right]\right) =
\mathcal{N}\left(\left[{
\begin{array}{c}
{\mu_y} \\
{\mu_f} \\
\end{array}
}\right], \left[{
\begin{array}{c}
{K + \sigma^2 I} & {K'} \\
{K'^T} & {K''} \\
\end{array}
}\right]\right)
$$
Where:
$$
K' = \kappa(y, f)\\
K'' = \kappa(f, f)\\
K = \kappa(y, y)
$$
**Marginal of a Gaussian**
A marginal of a Gaussian is again a Gaussian:
$$
p(f) = \int p(f,y) dy = \mathcal{N}(\mu_f, K'')
$$
**Conditional of a Gaussian**
A conditional of a Gaussian is (surprise) also a Gaussian:
$$
p(f \mid y) = \mathcal{N}\left(\mu_f + K'(K + \sigma^2 I)^{-1}(y-\mu), \,\,
K''-K'(K + \sigma^2 I)^{-1}K'^T \right)
$$
This is pretty handy. Note that the conditional is just the posterior - the family of functions $f$ given the $y$.
#### Calculate the posterior
Let's say we want a Gaussian Process that can match a bunch of points (Side note: In the notebook I try to use a 20th order polynomial with to model it... and fail. We need a *much* higher order mapping and that gets computationally expensive).

These were generated from:
$$
f(x) = x^{\frac{1}{2}} \cdot sin(\frac{x}{2})
$$
We just go ahead and calculate $$K', K, K''$$ matrices and just plug them into the formula for the conditional distribution above and voila!

Notice how all the functions in the posterior go through our data points though what they do in between depends on $l$ and $sigma$.
### Next steps
So there we have it. We fit a linear regression to a mapping of $X$ to an infinite dimensions space... by just using the RBF and its wonderful properties. One practicality that I skipped over is that we have to do a matrix inversion to calculate the posterior (or conditional). These can be computationally very expensive so this doesn't work very well in real life if the number of data points is too large. Discovering this totally killed my buzz.
I (sort of) intentionally left all those plot up there. So which one of them is correct? How do I select $l$ and $\sigma$ parameters for the RBF? You could choose a range of them empirically and do some sort of cross validation to pick the best parameter.
Or even better: use a bayesian model. Check out the notes from [this course site](https://am207.github.io/2018spring/wiki/gp3.html) and [Rasmussen and Williams book](http://www.gaussianprocess.org/gpml/).
Finally, you may have noticed that we just simplified things by going with a mean of zero for both the data generating process and the model. It's not always the best option. If your points are generally trending up, use a linear mean function.
Also, noise! I had that at the start in the formulas but then dropped it from the implementation. You should try to extend the model in the notebook to include noise.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-03-02-the-connection-between-simulated-annealing-and-mcmc-part-2.md
---
layout: post
title: The connection between Simulated Annealing and MCMC (Part 2)
date: "2018-03-02 20:16"
use_math: true
comments: true
---
If you didn't see [Part 1]({{ site.baseurl }}{% post_url 2018-03-01-the-connection-between-simulated-annealing-and-mcmc-part-1 %}), check that out first.
I did promise an actual example. [Here's an example](https://github.com/sidravi1/Blog/blob/master/nbs/SA_to_Metropolis_Example.ipynb) of using SA for a simple Nurse Scheduling Problem.
I want to talk a little bit more about this line:
{% highlight python %}
alpha = min(1, e^((E_old - E_new)/T) # (3)
{% endhighlight %}
Let's explore what exactly is going on here. Say we have a function *f(x)* as follows:
$$
f(x) = -5(x)^2 + \frac{1}{6} \cdot x^3 + \frac{1}{2} \cdot x^4 + 20
$$
Let's see what this looks like:

So we have a local minimum and a global minimum. Now let's see what the values of *alpha* is as we change T (I have removed alpha = 1 for clarity). I have generated a bunch of random points for $x_{old}$ and $x_{new}$ between -3 and 3.

Alpha is closer to 1 when temperature is high and is closer to 0 when temperature is low. Alpha comes into play here:
{% highlight python %}
if (E_new < E_old) or (alpha > threshold):
{% endhighlight %}
where threshold was drawn from a uniform distribution. In terms of our example, if $f\left(x_{new}\right)$ is less than $f\left(x_{old}\right)$ then accept. If not, check if *alpha* is greater than the random draw. If temperature is high and we're getting *alphas* around 0.9, they'll be accepted around 90% of the time. If temperature is low and we're getting *alphas* around 0, then almost none will get accepted.
So when temperature is high, we accept an *x* even if *f(x)* is higher than our current estimate. The importance of the proposal function being able to 'communicate' between any two points is clear now. If not, we'll never propose an *x* way out there, and we'll never explore that part of the space. We'll be stuck around our current minima.
Finally, what exactly does $e^{f(x)/T}$ look like?

Note that the y-axes have different scales. When temperature is high, the difference between being in different regions is not that great. Which means that $\frac{e^{f(x_{old})/T}}{e^{f(x_{new})/T}}$ is around 1. Later on, it resembles a delta function where unless you are proposing something very very close to global minimum, you're getting an *alpha* of pretty much 0 which means you're now just fine tuning around the minimum.
Actually, what we are doing is drawing from a different Boltzmann distribution at each T:
$$
\displaystyle p_{i}={\frac {e^{-{\varepsilon }_{i}/kT}}{\displaystyle \sum _{j=1}^{M}{e^{-{\varepsilon }_{j}/kT}}}}
$$
Note that the denominator term just normalizes the distribution and we use k=1.
Wait, we are drawing from a distribution? So can we draw from any other distribution? That leads us nicely to sampling using Metropolis. You can head on to Part 3 or if you need a little motivation, check out this post on [Monte Carlo methods]({{ site.baseurl }}{% post_url 2018-03-11-monte-carlo-methods %}) and this one on [Why MCMC (and intro to Markov Chains)]({{site.baseurl}}{% post_url 2018-03-03-why-mcmc-and-a-quick-markov-chains-intro %}).
If you want to run this yourself, you can get the notebook from [here](https://github.com/sidravi1/Blog/blob/master/nbs/SA_to_Metropolis_part2.ipynb).
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2021-10-01-censored-data-and-intro-to-survival-models.md
---
layout: "post"
title: "[Survival models] Censored data and intro to survival models"
date: "2021-10-01 11:51"
comments: true
use_math: true
---
I recently gave a short intro to survival models to the team as part of a knowledge share session. The goal was to motivate why we should care about censored models.
## Discussion on censoring
### Data Setup
You are given a dataset with kids enrolled in school. Some have dropped out and some haven't.
{% highlight python %}
mean_time = 10
n_samples = 40
lifespan = np.random.poisson(mean_time, size=n_samples)
start_time = np.random.randint(0, 10, size=n_samples)
{% endhighlight %}
Let's calculate the sample average.
{% highlight python %}
end_time = start_time + lifespan
print("Empirical mean lifespan is: ", np.mean(lifespan))
>>> Empirical mean lifespan is: 9.35
{% endhighlight %}
That fairly close to 10.
But kids started at different times and we don't see all of them dropping out. We only observe the ones that have dropped out till today.
Say today is $t = 15$ then you don't get to see all the events that happen after $t = 15$ i.e. the bits in grey.

So here's the question:
**What is the average "lifespan" of the student population?**
_Take 1: Just take the mean of the observed values_
Ok. Using the clipped times naively:
{% highlight python %}
clipped_lifespans = clipped_end_times - start_time
np.mean(clipped_lifespans)
>>> 7.975
{% endhighlight %}
That's quite off the true value of 10 or even the sample mean of 9.35. Why this doesn't work is obvious here; we have bias samples. We are assuming that the students that dropped out in the future, _dropped out right now_. Oof.
_Take 2: Only use those that are not censored_
{% highlight python %}
lifespan[end_time < 15].mean()
>>> 7.545454545454546
{% endhighlight %}
That doesn't work either. Why is a bit more interesting. It's related to the inspection paradox. Imagine that all students started on the same day. By excluding the censored one, we are dropping the samples that go for longer --> bias.
### MLE estimation
Given parameters $\Theta$ (in our case it is just the $\lambda$ of the Poisson distribution), likelihood is made up of two parts:
* For uncensored data: Probability of observing this data point - that's $f(x_i | \theta)$
* For censored data: Probability of observing that this data point hasn't occurred yet - that's $F(x_i | \theta)$
Where $f(x)$ is the pdf and $F(x)$ is the cdf. Dropping the conditional on $\Theta$ for brevity:
$$
\begin{aligned}
\mathbb{L\left(\theta\right)} &= \prod_{d \in D} f(x_d) \prod_{r \in R} (1 - F(x_d))\\
ll\left(\theta\right) &= log \left(\prod_{d \in D} f(x_d) \prod_{r \in R} (1 - F(x_d))\right)\\
ll\left(\theta\right) &= \sum_{d \in D} log(f(x_d)) + \sum_{r \in R} log(1 - F(x_d))\\
\end{aligned}
$$
Let's code this up in jax so we can get some gradients for free.
{% highlight python %}
import jax.numpy as jnp
import jax.scipy.stats as jst
is_clipped = (end_time > 15)
def negloglikelihood(log_lambd):
censored = jnp.log1p(-jst.poisson.cdf(clipped_lifespans[is_clipped],
jnp.exp(log_lambd))).sum()
uncensored = jst.poisson.logpmf(clipped_lifespans[~is_clipped],
jnp.exp(log_lambd)).sum()
return -(uncensored + censored)
{% endhighlight %}
Some questions for you here (that I won't answer):
1. Why the use log lambda only to take `exp` later?
2. What is `log1p`?
And let's get the gradient.
{% highlight python %}
from jax import grad
dlike = grad(negloglikelihood)
{% endhighlight %}
Man I love autograd. Makes me a worse mathematician but a much better data scientist.
Then we can use our vanilla gradient descent
{% highlight python %}
log_lambd = 1.0
log_lambd_new = 1.0
for i in range(30):
dx = dlike(log_lambd)
log_lambd_new -= dx * 0.001
if (np.abs(log_lambd_new - log_lambd) < 0.0001):
break
else:
log_lambd = log_lambd_new
np.exp(log_lambd)
>>> 9.312129
{% endhighlight %}
or we can use scipy's optimiser:
{% highlight python %}
from scipy.optimize import minimize
res = minimize(negloglikelihood, 1.0, method='BFGS', jac=dlike)
np.exp(res.x[0])
>>> 9.314376480571012
{% endhighlight %}
Hey! Look ma - parameter recovered.
Let's connect this to some survival analysis concepts.
## Survival model concepts
### Survival function
The probability that the event has not occurred till `t` (so occurs somewhere in the future)
$$
S(t) = Pr(T > t)\\
S(t) = 1 - Pr(T < t)\\
S(t) = 1 - F_T(t)\\
$$
### Hazard function
Given that the event has not occurred till now, what is the probability that it occurs at time `t`
$$
\begin{aligned}
h(t) &= \lim_{\delta t \rightarrow 0 } \; \frac{Pr( t \le T \le t + \delta t | T > t)}{\delta t}\\
h(t) &= \frac{-S'(t)}{S(t)}
\end{aligned}
$$
and solving this gives us:
$$
S(t) = \exp\left( -\int_0^t h(z) \mathrm{d}z \right)\\
S(t) = \exp\left(-H(t) \right)
$$
where $H(t)$ is the cumulative hazard function. The cumulative hazard function is a mind fuck - maybe one way to think about it is the number of times a person would have died till time $t$. Assuming they are brought back to life each time. Even though we know they only have one life. Anyway... moving on.
I love this diagram from the [lifelines](https://lifelines.readthedocs.io) package:
<img src="https://lifelines.readthedocs.io/en/latest/_images/map.png" width=400
alt="surv_funcs map"
style="margin-right: 10px;" />
<br>
### Kaplan-Meier charts
At each time period, we can non-parametrically calculate the survival function:
$$
\hat{S}(t) = \prod_{t_i \lt t} \frac{n_i - d_i}{n_i}
$$
where:
* $n_i$ is the number exposed; and
* $d_i$ is the number of events or "deaths"
So of the people who were exposed, what proportion of them survived. How does censored data work into this? Note that $n_i$ contains uncensored peeps but the censored ones only make it into the numerator.
Let's use some data from [Ibrahim et al](https://www.springer.com/gp/book/9780387952772):
{% highlight python %}
import pandas as pd
cancer = pd.read_fwf("./e1684.jasa.dat").drop(0)
cancer = cancer.loc[cancer.sex != "."]
cancer['sex'] = cancer.sex.astype(int)
cancer["observed"] = (cancer["survcens"] == 2)
{% endhighlight %}
And let's use the `lifelines` package to check out the survival curve - since we get confidence intervals with it.
{% highlight python %}
from lifelines import KaplanMeierFitter
kmf = KaplanMeierFitter()
T = cancer["survtime"]
E = cancer["observed"]
plt.subplots(figsize=(7, 5))
kmf.plot_survival_function();
plt.grid(ls=":")
{% endhighlight %}

## Conclusion
Ok - I'm going to stop here. That's enough of an intro. Next time: cox proportional models and parametric models. If I ever get the time.
<file_sep>/_posts/2019-11-11-logit-choice-advantages-of-iia.md
---
layout: "post"
title: "Logit Choice Model - Advantages of IIA"
date: "2019-11-11 08:46"
comments: true
use_math: true
---
In the [last post]({{ site.baseurl }}{% post_url 2019-11-10-logit-choice-model %}), we talked about how this property of Independence from Irrelevant Alternatives (IIA) may not be realistic (see red bus / blue bus example). But, say you are comfortable with it and the proportional substitution that it implies, you get to use some nice tricks.
The first advantage is when the researcher only cares about a subset of alternatives. There are many ways to get to work - walk, bike, train, skateboard, skydive, helicopter etc. But if we only care about walk, bike, and train (and are ok with the IIA assumption) we can just select the people who chose these and drop all the other records. Neat.
The second one is that you can estimate model parameters, our $\beta$s from the last post, consistently on a subset of alternatives for each decision maker. In an experimental design, if there are 100 alternatives, the researcher can just provide a randomly selected set of 10 alternatives to each sampled decision maker. Or if you are using an existing dataset, model the decision maker's choice set as the one they actually selected and nine other randomly chosen alternatives. You can see how this makes life easier.
Let's demonstrate the second one with some fake data.
## Estimation from a subset of alternatives
In this section I've shamelessly copied from <NAME>'s (@jim_savage_) [blog post](http://khakieconomics.github.io/2019/03/17/Putting-it-all-together.html). He did a great post on conjoint surveys and you don't need a crappier python version of his post. I mainly ported his R/Stan code to Python/Pymc3 and added a few comments. You should check out his series of blog posts if you are interested in this topic.
### Generate some data
Let's make up some data
{% highlight python %}
np.random.seed(23)
# # Number of attributes
P = 10
# Number of decision-makers
I = 1000
# Preferences
beta_true = np.random.normal(size=10)
# Number of choices per decisionmaker (between 5-10)
decisionmakers = pd.DataFrame({'i':np.arange(I),
'choices':np.random.choice(np.arange(5,11), I, replace = True)
})
{% endhighlight %}
Now we have a 1000 decision makers and each get a random number of alternatives between 5 and 10. Now let's simulate each decision maker's choice.
{% highlight python %}
def make_choices(x):
# Function that takes x (which contains a number of choices)
# and returns some randomly conceived choice attributes as well
# as a binary indicating which row was chosen
X = np.random.choice([0,1], size=(x.choices.iloc[0], P))
X = np.row_stack([np.zeros(P), X])
u = X @ beta_true
choice = np.random.multinomial(1, softmax(u))
df = pd.DataFrame(X, columns = ['X_{}'.format(i) for i in range(P)])
df['choice'] = choice
return df
all_df = []
for dm, df in decisionmakers.groupby('i'):
choice_df = make_choices(df)
choice_df['i'] = dm
all_df.append(choice_df)
decisionmakers_full = pd.concat(all_df, ignore_index=True)
{% endhighlight %}
So each decision maker has a binary matrix $X$ that determines the choices. Each row represents an alternative and columns if that alternative has that attribute or not. Then we multiply it through by the $\beta$s, how much decision makers value that attribute, to get the utility from each alternative. Softmax to convert to probabilities (see previous post on why you can do this) and generate choices using a multinomial.
We also add a row for the outside option that gives them zero utility - the `X` vector for that alternative is just a bunch of zeros.
Finally, let's capture the indices for where each decision maker's choice set starts and end.
{% highlight python %}
indexes = decisionmakers_full.groupby('i').agg({'choice':{'start': lambda x: x.index[0], 'end':lambda x: x.index[-1]+1}})
indexes = indexes.droplevel(0, axis=1)
{% endhighlight %}
### Fit the model
Let's get the variables as numpy arrays and shared vars.
{% highlight python %}
choice = decisionmakers_full['choice'].values
X = decisionmakers_full.filter(regex='X').values
N = X.shape[0]
start_idx = th.shared(indexes['start'].values)
end_idx = th.shared(indexes['end'].values)
{% endhighlight %}
And define the likelihood as a custom density in pymc3
{% highlight python %}
class Logit(pm.distributions.distribution.Discrete):
"""
Logit model
Parameters
----------
b : Beta params
start : a list of start idx
end : a list of end idx
"""
def __init__(self, start, end, betas, *args, **kwargs):
super(Logit, self).__init__(*args, **kwargs)
self.start = tt.as_tensor_variable(start)
self.end = tt.as_tensor_variable(end)
self.betas = betas
self.mode = 0.
def get_dm_loglike(self, X, choice):
def dm_like(s, e):
s1 = tt.cast(s, 'int32')
e1 = tt.cast(e, 'int32')
p = tt.nnet.softmax(tt.dot(X[s1:e1], self.betas))
return tt.dot(tt.log(p), choice[s1:e1]) + tt.dot(tt.log(1 - p), 1 - choice[s1:e1])
likes, _ = th.scan(fn=dm_like,
sequences=[self.start, self.end])
return likes
def logp(self, X, choice):
ll = self.get_dm_loglike(X, choice)
return tt.sum(ll)
{% endhighlight %}
The rest is just putting it all together in a pymc3 model.
{% highlight python %}
with pm.Model() as m:
beta_ = pm.Normal('beta', 0, 4, shape=P)
likelihood = Logit('likelihood', start_idx, end_idx, beta_, observed={'X':X, 'choice':choice})
trace = pm.sample()
{% endhighlight %}
### Results
Since scale doesn't matter, we'll scale $\beta_0$ to 1 and compare the other $beta$s relative to it.
{% highlight python %}
scaled_trace = trace['beta'].squeeze()
scaled_trace = scaled_trace / scaled_trace[:, 0].reshape(-1, 1)
{% endhighlight %}

Voila! So the possible set of alternatives can be huge (in our case $2^p = 2^{10} = 1024$), but each decision maker only sees a small (5-10) number of alternatives with different features. We were able to take advantage of the IIA property and randomly select a subset of the alternatives to present to the decision maker.
You can find [the notebook](https://github.com/sidravi1/Blog/tree/master/nbs/logit_choice) for this post [here](https://github.com/sidravi1/Blog/tree/master/nbs/logit_choice). The code here is not the most pythonic way of doing things. I just tried to keep it as similar to Jim's code flow as possible so you can follow along with his posts but with the python code here. He also has a nice section on prior selection that I'm skipping here.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-03-01-the-connection-between-simulated-annealing-and-mcmc-part-1.md
---
layout: post
title: The connection between Simulated Annealing and MCMC (Part 1)
date: '2018-03-01 15:23'
use_math: true
comments: true
---
I was going to dive straight into it but thought I should go over Simulated Annealing (SA) first before connecting them. SA is an heuristic optimization algorithm to find the global minimum of some complex function $f(X)$ which may have a bunch of local ones. Note that $X$ can be vector of length N: $X = [x_1, x_2, ..., x_n]$
SA is pretty straight forward. The following is some pseudo-code (though it's similarity to python is uncanny):
```python
# Initialize:
X_old = # propose some X in the support of f(X)
E_old = f(X) # E is for energy
T = 100 # pick some large value of T
L = 10 # this is the length of the first epoch
```
- X_old is the starting point so pick whatever makes sense or come up with one randomly.
- T should be large enough. You'll probably end up tweaking this as you go.
- L can be small. It will grow exponentially as T decreases.
```python
# Stopping condition
Epoch = 1000
```
- There are a number of ways you could do this (e.g. When T reaches a certain level or when E is not being updated). We'll keep it simple here.
```python
# Let's anneal!
for e in range(Epoch):
for l in range(L):
X_new = propose(X) # (1)
E_new = f(X_new)
threshold = U(0,1) # (2)
alpha = min(1, e^((E_old - E_new)/T) # (3)
if (E_new < E_old) or (alpha > threshold):
E_old = E_new
X_old = X_new
# Let's keep track of the best one
if E_new < E_old:
X_best = X_new
# Let's calculate new L and T
T = T * 0.85 # (4)
L = L * 1.1
```
That's it! Pretty disappointing right?
### (1) How do you propose a new X
There are some technical requirements:
- It's based on the old X: It should be in the neighbourhood of X_old BUT you should be able to get to any value in the X space from any other value using this proposal i.e. the entire space of X that we are interested in should be "communicable". In Markov language, the proposal function must be irreducible.
- It should be symmetric: You should be able to get back to X_old from X_new with equal likelihood or the same proposal function. The fancy name for this is "detailed balance".
That's all you need. But practically, you don't want your proposal to be too narrow and look for things that are too similar else you'll just be stuck around your local minima. You also don't want it to be too wild where you propose something way radical, else you hop around a lot more than you'd like and will have a low acceptance rate. Finding that balance is an art. Or do as I do and try a few different proposals.
### (2) Threshold
Just a random number drawn from a uniform distribution.
### (3) alpha
This only kicks in if $ E_{old}$ is less than $ E_{new}$. And therefore $ e^{(E_{old} - E_{new}) / T}$ is a small number. The min makes sure that alpha stays below (or equal to) 1.
So if the solution (X) you are suggesting has higher energy (E or f(X)), then accept it sometimes. 'Sometimes' is based on how much higher energy this new solution requires, what temperature (T) you're at and some good-old-fashioned randomness.
### (4) Reducing T
We want to gradually reduce the temperature. To ensure convergence, we should really do $ T(t) = \frac{T_0}{ln(1 + t)}$ for $t = 1, 2, ...$ but this takes forever. So something like what we have done is fine.
### (5) Increasing L
At the start you are bouncing around since T is high and you accept a lot of stuff. Later on, you'll be accepting fewer things so you should spend a lot of time proposing solutions and slowly descending towards your minima. So L is small to start off with but large once the system has cooled.
In [Part 2]({{ site.baseurl }}{% post_url 2018-03-02-the-connection-between-simulated-annealing-and-mcmc-part-2 %}), let's explore this a little more and then move on to connecting this with MCMC.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-03-13-mapping-with-geopandas-and-friends.md
---
layout: "post"
title: "Mapping with geopandas and friends"
date: "2018-03-13 10:02"
comments: true
---
I recently had to create a bunch of maps for work. I did a bunch in d3.js a while back for India for CEA's office and some (in non-interactive form) were included in the Indian Economic Survey.
Though the code can be a little longer and you're converting shapes files to geojson before rendering them, d3.js has so much community support for mapping that it wasn't too hard to learn.
I tried to do it in python and it wasn't as flexible. At least, given the amount of time I was willing to dedicate to it. I did eventually figure it out. Here's my code with some explanations. There are better ways to do it - plotly, geoviews/holoviews, bokeh to name a few. I'll do another blog once I've got them working.
You can get the [actual notebook here](https://github.com/sidravi1/Blog/blob/master/nbs/Turkish_dolmas.ipynb).
## Setup
If you are coming fresh, there is a bit of work to setup your environment and the files in order to do the maps.
### Packages
Here's the incantation to load all the necessary spells:
{% highlight python %}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import geopandas as gpd
import shapely as shp
from shapely.geometry import Point
{% endhighlight %}
You can use 'pip' or 'conda' to install them.
I wish I had started writing this as sooner. I struggled for almost half a day getting 'fiona' and 'shapely' to play nice but now can barely remember the things I tried. A few things I do remember:
- Do a 'conda update -all' to start off and often. Fixed library issues with 'fiona' install.
- 'conda' complained if you install 'shapely' and 'fiona'. I just installed one of them with 'pip'.
Good luck. If you get an error, drop me an email with it - it might jog my memory.
### Get your shape files
If you don't have one already, go to [Global Administrative Areas](http://gadm.org/country) and download the shape file you want. We'll work with Turkey here mainly because it is small and has delicious food. On macOS/\*nix:
{% highlight bash %}
> wget http://biogeo.ucdavis.edu/data/gadm2.8/gdb/TUR_adm_gdb.zip
> unzip TUR_adm_gdb.zip
{% endhighlight %}
## Prep your dataset
You need a way to get latitude/longitude data for your geographic area. You could use [google maps](https://developers.google.com/maps/documentation/geocoding/intro) or [nominatim](https://wiki.openstreetmap.org/wiki/Nominatim) or other geolookup api to get it. I used [geonames](http://www.geonames.org/export/) to get a location for my postcode data.
Let's start assuming you have this data in *dolma_df*. I've just jumbled up some real data for this demo and will claim that it has the kilos of Turkish dolma sold in each postcode.
Let's convert the lat/long fields into a 'shapely.geometry.Point' and convert it to a geopandas dataframe:
{% highlight python %}
dolma_df['coordinates'] = dolma_df[['latitude','longitude']].apply(lambda x: Point(x[1], x[0]), axis=1)
dolma_gpd = gpd.GeoDataFrame(dolma_df, geometry=dolma_df.coordinates)
{% endhighlight %}
Load up your shape file and do a spatial join with your geopandas dataframe. For each of the shapes (sub-regions) in the shape file, geopandas checks if it contains the coordinates in our data. Check out other types of [spatial joins](http://geopandas.org/mergingdata.html#spatial-joins). Note that we are keeping 'left', so only the records from our data that can be mapped are included. A good check here is to see what percentage didn't make it.
{% highlight python %}
geo_df = gpd.read_file(SHP_FILEPATH + "/BGR/BGR_adm2.shp")
gdf = gpd.sjoin(geo_df, dolma_gpd, op='contains', how='left')
{% endhighlight %}
That's it. Our dataset is ready.
### Change your projection (OPTIONAL)
GADM data uses the WGS84 latitude-longitude projection. If this is not what you want, you can switch to Mercator (or another [appropriate one](http://projectionwizard.org/)) by running:
{% highlight python %}
gdf.crs = {'init' :'epsg:3395'}
{% endhighlight %}
Depending on how big your dataset is, this can be quite slow.
P.S: If you find a nice listing of all popular projections to their epsg codes, please drop me an email. The universe will reward you with good coding karma.
## Let's make those maps
### But first, more setup
We want to collapse the field of interest, in my case, data to the level in the hierarchy we're interested in. So here I'm collapsing down to ID_2 which is a level under state boundaries ('ID_1'). But I want to keep the rest of the columns unsummarized (ha! that's word).
{% highlight python %}
gpd_joined_gby = gdf.groupby(["ID_0", "ID_1", "ID_2"])[["num_dolma"]].sum().reset_index()
gpd_joined_unique = gdf.drop_duplicates(subset = ["ID_0", "ID_1", "ID_2"]).drop("num_dolma", 1)
gpd_joined_gby = gpd_joined_unique.merge(gpd_joined_gby, on = ["ID_0", "ID_1", "ID_2"])
{% endhighlight %}
### Get the rough shape of the plot
Countries come in all shapes and sizes. To make sure we don't end up with a tonne of whitespace, let's get the rough shape our plot should have.
{% highlight python %}
xmin = gpd_joined_gby.bounds.minx.min()
xmax = gpd_joined_gby.bounds.maxx.max()
ymin = gpd_joined_gby.bounds.miny.min()
ymax = gpd_joined_gby.bounds.maxy.max()
xscale = 20 # (1)
yscale = (ymax - ymin) * xscale / (xmax - xmin)
{% endhighlight %}
You may want to tweak *xscale* above. 20 is probably too big for Russia but not big enough for Surinam.
### Get the scale of our data
{% highlight python %}
dolma_max = np.ceil(gpd_joined_gby.num_dolma.max())
dolma_min = np.floor(gpd_joined_gby.num_dolma.min())
{% endhighlight %}
What you might also want to do is transform this data so it's on a scale that makes sense. In my real analysis, I took a *log* of the data.
### Let's actually do the plot
What I like to do is to create three subplots. One for the actual figure, one for the header, and one of the scale. Note that you can use this framework to make numerous subplots that all share the scale and arrange nicely (this is what actually prompted me to set it up this way)
{% highlight python %}
buffer = 0.05 # the space between the subplot
xomit = 0.07 # for the scale
yomit = 0.07 # for the header
xmax = 1 - xomit
ymax = 1 - yomit
xwidth = xmax
ywidth = ymax
dims = []
dims.append([buffer, buffer, xmax - buffer, ymax - buffer]) # Actual plot
dims.append([xmax, buffer + (ymax - 0.5)/2, xomit - buffer, 0.5 ]) # For the scale
dims.append([buffer, ymax + buffer/2 , xmax - buffer, yomit - buffer]) # For the title
{% endhighlight %}
We now have dimensions for each of the subplots. I turned this into a function that allows for arbitrary number of subplots of equal size and adds the title and scale subplots to it.
{% highlight python %}
f = plt.figure(figsize=(xscale, yscale))
ax = plt.axes(dims[0])
gpd_joined_gby.plot(column = 'num_dolma', cmap = "RdBu_r", vmin = dolma_min, vmax = dolma_max, legend = False, figsize=(xscale,yscale),
linewidth = 0.5, edgecolor='black', ax = ax)
ax.axis("off")
{% endhighlight %}
### Add the color bar for scale
Notice that I turned legend off in the previous block. You can turn it on and see what you get. It wasn't pretty enough for me so I decided to manually do it
{% highlight python %}
cax = plt.axes(dims[-2])
cmap = mpl.cm.RdBu_r
norm = mpl.colors.Normalize(vmin=spend_min, vmax = spend_max)
cb1 = mpl.colorbar.ColorbarBase(cax, cmap=cmap,
norm=norm,
orientation='vertical')
cb1.set_label("dolma sales (kg)")
{% endhighlight %}
### Add a title
Add a title to the subplot reserved for it. There are other ways to do this - f.suptitle() etc. but this gives me a lot of control.
{% highlight python %}
ax = plt.axes(dims[-1])
ax.annotate(title, xy = (0.5, 0.5), ha="center", va="center", fontsize = 24)
ax.axis("off")
{% endhighlight %}
### Let's check out our masterpiece
{% highlight python %}
plt.show()
{% endhighlight %}

Not bad for not a tonne of work. You can get the [actual notebook here](https://github.com/sidravi1/Blog/blob/master/nbs/Turkish_dolmas.ipynb).
If your map looks a little skewed, I'd go back and play around with your projections and find one that makes sense. Ok hack at it by playing with *xscale* and *yscale*.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-04-25-playing-with-sgdr.md
---
layout: "post"
title: "Playing around with SGDR"
date: "2018-04-25 10:50"
comments: true
use_math: true
---
This is an implementation of SGDR based on [this paper](https://arxiv.org/abs/1608.03983) by Loshchilov and Hutter. Though the cosine annealing is built into PyTorch now which handles the learning rate (LR) decay, the restart schedule and with it the decay rate update is not (though PyTorch 0.4 came out yesterday and I haven't played with it yet). The notebook that generates the figures in this can be found here.
Let's talk about what SGDR is and then look at how it compares with step LR decay. Finally, we'll look at how varying the two hyper-parameters, T<sub>i</sub> and T<sub>mult</sub>, affects performance.
## SGDR intro
If you have done any sort of gradient descent type optimization, you'll agree that tuning the learning rate is a pain. Techniques that use adaptive learning rates, like Adam, make life a little easier but [some papers have suggested](https://arxiv.org/abs/1705.08292) that they converge to a less optimal minima than SGD with momentum.
SGDR suggests that we use SGD with momentum with aggressive LR decay and have a 'warm restart' schedule. Here's the formula from the paper for setting the LR, $\eta_t$, at run $t$:
$$
\eta_t = \eta_{min}^i + \frac{1}{2}(\eta_{max}^i - \eta_{min}^i)(1 + \cos(\frac{T_{cur}}{T_i} \pi))
$$
Where:
- $\eta_{min}^i$ and $\eta_{max}^i$ are the minimum and maximum LR for the $i$-th run.
- $T_i$ is the number of epochs before we'll do a restart.
Another parameter that they mention is $T_{mul}$. They suggest increasing $T_i$ by a factor of $T_{mul}$ at each restart. Here's the figure from the paper that shows the LR for for various values of $T_i$ and $T_{mul}$ and the step decay.

Authors show that using this method, you need fewer epochs to achieve a similar performance as some other learning rate schedules. Less epochs means [less compute time](https://xkcd.com/303/).
## The setup
We'll just build off the standard [tutorial for transfer learning](http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html) in the pytorch docs. This is a model that uses resnet architecture and fine-tunes pre-trained weights to classify an image as an ant or a bee.
In the code in the notebook you'll notice a few alterations from the model. We use a bigger model, resnet151, when comparing the SGDR and step decay. We also randomize the weights for 40 modules so that they need to be relearnt from the data. We do 20 runs and calculate the mean and standard deviation of the loss. We use seeds to ensure that the 'randomness' in SGD (what's in a batch etc.) is the same for the models.
We are only using a small number of images to make it fast but you should try it for bigger datasets (there is a furniture classification competition on kaggle right now).
## SGDR vs. step decay
Note that I use a step-size of 60 and a gamma of 0.1 in the step decay LR model. This is coming straight from the tutorial. You may want to play with this and see what gamma and step-size give the lowest loss under this scheme. We also use 10 and 2 for T<sub>i</sub> and T<sub>mult</sub> respectively. These are values that the authors find works well for them.
Here's what the loss looks like. The shaded areas shows the 1 standard deviation bounds.

The authors note that we should be looking at the loss at the *end* of a cycle since it's going to be bouncing all over the place early on when the LR is high. Looks like we get to a minimum pretty quickly. After just 10 epochs we seem to have hit a minimum. It jumps back out and find another minima after 30 epochs again. Meanwhile, step decay gradually improves it's performance and seems to real a minima around the 65th epoch.
## Effect of tuning hyper-parameters
We re-ran SGDR with resnet50 with the parameters for T<sub>i</sub> and T<sub>mult</sub> suggested in the paper. Here's what it looks like.

Bit hard to compare them but it shows the standard deviation which is useful to know how consistent it is at finding the minima.
Let's compare the mean performance for these (with some RBF smoothing):

T<sub>i</sub> and T<sub>mult</sub> values of 1 and 2 respectively seems to be the best for our problem; the minima reached on the 59th epoch by these models is the lowest. Going back to the previous figure, we also note that the variation around this is tiny so we have some measure of confidence that these are indeed the hyper-parameters we should go with.
## Want to play some more?
Though this specific paper implements this on a SGD with momentum optimizer, the same authors showed that you can do it with Adam as well. Give it a go.
The advantage of SGDR is that you need fewer epochs to reach the minima. And the minima found at the end of each cycle may be a different one. They show that taking an ensemble of models at these different minima can improve predictive performance. We don't do this here but it's easy enough to save weights at the end of each cycle (the code for keeping the best model is up, it just needs to be tweaked to keep a set of them).
## Other references
You should check out the paper. There is a lot more in it and I gloss over a few details here. <NAME> had a [nice blog post](http://ruder.io/deep-learning-optimization-2017/index.html) that summarizes a number of recent advances in improving optimization in deep learning.
Distill had [an amazing blogpost](https://distill.pub/2017/momentum/) (the kind only a team like that could produce) that explains a lot of these method with some nice visualizations.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-05-04-back-to-basics-with-david-mackay-gibbs-slice-samplers.md
---
layout: "post"
title: "Back to basics with David Mackay #3: Gibbs & Slice samplers"
date: "2019-05-04 21:17"
comments: true
use_math: true
---
In this post, I just implement a Gibbs and a slice sampler for a non-totally-trivial distribution. Both of these are vanilla version -- no overrelaxation for Gibbs and no elliptical slice samplers, rectangular hyper-boxes etc. I am hoping you never use these IRL. It is a good intro though.
## Generating the data
Instead of the usual "let's draw from a 1-d gaussian" example, let's make our samplers work a bit. We're going to generate a mixture of three 2-d gaussians where the dimensions are correlated.
The following class creates such a distribution
{% highlight python %}
class GaussianMix(object):
def __init__(self, n_clusters, n_dims, means=None, cov=None, low=-3, high=3):
if means == None:
means = np.random.randint(low=low, high=high, size=(n_clusters, n_dims))
elif (means.shape[0] != n_clusters) or (means.shape[0] != n_dims):
raise RuntimeError("Incorrect dimensions for means")
if cov == None:
cov = np.empty((n_clusters, n_dims, n_dims))
for i in range(cov.shape[0]):
corr = st.random_correlation.rvs(np.random.dirichlet(alpha = np.ones(n_dims)) * n_dims)
sig = np.random.uniform(low=1, high=(high-low)/2, size=n_dims)
cov[i] = corr * sig.reshape(-1, 1) * sig
elif (cov.shape[0] != n_clusters) or (cov.shape[1] != n_dims) or (cov.shape[2] != n_dims):
raise RuntimeError("Incorrect dimensions for cov")
self.means = means
self.cov = cov
self.n_clusters = n_clusters
self.n_dims = n_dims
def rvs(self, size=100):
all_points = []
for dim in range(self.n_clusters):
points = st.multivariate_normal(self.means[dim], self.cov[dim]).rvs(size)
all_points.append(points)
return np.row_stack(all_points)
def pdf(self, x):
pdf_val = 0
for dim in range(self.n_clusters):
pdf_val += st.multivariate_normal(self.means[dim], self.cov[dim]).pdf(x)
return pdf_val / self.n_clusters
def get_weights(self, point, dim):
distance = np.zeros(self.n_clusters)
other_dims = np.delete(np.arange(self.n_dims), dim).squeeze()
point_other_dim = point[other_dims]
for i in range(self.n_clusters):
distance[i] = st.norm(self.means[i][other_dims], self.cov[i][other_dims][other_dims]).pdf(point_other_dim)
return distance / distance.sum()
{% endhighlight %}
Let's use this to generate a few different distribution to see what they look like.

So, not easy ones; Some islands, some covariance, some corner. Now let's write our samplers.
## Slice sampler
Here's a 2d slice sampler - we create two auxiliary variables. The code is based off the pseudo-code in Mackay's book. Note that the proposal boxes are squares and shrunk at the same rate. Not great since we know there is a lot of covariance. In a later post, we might check out some of the more advanced techniques to improve our proposal.
{% highlight python %}
def get_interval(x, dist, u, w = 0.1):
r = np.random.uniform(0, 1)
xl = x - r*w
xr = x + (1 - r) * w
while (dist.pdf(xl) > u).any():
xl = xl - w
while (dist.pdf(xr) > u).any():
xr = xr + w
return xl, xr
def modify_interval(x, x_prime, xl, xr):
dims = x.shape[0]
for d in range(dims):
if x_prime[d] > x[d]:
xr[d] = x_prime[d]
else:
xl[d] = x_prime[d]
return xl, xr
def slice_sampler2d(dist, n=1000, x_init = np.array([2, 1]), w = 0.5):
x_prime = x_init
all_samples = []
n_samples = 0
dim = np.shape(x_init)[0]
while n_samples < n:
# evaluate P*(x)
p_star_x = dist.pdf(x_prime)
# draw a vertical u' ~ U(0, P*(x))
u_prime = np.random.uniform(0, p_star_x, size=2)
# create a horizontal interval (xl, xr) enclosing x
xls, xrs = get_interval(x_prime, dist, u_prime, w=w)
# loop
break_out = True
iters = 0
x_old = x_prime
while break_out and (iters <= 1000):
# draw x' ~ U(xl, xr)
x_prime = np.random.uniform(xls, xrs)
# evaluate P*(x')
p_star_x = dist.pdf(x_prime)
# if P*(x') > u' break out of loop
if (p_star_x > u_prime).all():
break_out = False
# else modify the interval (xl, xr)
else:
xl, xr = modify_interval(x_old, x_prime, xls, xrs)
iters += 1
if iters == 1000:
print("!!! MAX ITERS")
all_samples.append(x_prime)
n_samples += 1
return np.row_stack(all_samples)
{% endhighlight %}
Let's see how it does for the last example distribution above.
{% highlight python %}
samples_slice = slice_sampler2d(dist, x_init=np.array([-4, 0]), n=10000, w=10)
{% endhighlight %}

Not bad! Generally the right shape though the lower island seemed to have been sampled less. We also seemed to have sufficient samples from the middle of the distribution but the tail samples seems to be missing.
## Gibbs sampler
We need to the conditionals for the Gibbs sampler. Since we are working with multivariate normals, that easy.
{% highlight python %}
def gaussian_conditional(mu, cov, dim, dim_vals):
# roll axis to get the dimension of interest to the top
sig = np.roll(np.roll(cov, -dim, axis=0), -dim, axis=1)
mu_2 = np.delete(mu, dim)
mu_1 = mu[dim]
sig_11 = sig[0, 0]
sig_12 = sig[0, 1:]
sig_21 = sig[1:, 0]
sig_22 = sig[1:, 1:]
sig_22_inv = np.linalg.pinv(sig_22)
mu_bar = mu_1 + sig_12 @ sig_22_inv @ (dim_vals - mu_2)
sig_bar = sig_11 - sig_12 @ sig_22_inv @ sig_21
return mu_bar, np.sqrt(sig_bar)
{% endhighlight %}
The tricky part is picking which gaussian conditional to draw from. Remember that we have 3 multivariate gaussians. So any given point could have come from any of those three. But we know how likely it is that they came from each of those. We can just use these as weights and draw from a multinomial to pick conditional distribution.
The code to get the weights is already included in the `GaussianMix` class above. Here's the code for the sampler.
{% highlight python %}
def gibbs_sampler_mix(gm, init=[0.0, 1.0], n_samples = 1000):
dim_vals = np.array(init, dtype='float')
samples = []
n_dims = gm.n_dims
for i in range(n_samples):
for dim in range(n_dims):
if dim == (n_dims - 1):
next_dim = 0
else:
next_dim = dim + 1
cond_vals = np.delete(dim_vals, dim)
weights = gm.get_weights(dim_vals, dim)
c_id = st.multinomial(1, weights).rvs()
cluster_id = np.argmax(c_id)
mu_bar, sig_bar = gaussian_conditional(gm.means[cluster_id],gm.cov[cluster_id], dim, cond_vals)
dim1_sample = np.random.normal(mu_bar, sig_bar)
dim_vals[dim] = dim1_sample
samples.append(dim_vals.copy())
return np.row_stack(samples)
{% endhighlight %}
Let's draw!
{% highlight python %}
samples_gibbs = gibbs_sampler_mix(dist, init=[0, 0], n_samples = 10000)
{% endhighlight %}

We burned the first 5000 samples and plotted the rest. Now we have plenty of samples (too many?) from the tails and the shape of the core is still approximately correct.
## Comparison
We can do better than visual inspection though. Let's just generate a 1000 different distributions and compare the KL divergence across a marginal between the samples from `GaussianMix` and samples from the two samplers.
I've trimmed the values greater than 1.0 for readability.

So Gibbs does better than slice with lower KL divergence scores. But not always.
Here are some where Gibbs does better than slice:

And some where slice does better than Gibbs:

For multimodal distributions, slice does better than Gibbs. There may be a better Gibbs sampler that overcomes this but this makes sense for our implementation. The multinomial draw is very unlikely to shift you to the other far away gaussians if you stuck in one.
So if you have little covariance and the distribution is unimodal (and you have the conditionals!) the Gibbs rocks it. The covariance thing is not a deal breaker though (see overrelaxation) but not sure how I'd get over the multimodal problem in my example.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2020-04-10-large-scale-hypothesis-testing.md
---
layout: "post"
title: "Large-Scale Hypothesis Testing (Part 1)"
date: "2020-04-10 17:38"
comments: true
use_math: true
---
We take a short detour from Bayesian methods to talk about large-scale hypothesis testing. You all are probably quite familiar with the p-hacking controversy and the dangers of multiple testing. This post isn't about that. What if you are not confirming a single hypothesis but want to find a few interesting "statistically significant" estimates in your data to direct your research?
This post is based on Chapter 15 of [Computer Age Statistical Inference (CASI)](https://web.stanford.edu/~hastie/CASI_files/PDF/casi.pdf) by <NAME> Efron.
## Large-scale Testing
The example in CASI is of microarray study of 52 prostate cancer patients and 50 controls. This microarray allows you to measure the individual activity of 6033 genes. We want to identify which of the difference in gene activity between the patients and the controls is significant. In hypothesis testing land, that's 6033 t-tests.
### The null Hypothesis
If we have $i$ genes, we have $i$ hypothesis tests and therefore $i$ nulls. Our null hypothesis, $H_{0i}$ is that patients' and the controls' responses come from the same normal distribution of gene $i$ expression. The t-test for gene $i$ will follows a [Student $t$ distribution](https://en.wikipedia.org/wiki/Student%27s_t-test#Independent_(unpaired)_samples) with 100 (50 + 52 - 2) degrees of freedom. Let's map this to the normal distribution:
$$
z_i = \Phi^{-1}(F_{100}(t_i))
$$
where $F_{100}(t_i)$ is the cdf of the $t_{100}$ distribution and $\Phi^{-1}$ is the inverse cdf of the normal distribution.
Now we can state our null hypotheses as:
$$
H_{0i} : z_i \sim \mathcal{N}(0, 1)
$$
You probably already know that you can't just run all the 6033 hypothesis tests and pick the ones with p < 0.05. 5% of them will be "significant" even when the null is true. Even if you don't remember the definition of p-value from school, you can just simulate it to prove it to yourself:
{% highlight python %}
# Simulation 100 t-tests with 0.05
dist1 = np.random.normal(0, 1, size = (1100, 100))
dist2 = np.random.normal(0, 1, size = (1100, 100))
_ , p_vals = st.ttest_ind(dist1, dist2, axis = 1)
{% endhighlight %}

The red bar shows the 5% of the samples that show up as significant at the 5% level even though we know that both samples came from the same distribution.
For the prostate data, the z-vals match the null distribution quite well. Maybe it's a little fatter on the tails suggesting we may have some interesting stuff going on.

### Bonferroni bounds
You probably also remember the Bonferroni correction. If you're going to do 6033 hypothesis tests then the one-sided Bonferroni threshold for significance is $\alpha / 6033$. The idea is to keep the *family-wise error rate*, the probability of making even one false rejection, to below $\alpha$.
Using the prostate data, 4 genes that shows up as significant at the Bonferroni threshold of $\frac{0.05}{6033} = 8.3 \times 10^6$.
### Holm's procedure
Holm's is bit better than Bonferroni. Here's how that goes:
1. Sort p-vals from smallest to largest:
$$
p_{1} \leq p_{2} \leq ... \leq p_{i} \leq ... \leq p_{N}
$$
2. Let $i_0$ be the smallest index $i$ such that
$$
p_{i} > \alpha / (N - i + 1)
$$
3. Reject all the $H_{0i}$ for $i < i_0$.
On the prostate data this gives 5 significant genes, one more than the Bonferroni correction.
## Benjamini–Hochberg FDR Control
Most of the time when we're doing this sort of multiple testing, we're going on a fishing expedition. We are hoping that to find some interesting things worth further investigating. It's more exploratory analysis than inference. So another way we may think about the problem is that we want to minimise the probability of making an error - rejecting the null when we shouldn't have.
Here's a figure taken from CASI:
<img src="{{'/assets/20200410_fig15.2.png' | absolute_url}}" alt="alt text" width="600">
Under some decision rule, $\mathcal{D}$, you choose to reject $R$. $a$ of them would be wrong (should not be rejecting) and $b$ would be correct. We don't know $a$, so we can't calculate the "false-discovery proportion" (Fdp) of $\alpha / R$. But under certain circumstances we can control its expectation:
$$
FDR(\mathcal{D}) = \mathbf{E}\{Fdp(\mathcal{D})\}
$$
We'd want to come up with a decision $\mathcal{D}_q$ that keep this $FDR$ below $q$:
$$
FDR(\mathcal{D}) \leq q
$$
Here's the procedure that does that. See book for theorem and proof.
1. Sort p-vals from smallest to largest:
$$
p_{1} \leq p_{2} \leq ... \leq p_{i} \leq ... \leq p_{N}
$$
2. Define $i_{max}$ to be largest index for which
$$
p_{i} \leq \frac{i}{N}q
$$
3. Reject all the $H_{0i}$ for $i < i_{max}$.
### Comparison with Holm's
Holm's rejects null, $H_{0i}$, if:
$$
p_i \leq \frac{\alpha}{N - i + 1}
$$
and $\mathcal{D}_q$ has threshold:
$$
p_i \leq \frac{q}{N}i
$$
For the prostate data, we can compare the two methods:

FDR is a lot more generous and rejects the 28 most extreme z-vals. The slope for the Holm's procedure is barely noticeable.
## Empirical Bayes Large-Scale Testing
Ok - I lied. The thing that really got me writing this blogpost was restating the multiple testing problem in a Bayesian framework. The algorithm for $\mathcal{D}_q$ above can be derived from this Bayesian re-interpretation.
Let's think about it as a generative model. Each of the $N$ cases (6033 in the prostate example) is either null or not-null. So the $z$-score we came up with above come from either the null distribution $f_0(z)$ or some other, non-null distribution, $f_1(z)$. Let's say the probability of a null is $\pi_0$ and and non-null is $\pi_1 = 1 - \pi_0$. So we have:
$$
\begin{aligned}
\pi_0 &= Pr\{null\} &&f_0(z)\text{ density if null} \quad &&\\
\pi_1 &= Pr\{non\text{-}null\} &&f_1(z)\text{ density if non-null}&&
\end{aligned}
$$
In the prostate case, $\pi_0$ is close to one; most of the genes differences are not significant. And $f_0$ is the standard normal here (though it doesn't always have to be). Few other definitions: $F_0$ and $F_1$ are the cdfs for $f_0$ and $f_1$ with "survival curves":
$$
S_0(z) = 1 - F_0(z)\\
S_1(z) = 1 - F_1(z)
$$
What we actually observe is a mixture of the two. So we have:
$$
S(z) = \pi_0 S_0(z) + \pi_1 S_1(z)
$$
Now let's define the Bayesian Fdr as the probability that the case really is null when our $z$ value is greater than some rejection threshold, $z_0$:
$$
\begin{aligned}
Fdr(z_0) &\equiv Pr(\text{case i is null}| z > z_0) \\
&= \frac{Pr(\text{case i is null}, z > z_0)}{P(z > z_0)}\\
&= Pr(z > z_0 | \text{case i is null}) \frac{Pr(\text{case i is null})}{Pr(z > z_0)}\\
&= S_0(z_0) \frac{\pi_0}{S(z_0)}
\end{aligned}
$$
We know that $\pi_0$ is close to one. We also know that our null distribution is a standard normal so $S_0(z_0)$ is just $1 - \Phi(z_0)$. Only thing left is to figure out $S(z_0)$ and we just do this empirically:
$$
\hat{S}(z_0) = N(z_0)/N \quad \text{where } N(z_0) = \#\{z_i \geq z_0\}
$$
So we now have the empirical false discovery rate:
$$
\widehat{Fdr}(z_0) = \pi_0 \frac{S_0(z_0)}{\hat{S}(z_0)}
$$
### Equivalence to Benjamini-Hochberg
Now here's the fun bit. Note that the p-value for $i$ is the probability that you observe something this or more extreme given the null hypothesis. That's exactly what $S_0(z_i)$ is. So we have:
$$
p_i = S_0(z_i)
$$
and $\hat{S}(z_i) = i / N$ if $z_i$ are sorted and $i$ is the index. Sub these into the equation in step 2 above and you get:
$$
\begin{aligned}
S_0(z_i) &\leq \hat{S}(z_i)\cdot q\\
\frac{S_0(z_i)}{\hat{S}(z_i)} &\leq q\\
\widehat{Fdr(z_i)} &\leq \pi_0 q
\end{aligned}
$$
the last line is by multiplying $\pi_0$ on both sides.
## Final words
So when you are using the Benjamini-Hochberg algorithm, you are rejecting the cases where the posterior of coming from the null distribution is too small.
There are other things to talk about. With the Bayesian framework, why look at $ Pr(\text{case i is null} \vert z_i > z0)$ when we can do $Pr(\text{case i is null} \vert z_i = z0)$. It makes a lot more sense. These lead us to *local* false-discovery rates and another blog post.
The untidy notebook can be found [here](The notebook can be found [here](https://github.com/sidravi1/CASI_Examples/blob/master/nbs/Ch15_Large_Scale_Testing.ipynb).). Thanks for reading.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-11-10-logit-choice-model.md
---
layout: "post"
title: "Logit Choice Model"
date: "2019-11-10 20:51"
comments: true
use_math: true
---
I've been working my way through <NAME>'s ["Discrete Choice Methods with Simulation"](https://eml.berkeley.edu/books/train1201.pdf) and playing around with the models and examples as I go. Kind of what I did with Mackay's book. This post and the next have are some key takeaways with code from chapter 3 - Logit.
You can [check out the notebooks](https://github.com/sidravi1/Blog/tree/master/nbs/logit_choice) for this post and the next [here](https://github.com/sidravi1/Blog/tree/master/nbs/logit_choice).
## Utility model
A decision maker, $n$, faces $J$ alternatives. We can decompose the utility that the decision maker gets from each alternative as:
$$
U_{nj} = V_{nj} + \epsilon_{nj}\,\,\forall j
$$
$V_{nj}$ is the known bit - what we can model and $\epsilon_{nj}$ is the iid error term.
### Specifying $V_{nj}$
Linear. It does the job.
$$
V_{nj} = \beta ' x_{nj}
$$
Also, as Train points out: "Under fairly general conditions, any function can be approximated arbitrarily closely by one that is linear in parameters." You can get fancier though if you like and use something flexible like Cobb-Douglas if you like.
### Gumbel errors
We get the logit model by assuming that that $\epsilon_{nj}$ follows a Gumbel distribution. Train claims this is not that hard a pill to swallow - it's nearly the same as assuming the errors are independently normal. It just give fatter tails than a normal so allows the decision maker to get a little more wild.

But if we *are* comfortable with this assumption, then the difference of two Gumbel distributions:
$$
\epsilon^* _ {nji} = \epsilon_{nj} - \epsilon_{ni}
$$
follows as logistic distribution:
$$
F(\epsilon^* _ {nji}) = \frac{exp(\epsilon^* _ {nji})}{1 + exp(\epsilon^* _ {nji})}
$$

What might be harder tmo swallow is that the errors are iid. We are saying that the errors for a decision maker <u>between</u> alternatives are independent. Train doesn't stress about this too much though; he claims that if you do a good job of specifying $V_{nj}$, then the rest is basically white noise.
But the key takeaway here is:
Violations of the logit assumptions seem to have less
effect when estimating average preferences that when
forecasting substitution patterns.* (pg. 36)
Nice. We'll do an experiment later to test one of these violations as well.
### From utility to probabilities
You can check out the book for the derivation. I'll just outline the key bits that will be relevant when we do some simulations.
The probability that the decision maker chooses alternative $i$ over $j$ is:
$$
\begin{aligned}
P_{ni} &= Prob(V_{ni} + \epsilon_{ni} \gt V_{nj} + \epsilon_{nj} \,\, \forall j \ne i) \\
& ...\\
&<insert\,\, math>\\
& ...\\
P_{ni} &= \frac{exp(\beta' x_{ni})}{\sum_j exp(\beta' x_{nj})}
\end{aligned}
$$
A decision maker is simply comparing two utilities and picking the one that is higher. We don't get to see those idiosyncratic errors but the decision maker experiences them.
## Power and Limitations of the Logit
Logit has some nice properties - the bounds on $P_{ni}$, the sigmoid shape. And this has some implications on modelling which we won't go into here.
The key thing here is to remember that the coefficients don't have any meaning but *their ratio* does. So if you model utility as
$$
U_{ni} = \beta_1 x_{1,ni} + \beta_2 x_{2,ni} + \epsilon_{ni}
$$
Then the ratio of $\beta_1 / \beta_2$ has meaning. For example, if $x_1$ represents price and $x_2$ is operating cost, $\beta_1 / \beta_2$ represents the decision maker's willingness to pay for operating cost reductions in up front price. Scale of the individual parameters doesn't really matter - and this is also makes fitting them a little tricky sometimes.
### Taste variation
Finally, some modelling.
Utility can be based on features of the car AND the household i.e we can model taste variation amongst the decision makers. Here's the two param example from the book. Reminder that $n$ represents the decision maker and $j$ the alternative. Here ${PP}_{j}$ is the purchase price for car $j$, and ${SR}_{j}$ is the shoulder room in the car.
$$
U_{nj} = \alpha_n {SR}_j + \beta_n{PP}_j + \epsilon_{nj}
$$
Each household has it's own $\alpha$ and $\beta$ i.e. how much weight they put on these features of the car, based on some characteristics of the household - $M_n$ (size of family) and $I_n$ (income).
$$
\alpha_n = \rho M_n\\
\beta_n = \theta / I_n
$$
Substituting these into first equation:
$$
U_{nj} = \rho (M_n {SR}_j) + \theta ({PP}_j / I_n) + \epsilon_{nj}
$$
So we are down to estimating $\rho$ and $\theta$. The rest of the $V_{nj}$ part of the utility are features of the car and household that are given.
We're going to make up some data for households choosing between three cars. It's similar to the example in the book but instead of 2 params ($\rho$ and $\theta$), let's do 10 - because computers - and we'll call them $\beta$s.
{% highlight python %}
utility = (betas * households) @ cars.T + errors
choice = np.argmax(utility, axis=1)
car_choice_simple = np.zeros_like(utility)
car_choice_simple[np.arange(car_choice_simple.shape[0]), choice] = 1
{% endhighlight %}
That's it. We're done setting up the data. Now let's see if we can recover the $\beta$ parameters (or rather, the ratios of these).
**Outside option**
We need to "pin down" one of the utilities else the model is not identified. Remember that scale of the betas doesn't matter so an infinite sets of betas can fit the model. What we'll do to get around this is to make the first car the "outside option" and say that the decision maker gets a utility of zero when she chooses that. The rest will be relative to this.
To achieve this, let's make all the features relative to the first car.
{% highlight python %}
cars_oo = cars - cars[0]
{% endhighlight %}
So now, all the features of car 1 are zeros which means the household will get a utility of zero as well.
**Pymc3 model**
The likelihood of the model is derived in section 3.7 of the book and is basically:
$$
\mathbf{LL}(\beta) = \sum_{n=1}^{N} \sum_{i} y_{ni} \ln P_{ni}
$$
Look familiar? Yep, it's a multinomial likelihood. You can write it out as a custom density, and I did, but the sampler is sooo much faster when using the optimized multinomial likelihood that comes built-in.
{% highlight python %}
with pm.Model() as m_simple:
betas_rest = pm.Normal('betas', 0, 1, shape=(1, n_params))
utility_ = tt.dot((betas_rest * households), cars_oo[1:].T)
utility_zero = pm.Deterministic('utility', tt.concatenate([tt.zeros((n_households, 1)), utility_], axis=1))
p = pm.Deterministic('p', tt.nnet.softmax(utility_zero))
pm.Multinomial('ll', n=1, p=p, observed = car_choice_simple)
{% endhighlight %}
How did we do?
{% highlight python %}
trace = pm.sample(draws=500, model=m_simple, tune=5000, target_accept=0.95)
scaled_trace = trace['betas'].squeeze()
scaled_trace = scaled_trace / scaled_trace[:, 0].reshape(-1, 1)
{% endhighlight %}
That last line is "de-scaling" it. As we mentioned above, we'll only look at the betas with reference to the first one.

:D
You can dial up the gumbel noise and try to break it. I found it to be pretty robust.
**When taste change randomly**
Logit breaks down when tastes don't vary systematically i.e. based on features of the household in our example, but rather each household has some randomness to their tastes. But as we'll see and as Train points out, logit models are pretty robust to misspecification when you want to understand average tastes.
Now the household tastes have some randomness:
$$
\begin{aligned}
\alpha_n &= \rho M_n + \mu_n\\
\beta_n &= \theta / I_n + \eta_n
\end{aligned}
$$
So the utility now becomes:
$$
\begin{aligned}
U_{nj} &= \rho (M_n {SR}_j) + \mu_n {SR}_j + \theta ({PP}_j/I_n) + \eta_n {PP}_j + \epsilon_{nj}\\
U_{nj} &= \rho (M_n {SR}_j) + \theta ({PP}_j/I_n) + \tilde{\epsilon}_{nj}
\end{aligned}
$$
$\tilde{\epsilon}_{nj}$ is no longer iid since they are correlated within the same decision maker, $n$. Let's simulate this data:
{% highlight python %}
taste_errors = np.random.normal(4, 4, size = (n_households, n_params))
utility = (betas * households + taste_errors) @ cars.T + errors
{% endhighlight %}
We'll skip the rest of the code here which is basically the same as above and go straight to the results.

We get some large credible intervals but still not terrible. The actual value (mostly) lies within the 95% CI. In the notebook, I do another experiment where I model the taste errors as well it does a little better.
### Substitution patterns
A feature (or bug if you're not ok with the implications) of the logit model is how substitution occurs. It can be seen in two ways.
**Independence from Irrelevant Alternatives (IIA)**
For any two alternatives $i$ and $k$, the ratio of the logit probabilities is
$$
\begin{aligned}
\frac{P_{ni}}{P_{nk}} &= \frac{exp(V_{ni}) / \sum_j exp(V_{nj})}{exp(V_{nk}) / \sum_j exp(V_{nj})}\\
&= \frac{exp(V_{ni})}{exp(V_{nk})} = exp(V_{ni} - V_{nk})
\end{aligned}
$$
No other alternatives but $k$, and $i$ enter this. So if some other alternative $l$ changes, it will effect the absolute probabilities of picking $k$ and $i$ but not the <u>*ratio*</u> of their probabilities.
Let's check this out in our example (in logs to avoid overflow):
{% highlight python %}
utility = (betas * households) @ cars.T + errors
p_base = sp.special.softmax(utility, axis=1)
p_base_ratio_12 = np.log(p_base[:, 1]) - np.log(p_base[:, 2])
# let's "improve" car 0
cars_0_improved = cars.copy()
cars_0_improved[0] = cars_0_improved[0] * 2
utility_car0_imp = (betas * households) @ cars_0_improved.T + errors
p_car0_imp = sp.special.softmax(utility_car0_imp, axis=1)
p_car0imp_diff12 = np.log(p_car0_imp[:, 1]) / np.log(p_car0_imp[:, 2])
np.all(np.isclose(p_car0imp_ratio_12, p_base_ratio_12))
#> True
{% endhighlight %}
This might not always make sense. The book provides the blue bus, red bus example. Say there are two modes of transport available - a blue bus and a car. Then a red bus gets introduced that travellers consider to be the same as the blue bus. The ratio of probabilities of blue bus and the car will clearly change. Half the people using the blue bus will switch to the red bus but none of the car drivers will. If you have this sort of situation, logit might not the right model.
### Proportional Substitution
The same "issue" can be seen in terms of cross-elasticities. When an alternative improves, it changes the other probabilites proportional to their original values. It's just easier to show you in code
{% highlight python %}
diff_imp_car0 = p_car0_imp[:, 0] - p_base[:, 0]
# estimated change in car 1's probabilities as per proportion
diff_imp_car1_prop = diff_imp_car0 * p_base[:, 1]/(p_base[:, 1] + p_base[:, 2])
# actual change in car 1's probabilities
diff_imp_car1 = p_base[:, 1] - p_car0_imp[:, 1]
np.all(np.isclose(diff_imp_car1_prop, diff_imp_car1))
#> True
{% endhighlight %}
## Next up - advantages of IIA
This post got a bit long so I'll save the remainder for [another (shorter) post]({{ site.baseurl }}{% post_url 2019-11-11-logit-choice-advantages-of-iia %}). You can check that one out here. Notebooks for this post and the next are on github [here](https://github.com/sidravi1/Blog/tree/master/nbs/logit_choice).
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-03-10-the-connection-between-simulated-annealing-and-mcmc-part-3.md
---
layout: "post"
title: "The connection between Simulated Annealing and MCMC (Part 3)"
date: "2018-03-10 15:00"
use_math: true
comments: true
---
Check out [part 1]({{ site.baseurl }}{% post_url 2018-03-01-the-connection-between-simulated-annealing-and-mcmc-part-1 %}) and [part 2]({{ site.baseurl }}{% post_url 2018-03-02-the-connection-between-simulated-annealing-and-mcmc-part-2 %}). Let's start off by writing the code for the Metropolis algorithm and comparing it to Simulated Annealing.
{% highlight python %}
def metropolis(p, qdraw, nsamp, stepsize, initials):
samples=np.empty((nsamp, 5))
x_prev =initials['xinit']
for i in range(nsamp):
x_star = qdraw(x_prev, stepsize)
p_star = p(x_star)
p_prev = p(x_prev)
# note that p is in logs!
pdfratio = p_star - p_prev # (1)
threshold = np.random.uniform()
alpha = min(1, np.exp(pdfratio))
if threshold < alpha:
samples[i] = x_star # (2)
x_prev = x_star
else:
samples[i]= x_prev # (3)
return samples
{% endhighlight %}
Here's the simulated annealing algorithm again but using the same variable names where it makes sense.
{% highlight python %}
def annealing(p, qdraw, nsamp, initials):
L = initials['L']
T = initials['T']
x_prev =initials['xinit']
for e in range(nsamp):
for l in range(L):
x_star = qdraw(X)
p_star = p(x_star)
p_prev = p(x_prev)
pdfratio = p_prev - p_star # (1)
threshold = np.random.uniform()
alpha = min(1, np.exp(pdfratio/T))
if (p_star < p_prev) or (threshold < alpha ):
x_prev = x_star
# Let's keep track of the best one
if p_star < p_prev:
x_best = x_star # (2)
# Let's calculate new L and T
T = T * 0.85
L = L * 1.1
return x_best
{% endhighlight %}
Let's start off by writing the code for the Metropolis algorithm and comparing it to Simulated Annealing.
## Similarities and differences
1. In both, we have a proposal function that generates an *x_star*
2. In both, we calculate the probability of the target distribution at *x_star*
3. Temperature for Metropolis is just 1 (T = 1).
4. Note that in SA, we move from *x_prev* to *x_star* in SA if the new energy, or the value of the target function, is lower. In Metropolis, we move if the probability mass function of the target distribution is higher.
5. We always take a sample in Metropolis.
It's pretty remarkable how similar they are.
## Why does it work?
The main reason this works is because of "detailed balance" which you may remember from the post on Markov Chains. We said that if $\pi_{i} p_{ij} = p_{ij} \pi_{j}$ then $\pi$ is a stationary distribution. Detailed balance for continuous variables is:
$$
f(x)p(x,y) = f(y)p(y,x)
$$
Now, if this is true (and proof isn't too hard), then you know that *f* is a stationary distribution for the chain. And since it is stationary, each step in the Markov Chain lands us back in *f*. This means that all the samples that we draw are coming from *f*.
If you squint hard enough, you'll notice that even in simulated annealing, we're drawing from a stationary distribution at each temperature.
It may take a little while for the chain to get to that stationary distribution depending on where you start but once you're there you're (by definition) stuck in the stationary distribution. But how do you know that you actually made it to your stationary distribution? The truth is that you don't really. There are signs that you *haven't* made it to the stationary distribution so high dose of paranoia is advised.
We'll talk about *burnin*, *autocorrelation*, Gewecke, and Gelman-Rubin test, in a future post.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2020-04-12-large-scale-hypothesis-testing-part-2.md
---
layout: "post"
title: "Large-Scale Hypothesis Testing (Part 2)"
date: "2020-04-12 22:06"
comments: true
use_math: true
---
In [part 1]({{ site.baseurl }}{% post_url 2020-04-10-large-scale-hypothesis-testing %}), we looked at Empirical Bayes Large-Scale Testing where we defined the data generating process as a mixture model. In this post, instead of empirically estimating $S(z)$, we assume it's a mixture of two gaussian and define a mixture model in pymc3. We finish by considering the *local* false discovery rate, which has a much cleaner bayesian interpretation.
This post is also based on Chapter 15 of [Computer Age Statistical Inference (CASI)](https://web.stanford.edu/~hastie/CASI_files/PDF/casi.pdf) by <NAME> Efron.
## Large Scale Testing as a mixture of gaussians
In the previous post, we defined our data generating process for the z-scores of the gene activity t-tests as:
$$
S(z) = \pi_0 S_0(z) + \pi_1 S_1(z)
$$
Where $S_0(z)$ and $S_1(z)$ are the survival function of the null distribution (the standard normal), and the non-null distribution, respectively. We showed the error rate to be:
$$
Fdr(z_0) = \pi_0 \frac{S_0(z_0)}{S(z_0)} < \pi_0 q
$$
### Problem as a mixture of normals
Instead of estimating $S(z)$ using the empirical distribution, we assume $S_1(z)$ is also a normal and just model it as a mixture. Here's the model in pymc3:
{% highlight python %}
with pm.Model() as m:
sd = pm.HalfNormal('sd', 3)
dist1 = pm.Normal.dist(0, 1)
dist2 = pm.Normal.dist(0, sd)
pi = pm.Dirichlet('w', a= np.array([0.9, 0.1]))
like = pm.Mixture('like', w=pi, comp_dists=[dist1, dist2], observed=x1)
{% endhighlight %}
Here are the posterior draws:

The posterior for `sd` is mostly between 1.5 and 1.8 which makes sense. Now that we have $S_1$ and $\pi_0$ we can calculate the distribution of $S(z)$. Plug these into the $Fdr$ equation above and we can identify the non-nulls with some error rate $q$.
{% highlight python %}
F1 = st.norm(0, sample['sd']).cdf(x1.reshape(-1, 1))
F0 = st.norm(0, 1).cdf(x1.reshape(-1, 1))
S = (sample['w'][:, 0] * (1 - F0)) + (sample['w'][:, 1] * (1 - F1))
S_ratio = (1 - F0) / S
low, high = np.percentile(S_ratio, [2.5, 97.5], axis = 1)
significant_idx = np.argwhere((high <= 0.1)).squeeze()
{% endhighlight %}
Here's the histogram of the 6033 $z$ values again with the significant results show in the rug plot:

You could repeat this and use the cdf instead of the survival functions in the code above to get the negative significant values.
## Local False-Discovery Rates
After this whole Bayesian re-interpretation, it doesn't really make a lot of sense to be looking at tail-area, $z_i \geq z_0$. Why not just look at the probability or pdf of $z_i = z_0$. What we want is the *local false discovery rate (fdr)*:
$$
fdr(z_0) = Pr\{\text{case i is null }\vert\, z_i = z_0\}
$$
A similar logic follows to the tail-area false discovery rate and you can check out the book for more details. But you may not be too surprised to learn that we get something very similar to the tail area fdr:
$$
\widehat{fdr}(z_0) = \left. \pi_0 f_0(z_0) \middle/ \hat{f}(z_0)\right.
$$
### Fitting $f(z)$
We could estimate $\hat{S}(z_0)$ empirically and it was fairly smooth since we were working with a cdf. Using the same method here would give us a noisy estimate since we'll only have a point or two to estimate a pdf, $f$. We need to smooth it out. You could do this in a number of ways but CASI chooses to fit a Poisson distribution to the binned values with the latent variable modelled as a 4th degree polynomial, so let's go with that.
{% highlight python %}
from sklearn.preprocessing import PolynomialFeatures
import statsmodels.api as sm
vals, edges = np.histogram(-trans_t, bins=45, density=True)
mid_points = (edges[0:-1] + edges[1:]) / 2
X = PolynomialFeatures(degree=4).fit_transform(mid_points.reshape(-1, 1))
y = vals
m = sm.GLM(y, X, family=sm.families.Poisson(), ).fit()
y_hat = m.predict()
{% endhighlight %}
And here's the fit:

### Calculate *fdr*
We know that $f_0(z)$ is a standard normal and now have a fitted $f(z)$. We just need to plug this back into the equation for fdr (we can assume $\pi_0$ to be close to 1). These two functions can do that for us:
{% highlight python %}
def fhat(z, m):
n_dims = m.params.shape[0]
poly_vals = PolynomialFeatures(degree=(n_dims - 1)).fit_transform(z.reshape(-1, 1))
return np.exp(poly_vals.squeeze() @ m.params)
def fdr_hat(z, m, pi0 = 0.9):
return pi0 * st.norm.pdf(z) / fhat(z, m)
{% endhighlight %}
Now we can plot the local false discovery rates and the tail-area false discovery rates to do a comparison:

The local fdr is a lot stricter. In both tails, it requires a larger threshold for the same rate of false discovery $q$, shown in the figure at 0.2.
### Full bayesian model again
Earlier in the post, we fitted a mixture model. We can use that here again. $f_1(z)$ is a zero-mean normal with standard deviation between 1.5 and 1.8. We can calculate the local fdr as before using this.
Let's add this to the plot above:

The bayesian version is not as conservative as the glm fitted local fdr but results are pretty similar. And hey! Confidence intervals.
## Conclusions
You probably been Bonferroni-ing it like me. And that's perfecting fine in most cases where you are testing 5-10 hypothesis. When you start getting in the thousands, you can actually do much better. You can use the *other* estimates to inform the significance of a particular *estimate*, a property you usually associated with bayesian methods. And there is indeed a bayesian interpretation.
The notebook can be found [here](https://github.com/sidravi1/CASI_Examples/blob/master/nbs/Ch15_Large_Scale_Testing.ipynb). I stopped cleaning up notebooks at some stage. It has a lot of failed experiments and other extensions but it's messy and badly commented. Don't judge me.
Thanks for reading. Happy hunting.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-03-06-back-to-basics-i.md
---
layout: "post"
title: "Back to Basics with David MacKay #1 "
date: "2019-03-06 22:25"
comments: true
use_math: true
---
There are two ways of learning and building intuition. From the top down, like [fast.ai](https://www.fast.ai/2016/10/08/teaching-philosophy/) believes, and the bottom up, like <NAME>'s deep learning course on coursera. I'm not sure what my preferred strategy is.
While learning Bayesian analysis, I've gone back and forth. <NAME> has [a great lecture](http://videolectures.net/mackay_course_10/) where he introduces Bayesian inference using a very small dataset of 8 data points. It was a cool way to introduce the topic so I decided to implement it. I learnt a tonne of stuff -- not the least, animating 3d plots -- doing it and refined my intuition. You can find the [notebook here](https://github.com/sidravi1/Blog/blob/master/nbs/MacKay_bayesian_exp.ipynb).
## Problem setup
You have 8 data points as follows:
$$
X = [ 0.64,\,0.016,\,0.1,\,0.05,\,3.09,\,2.14,\,0.2,\,7.1]
$$
We assume that this comes from one (or two) exponential processes.
We need to answer the following questions:
2. What is the rate parameter assuming this comes from just one exponential process?
3. What are the rate parameters assuming this comes from just two exponential processes?
4. Which model, one process or two processes, is better supported by the data?
## One process
First the easy stuff. Since it is an exponential, we can define likelihood, $P(x\vert\lambda)$, as
$$
P(x|\lambda) = \prod_{i=1}^{8} \frac{1}{\lambda} exp(-\frac{\lambda}{x_i})
$$
$x$ is given, so let's see what this looks like
<div style="text-align: center">
<img src="/assets/2019_03_06_one_process.png" align="middle" alt="one process" width="600"/>
</div>
<br>
*N.B: Why is the plot black? Idk. I spent too long replicating David Mackay's style -- then discovered that it is just the classic gnuplot colors. But it looks nice I think.*
The blue line shows what lambda could be. If you pushed me for a point estimate, I might give you the MAP value which is shown by the orange line.
Note that we are assuming that all lambdas are equally likely (flat prior). We know that's rubbish but let's pretend for the sake of this exercise.
### The evidence
The evidence is given by :
$$
\begin{align}
P(x) = \int_0^{\infty} P(x|\lambda)\, d \lambda \\
\hat{P}(x) = \sum_{i=1}^{N} P(x|\lambda_i)\,P(\lambda) \\
\hat{P}(x) = \frac{1}{N} \sum_{i=1}^{N} P(x|\lambda_i) \\
\end{align}
$$
That just taking the mean of all the likelihoods since we are assuming a
flat prior on lambda:
```
evidence1 = all_likelihoods.mean()
```
## Two processes
Now for the fun bit. What if we had two exponential processes, with rate parameters $\lambda_0$ and $\lambda_1$ respectively?
Let $k$ define the vector of assignment of each of the data points to one of the two processes. So $k_i$ == 1's say we knew the process assignments $k$. So for example, $k$ could be $[1\, 0\, 0\,0\,0\,1\,1\,1]$ which says that the first and the last three points come from process 2 while the rest come from process 1. If we do know $k$, we can calculate the likelihood as follows:
$$
\begin{aligned}
P(\mathbf{x}|\lambda_0, \lambda_1, \mathbf{k}) &= \prod_{i=1}^{8} \frac{1}{\lambda_{k_i}} exp(-\frac{\lambda_{k_i}}{x_i})
\end{aligned}
$$
So for a given vector $k$, we can get the likelihood for all combinations of $\lambda_0$ and $\lambda_1$. Since $\vert k \vert$ is 8, there are $2^8$ possible $k$ vectors. We can just iterate over all of these $k$ vectors and calculate the likelihood. The seizure-inducing gif below shows the likelihood for all combinations of $\lambda_0$ and $\lambda_1$ for every possible $k$ - all $2^8$ of them.
<img align="middle" src="/assets/2019_03_06_two_process_anim.gif" />
Mackay asks us to imagine these as a stack of pancakes. So each pancake is $P(\mathbf{x}\vert \lambda_0, \lambda_1, \mathbf{k})$ for a possible value of $\mathbf{k})$.
Now what we really want is $P(x \vert \lambda_1, \lambda_2)$ which is:
$$
\begin{aligned}
P(\mathbf{x}|\lambda_0, \lambda_1) &= \int P(\mathbf{x}|\lambda_0, \lambda_1, \mathbf{k})\,d\mathbf{k}\\
\hat{P}(\mathbf{x}|\lambda_0, \lambda_1) &= \frac{1}{2^8}\sum_k P(\mathbf{x}|\lambda_0, \lambda_1, \mathbf{k})
\end{aligned}
$$
So all you need to do is take an average of all the pancakes.
This is also the posterior distribution if you:
- Assume every $k$ has equal probability i.e. probability of each point belonging to a process is $\frac{1}{2}$ and each $k$ vector has probability $\frac{1}{2^8}$. Not that outrageous an assumption.
- Normalize
And you get this:
<div style="text-align: center">
<img src="/assets/2019_03_06_two_process.png" align="middle" alt="one process" width="600"/>
</div>
<br>
We get two distinct peaks, so there are indeed two distinct exponential processes. And if you wanted to know the best process assignment vector, $\mathbf{k}^* $, you could just look at the maximum likelihood for each $\mathbf{k}$ and normalize.
<div style="text-align: center">
<img src="/assets/2019_03_06_two_process_k.png" align="middle" alt="one process" width="700"/>
</div>
<br>
Wunderbar! So the best k is 114 or $[0, 1, 1, 1, 0, 0, 1, 0]$ and its twin 141 or $[1, 0, 0, 0, 1, 1, 0, 1]$ depending if $\lambda_0$ > $\lambda_1$ or $\lambda_1$ > $\lambda_0$. Label-switching is pretty annoying when working with mixture models. We won't worry about it here and just pick one.
### The evidence
The same formula for evidence applies here. We have some the extra $\mathbf{k}$ paramters but that's no worry for us since we are assuming flat priors on it as well. So we'll just take the mean over all the parameters and Bob's your uncle
```
evidence2 = all_Z.mean()
evidence2
```
## Comparing Models
In previous posts we have used WAIC to compare models. We'll do something simpler (and terrible depending on who you ask) - we'll just calculate the Bayes Factor. The ratio of the evidences is just
```
evidence2 / evidence1
```
which is around 13 for our data. Since it's substantially greater than 1, we conclude that model 2, with two processes, fits the data better.
There's another way to look at this. Let $H_1$ be the hypothesis that there is just one process and $H_2$ be the hypothesis that there are two processes. A priori we think both of these hypothesis are equally likely:
$$
p(H_1) = p(H_2) = 0.5
$$
So posterior for $p(H_1 \vert x)$ is just:
$$
p(H_1 \vert x) = \frac{p (x | H_1) \cdot p (H_1)}{p (x | H_1) \cdot p (H_1) + p (x | H_2) \cdot p (H_2)}
$$
This just boils down to:
```
PosteriorProbOfH2 = evidence2 / (evidence1 + evidence2)
PosteriorProbOfH1 = evidence1 / (evidence1 + evidence2)
```
which gives:
$$
\begin{align}
p(H_2 \vert x) = 0.93 \\
p(H_1 \vert x) = 0.07
\end{align}
$$
## Conclusion
So looks like $H_2$, that there are two processes is better supported by the data. Feel free to check out the notebook for all the code and to see what the MAP values for the $\lambda$ work out to be.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-07-17-implementing-advi.md
---
layout: "post"
title: "Implementing ADVI with autograd"
date: "2019-07-17 22:17"
comments: true
use_math: true
---
We use things without knowing how they work. Last time my fridge stopped working, I turned it off and on again to see if that fixed it. When it didn't I promptly called the "fridge guy". If you don't know how things work, you don't know when and how they break, and you definitely don't know how to fix it.
I've been interviewing a ton of people. It's hard to find the "ML guy" who can fix a broken model but there is no dearth of people who know how to train some ML model.
Rant over. On with the show.
## Implementing ADVI
Avid readers may remember that I'm working my way through Mackay's lectures and book. He has a lecture or two on variational inference, where he approximates posterior states of the Ising model. He handcrafts $q(\theta)$ for the model and finds the parameters that minimize KL-divergence from $p(\theta \vert x)$.
With Automatic Differentiation Variational Inference (ADVI), you don't need to worry about all that work. You have probably read the paper - it's 3 years old now which is ancient history in the CS world - but [here it is again](https://arxiv.org/pdf/1603.00788.pdf) for reference.
## The algorithm
We're going to fit a simple linear regression model.
$$
Y \sim N(X'\beta, 2.5)
$$
We're going to choose $\beta$ to be [5, -3.5]. We'll generate $y$ and see if we can recover these betas.
The algorithm itself is brilliant in its simplicity.
### 1. Transform latent variables ###
If support is constrained (e.g. is just positive) then we transform it to have a support over all real-values. Why do we need this? Remember that we are trying to minimize KL-divergence:
$$
\phi^* = \text{arg min}\\
\DeclareMathOperator*{\argmax}{argmax}
\argmax_{\phi \in \Phi} \text{KL}(q(\theta; \phi) \Vert p(\theta | x))
$$
and KL divergence is:
$$
KL(q\Vert p) = \int _ {-\infty }^{\infty} q(x) \log \frac{q(x)}{p(x)}\,dx
$$
Now if you choose an $x$ such that $p(x)$ is zero, we're going to have a division by zero and a blackhole will appear under your chair. So we need the following condition to be true:
$$
\text{supp}(q(\theta;\phi)) \subseteq \text{supp}(p(\theta\vert x))
$$
In order to do our inference automatically, we need to transform $p(\theta \vert x)$ to have a support over all reals. Then we can just choose a $q(\theta)$ that has a support over all reals as well... like your friendly neighbourhood gaussian.
One transformation might be $\zeta = \log(\theta)$. Note that this takes a $\theta$ with a support of positive reals and transforms it to $\zeta$, which has a support over all reals.
### 2. Calculate gradients
Another transformation allows you to convert the gradient of the objective function as an expectation over the gradients of the joint density: $\nabla_{\theta}\log p(x, \theta)$. Check out the paper. Basically it's an affine transformation (you're normalizing) so you don't need to stress about Jacobians.
The key takeaway is that if you can calculate the jacobians of the transformation we did in (1) and the gradient of $p(x, \theta)$ then we can calculate the gradient of the ELBO. Enter `autograd`.
#### Autograd
Part of my motivation for this implementation was to play with the `autograd` package. It's so beautifully easy. If you can numpy and scipy, you can autograd... mostly. You can check out the [github readme](https://github.com/HIPS/autograd) on what is implemented.
So you write your functions like you would in numpy/scipy and use the `grad`, `jacobian` and other functions to get the gradient function. Here's an example:
{% highlight python %}
from autograd import numpy as npa
grad_cos = grad(npa.cos)
grad_cos(np.pi / 2)
## -1.0
{% endhighlight %}
In our case, we just need to write out:
$$p(x, \theta) = p(x | \theta)p(\theta)$$
The first bit on the RHS is your likelihood and the second bit is the prior. Both super easy to code up. If you have multiple thetas, you can either assume they are independent (mean-field) or also fit their covariance (full-rank). For our linear model with mean-field it is simply:
{% highlight python %}
# Prior
def log_p_theta(self, betas, sigma):
beta_prior = spa.stats.norm.logpdf(betas, self.betas_mu, self.betas_sd).sum()
sigma_prior = spa.stats.gamma.logpdf(sigma/self.sigma_scale,
self.sigma_shape) - npa.log(self.sigma_scale)
return beta_prior + sigma_prior
# Likelihood
def log_p_x_theta(self, theta):
# likelihood
betas = theta[:2]
sigma = theta[2]
ones = np.ones((self.x.shape[0],1))
x = np.hstack([ones, self.x])
yhat = (x @ betas)
like = spa.stats.norm.logpdf(self.y, yhat, sigma).sum()
return like + log_p_theta(betas, sigma)
{% endhighlight %}
and the gradients can be gotten easily. Here we code up equations (8) and (10) from the paper.
{% highlight python %}
def nabla_mu(self, eta):
x = self.x
y = self.y
zeta = (eta * self.omega) + self.mu
theta = self.inv_T(zeta)
grad_joint = elementwise_grad(self.log_p_x_theta)(theta)
grad_transform = elementwise_grad(self.inv_T)(zeta)
grad_log_det = elementwise_grad(self.log_det_jac)(zeta)
return grad_joint * grad_transform + grad_log_det
def nabla_omega(self, nabla_mu_val, eta):
return nabla_mu_val * eta.T * npa.exp(self.omega) + 1
def log_det_jac(self, zeta):
a = jacobian(inv_T)(zeta)
b = npa.linalg.det(a)
return npa.log(b)
{% endhighlight %}
### 3. Stochastic optimization ###
We take a draw from a standard gaussian, do all the inverse-transform, calculate gradients and then just do gradient ascent. You can even mini-batch this to make it even faster but we don't do it here.
The authors also provide their own algorithm to adaptively set the step-size that combines RMSPROP with a long memory. Here it is in python:
{% highlight python %}
def get_learing_rate(base_lr, iter_id, s, gk, tau = 1, alpha=0.9):
s = alpha * gk**2 + (1 - alpha) * s
rho = base_lr * (iter_id ** (-1/2 + 1e-16)) / (tau + s**(1/2))
return rho, s
{% endhighlight %}
Where `s` is initialized as `s = gk**2`.
## Show me the results
Here's an animation of the optimization process. Enjoy!
{% include youtube.html id="DyRjj3ufuAw" %}
## Code and last words
You can get [the code here](https://github.com/sidravi1/Blog/tree/master/src/advi). If you really want the animation code, then ping me and I'll clean up the notebook and throw it up somewhere.
Full-rank doesn't look too hard to do. That would be a nice extension if you want to do it. I did play around with other transformations, especially the $\log(\exp(\theta) - 1)$ and at least for this example, I didn't find much of a difference. If you do that, don't forget to use `logaddexp` when writing the inverse transform - else you will get underflow/overflow.
Choosing the base learning rate took a little tuning. Also, my biggest time sink was not realizing that you shouldn't transform (well you can't take the log of a negative!) the latent params that already have a support over all reals. Oof.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2021-10-11-cox-proportional-hazard-model.md
---
layout: "post"
title: "[Survival models] Cox proportional hazard model"
date: "2021-10-11 10:42"
comments: true
use_math: true
---
In the [previous blogpost]({{ site.baseurl }}{% post_url 2021-10-01-censored-data-and-intro-to-survival-models %}), we talked about the *hazard* function - the probability that the event happens at time $t$ given that you it hasn't till time $t$. In the Cox proportional hazard model, we assume the hazard function is:
$$
h(t) = h_0(t) \times exp(b_1x_1 + b_2x_2 + ... + b_px_p)
$$
Some interesting things to point out here:
* time $t$ only occurs in $h_0(t)$
* covariates, $x_i$ only occur in the $exp$ bit
So there is some base hazard rate $h_0(t)$ and the only way it varies for units with different characteristics is through the $exp$ bit. So why is it called "proportional" hazard model?
Imagine a simple model where:
$$
h(t) = h_0(t) \times exp(b_1x_1)
$$
And we have a unit $i$ with $x_{i1} = z$ and another unit $j$ with $x_{ji} = a \cdot z$ so let's see the hazard for each:
$$
h_i(t) = h_0(t) \times exp(b_1z)
$$
And
$$
h_j(t) = h_0(t) \times exp(b_1 az)
$$
So the hazard ratio of the two is:
$$
\begin{aligned}
\frac{h_i(t)}{h_j(t)} &= \frac{h_0(t) exp(b_1 az)}{h_0(t) exp(b_1 z)} \\
&= \frac{exp(b_1 az)}{exp(b_1 z)} \\
&= exp(b_1 (a - 1)z)
\end{aligned}
$$
So no matter what the $t$ is, the hazard ration between these two is always some constant. Another way is to note that:
$$
\begin{aligned}
h_i(t) &= h_j(t) \times exp(b_1 (a -1 )z)\\
h_i(t) &= c h_j(t)
\end{aligned}
$$
where $c = exp(b_1 (a -1 )z)$. So $h_i(t)$ is proportional to $h_j(t)$ - times does not make an appearance in the coefficient. This assumption may not be true and there are a bunch of tests you can do to check it.
Alright. Enough with the theory.
## Partial likelihood
I'm not going to derive it. The internet is your friend.
$$
PL(\beta | D) = \prod_{j=1}^{d} \frac{\exp(x_j'\beta)}{\sum_{l \in R_j} \exp(x'_l\beta)}
$$
where $R_j$ is the _risk set_ - people at risk of death/event when the event for $j$ occurs. This should look familiar - it's softmax. The intuition follows from there. So we want to pick the betas that maximise the likelihood of the event happening out of all the units at risk.
Log-likelihood just needs some $algebra$:
$$
pll(\beta | D) = \sum_{j=1}^{d} \left( x_j'\beta - \log\left(\sum_{l \in R_j} \exp(x'_l\beta)\right)\right)
$$
Now all we need to code it up with `jax` for some sweet sweet autograd.
## Minimize negative log likelihood
{% highlight python %}
import jax.scipy as jsp
import jax
@jax.jit
def neglogp(betas, riskset=riskset, observed=observed):
betas_x = betas @ x.T
riskset_beta = betas_x * riskset
ll_matrix = (betas_x - jsp.special.logsumexp(riskset_beta, b=riskset, axis=1))
return -(observed * ll_matrix).sum()
{% endhighlight %}
If you know `numpy` and `scipy`, you know a lot of `jax`.
P.S: Took me forever to realise that `logsumexp` take a weight argument as `b`. No idea why `statsmodels` doesn't use this.
Ok. Now all we need is to minimize it. Here comes the magic of autograd
{% highlight python %}
from jax import grad, hessian
from scipy.optimize import minimize
dlike = grad(neglogp)
dlike2 = hessian(neglogp)
res = minimize(neglogp, np.ones(2), method='Newton-CG', jac=dlike, hess=dlike2)
res.x
>>> DeviceArray([-0.14952305, -0.16527627], dtype=float32)
{% endhighlight %}
You can compare this to `statsmodels` or `lifelines` package. It's in the notebook - you can check it out.
## Let's get Bayesian
Blackjax is a pretty sweet package with a lot of sampling methods. Let's use the NUTS sampler (yes - i know, that's calling it a "sampler sampler"). Let's use it to get some samples. This is basically the example in the blackjax documentation.
First we need the posterior probability which is simply the prior $\times$ the likelihood. In log terms:
{% highlight python %}
def logprior(betas):
return jsp.stats.norm.logpdf(betas, 0, 1.0).sum()
logprob = lambda x: logprior(**x) + neglogp3(**x)
{% endhighlight %}
Ok. Let's setup the initial values and the kernel.
{% highlight python %}
initial_position = {"betas": jnp.ones(2)}
initial_state = nuts.new_state(initial_position, logprob)
inv_mass_matrix = np.array([0.5, 0.5])
step_size = 1e-3
nuts_kernel = jax.jit(nuts.kernel(logprob, step_size, inv_mass_matrix))
{% endhighlight %}
and the inference loop for samples:
{% highlight python %}
def inference_loop(rng_key, kernel, initial_state, num_samples):
def one_step(state, rng_key):
state, _ = kernel(rng_key, state)
return state, state
keys = jax.random.split(rng_key, num_samples)
_, states = jax.lax.scan(one_step, initial_state, keys)
return states
rng_key = jax.random.PRNGKey(0)
states = inference_loop(rng_key, nuts_kernel, initial_state, 1000)
beta_samples = states.position["betas"].block_until_ready()
{% endhighlight %}
Now let's get some samples:
{% highlight python %}
rng_key = jax.random.PRNGKey(0)
states = inference_loop(rng_key, nuts_kernel, initial_state, 1000)
beta_samples = states.position["betas"].block_until_ready()
{% endhighlight %}
Here's the trace from it:

And the posterior:

And there you have it folks - some nice confidence intervals.
## Final words
Ok - I cheated a little bit. I removed ties in the database. If you have ties you need a slight change to the likelihood - check out the [statsmodels](https://github.com/statsmodels/statsmodels/blob/main/statsmodels/duration/hazard_regression.py) code for `efron_loglike` or `breslow_loglike`.
The point of this was also to play around with `jax` and `blackjax`. Mission accomplished. Let's look at some parametric models next time around.
<file_sep>/_posts/2018-03-03-why-mcmc-and-a-quick-markov-chains-intro.md
---
layout: "post"
title: "Why MCMC and a quick markov chains intro"
date: "2018-03-03 22:10"
use_math: True
comments: true
---
A lot of this material is from <NAME>'s All of Statistics. I love how the title makes such a bold claim and then quickly hedges by adding the subtitle "A *Concise* Course in Statistical Inference" (The italic are mine).
Before systematically trying to understand MCMC, I floundered a bit. [This post](https://jeremykun.com/2015/04/06/markov-chain-monte-carlo-without-all-the-bullshit/) by <NAME> is probably one of the best explanations but that too required some side reading and close following with a scratch pad. I'm going to try to explain it simply (glossing over some details and proofs) and slowly, but if it's too basic, you might want to head over to Jeremy's site (you should be reading his blog anyway). This post start off with Markov Chain - "All of Markov Chains: A Concise Intro to Markov Chains" and then we'll continue onto Metropolis, Metropolis-Hastings, and all the other good stuff.
## Storytime
This "story" about Good King Markov is from section 8.1 of "Statistical Rethinking" by <NAME>. King Markov's kingdom has 10 islands {i<sub>1</sub>... i<sub>10</sub>}, each island is neighboured by 2 others so they all form a ring. They are all of different sizes and so have different populations. Population of island i<sub>1</sub> is P<sub>1</sub>. Population of island i<sub>2</sub> is P<sub>2</sub> = 2P<sub>1</sub>, and Population of island i<sub>3</sub> is P<sub>3</sub> = 3P<sub>1</sub> and so forth.
The king wants to spend time on the islands in proportion to their population size. King Markov, like your humble writer, doesn't like planning out his schedule in advance. And, because he's lazy, like your humble writer, wants to only travel to neighbouring islands. How should he do it?
Here's how he does it:
1. Start of each week, he flips a coin. If it's heads he considers moving clockwise, if it's tails he considers moving anti-clockwise.
2. To decide whether he actually moves, he gets # of shells equivalent to the island number that has been proposed by the coin. So if it is i<sub>6</sub>, gets 6 shells out. Then gets out the number of stones equivalent to the island number he is on. So if he is on i<sub>7</sub>, he gets out 7 stones and 5 if he is on i<sub>5</sub>.
3. If there are more shells than stones, move to the island.
4. If there are fewer shells than stones, discard the number of stones equal to the number of shells. So in our example, he has 7 stones so he discards 6 of them. He puts the 1 stone remaining and the 6 shells back into a bag and gives it a vigourous shake.
5. He reaches in and pull out one object. If it is a shell, he moves, else he stays for another week. So probability of staying in 1/7 and moving is 6/7.
This works! The king's movement looks erratic but in the long run, it satisfies his requirement and allows him to remain a monarch in an increasingly democratizing world.
This is a special case of the Metropolis algorithm (which is one example of MCMC algorithm). Let that stew for a bit or even better try and simulate this in python or R to convince yourself that this works.
## Why MCMC?
From <NAME>'s post that I mentioned earlier but the word in bold is mine:
> Markov Chain Monte Carlo is a technique to solve the problem of **efficiently** sampling from a complicated distribution.
He does a great job of motivating it so read that if you have more "why"s. In brief, you have some distribution *f(X)*, and you want to draw i.i.d samples such that their distribution is *f(X)*. There are less efficient ways of doing it (see rejection sampling) but if you're talking about high dimensional space, you'll need this.
## Markov chains
A Markov chain is a stochastic (read:random) process where the distribution of X<sub>t</sub> depends only on X<sub>t-1</sub>, where (X<sub>1</sub>, ... , X<sub>t</sub>) are random variables. So it has memory of just 1 time period.
It's given by a transition matrix, *P*, with element *p<sub>ij</sub>* that are the probability of going from state i to j. One more notation: p<sub>ij(n)</sub> is the probability of going from i to j in n steps.
### Some interesting things about Markov chains
For all of these, I talk about the properties of the state. But if all states have a property then the chain itself can be said to have this properties.
I'm skipping the proofs but they are pretty straight forward:
- $p_{ij}(m + n) = \sum_k p_{ik}(m)p_{kj}(n)$ : To get the probability of getting from i to j in (m+n) steps we are summing over all the possible paths where we get to some intermediate stage, k, in m steps and then from there to j in n steps.
- P<sub>n</sub> = P<sup>n</sup>: To calculate the probabilities of state transition in n-steps is just P<sub>n</sup>.
### Some properties of Markov chains
For all of these, I talk about the properties of the state. But if all states have a property then the chain itself can be said to have this properties.
- **Communicable**: If you can get from i to j in some n with a non-zero probability then i and j are communicable. If all states can communicate with each other, it is irreducible.
- **Recurrent**: Say you are in state i. State i is recurrent if you will return to i if you keep applying the transition matrix. Else it is transient. Cool fact: A finite Markov chain must have at least one recurrent state. Also, if it is irreducible, then all states are recurrent.
- **Aperiodic**: State i is aperiodic if it isn't a cycle. That is when you will be in in a state i should be not be determined solely by n.
Non-null: If mean time taken to get back to state i is less than $\infty $ it is non-null.
- **Ergodic**: If a state is recurrent, non-null, aperiodic, it is ergodic.
- **Stationarity**: If say $\pi$ is a stationary distribution if $\pi = \pi \cdot P$
- **Limiting Distribution**: $\pi_j = \lim_{n \to \infty} P^n_{ij}$ independant of i. So no matter which state we start in, if we run it for long enough, the probability of being in state j is $\pi_j$
- **Detailed balance**: $\pi_{i} p_{ij} = p_{ij} \pi_{j}$ for all i,j. This takes a minute to get your head around. It saying something very strong: if there is a distribution where, for all the states, the amount going in from another state is equal to the amount going back to that state, then that distribution is a stationary distribution.
Ok. Next time, we'll get back to going from simulated annealing to MCMC.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-06-21-hmc-and-slice-sampler.md
---
layout: "post"
title: "Back to Basics with David Mackay #4: HMC and Slice sampler - now with animations!"
date: "2019-06-21 20:34"
comments: true
use_math: true
---
I just wanted to put up a few animations of HMC and slice samplers that I have been playing around with.
I started coding up the slice sampler and the Hamiltonian Monte-Carlo (HMC) after reading the chapter in MacKay's book. Around the same time, Colin Carol published is `minimc` package for HMC. This package so nicely written so I just decided to play around with it instead. I'll do another post with some HMC experiments.
The code for the HMC animation (uses minimc) can be [found here](https://gist.github.com/sidravi1/a7965d57c63e71f9b9ff47098cd774df). The code for slice sampler and the file to run the animation can be [found here](https://github.com/sidravi1/slicesampler).
## Hamlitonian Monte Carlo
I would recommend heading over to Colin's blog and reading the introduction to HMC he has posted up there and then come back and watch these videos. Note the Metropolis proposals where the sampler jumps in momentum space to a new energy level. Then it takes a bunch of leapfrog steps and then takes a sample.
{% include youtube.html id="po0Obe04Nfs" %}
## 1-d slice sampler
I basically implemented Mackay's algorithm from his book (Ch 29, page 375):
**Main algorithm**

**Stepping out**

**Shrinking**

And here's the video:
{% include youtube.html id="NsYqQt0Yfs8" %}
## multi-dimensional sampler
Toward the end of his lecture on slice sampling, MacKay answers a student question about how you'd do a multi-dimensional slice sampling. That makes a hell of lot more sense to me that his one paragraph in the book. Basically, each time we pick a random direction for the vector we step out in. Rest is pretty much the same.
{% include youtube.html id="Ti3DRyUDWZU" %}
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/resume.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="<NAME>" />
<meta name="date" content="2021-05-28" />
<title><NAME>’s resume</title>
<script src="resume_sid_files/header-attrs-2.5/header-attrs.js"></script>
<link href="resume_sid_files/font-awesome-5.1.0/css/all.css" rel="stylesheet" />
<link href="resume_sid_files/font-awesome-5.1.0/css/v4-shims.css" rel="stylesheet" />
<link href="resume_sid_files/paged-0.13/css/resume.css" rel="stylesheet" />
<script src="resume_sid_files/paged-0.13/js/config.js"></script>
<script src="resume_sid_files/paged-0.13/js/paged.js"></script>
<script src="resume_sid_files/paged-0.13/js/hooks.js"></script>
<script src="resume_sid_files/accessible-code-block-0.0.1/empty-anchor.js"></script>
</head>
<body>
<div id="aside" class="section level1">
<h1>Aside</h1>
<div id="contact" class="section level2">
<h2>Contact Info</h2>
<ul>
<li><i class="fa fa-envelope"></i> <a href="mailto:<EMAIL>" class="email"><EMAIL></a></li>
<li><i class="fa fa-github"></i> <a href="https://github.com/sidravi1">github.com/sidravi1</a></li>
<li><i class="fa fa-phone"></i> +1 415 666 6109</li>
<li><i class="fa fa-globe"></i> <a href="sidravi1.github.io">sidravi1.github.io</a></li>
</ul>
</div>
<div id="skills" class="section level2">
<h2>Skills</h2>
<ul>
<li><p>Bayesian Inference, Optimization, Causal Inference, Statistical Modelling, Machine Learning, Econometrics.</p></li>
<li><p>NLP, Time-series, Market Segmentation, Process Optimization, Choice Models, Survival Models.</p></li>
<li><p>Tools: Python (incl. pymc3, pytorch, pyspark, flask), R, Stata, AWS, Docker</p></li>
</ul>
</div>
<div id="disclaimer" class="section level2">
<h2>Disclaimer</h2>
<p>Last updated on 2021-05-28.</p>
</div>
</div>
<div id="main" class="section level1">
<h1>Main</h1>
<div id="title" class="section level2">
<h2><NAME></h2>
<div id="data-scientist" class="section level3">
<h3>Data Scientist</h3>
<p>Background in Computer Science, Development Economics, and Econometrics. Loves building bespoke machine learning models to inform business actions. Enjoys learning, experimentation, and building things.</p>
</div>
</div>
<div id="education" class="section level2" data-icon="graduation-cap" data-concise="true">
<h2>Education</h2>
<div id="harvard-university" class="section level3">
<h3>Harvard University</h3>
<p>MPA/ID, Kennedy School of Government</p>
<p>Cambridge, USA</p>
<p>2016</p>
<p>Areas of study: econometrics, macroeconomics, microeconomics, data science, statistics, machine learning</p>
<p>Thesis: <a href="https://www.hks.harvard.edu/sites/default/files/degree%20programs/MPAID/files/Redesigning%20India's%20Urea%20Policy_SYPA_Sid%20Ravinutala_2016.pdf">Redesigning India’s Urea Policy</a> (awarded best policy paper)</p>
</div>
<div id="university-of-melbourne" class="section level3">
<h3>University of Melbourne</h3>
<p>B.Eng (Electrical) & B.Sci (Computer)</p>
<p>Melbourne, Australia</p>
<p>2004</p>
<p>Thesis: <a href="https://link.springer.com/chapter/10.1007/978-3-540-24775-3_33">Adaptive Clustering for Network Intrusion Detection</a></p>
</div>
</div>
<div id="professional-experience" class="section level2" data-icon="suitcase">
<h2>Professional Experience</h2>
<div id="data-science-director" class="section level3">
<h3>Data Science Director</h3>
<p>IDInsight</p>
<p>Cambridge, USA</p>
<p>current - April 2020</p>
<ul>
<li>Establishing and growing the data science function within the organisation.</li>
<li>Helping clients discover how data science can address their business challenges.</li>
<li>Tech lead / lead data scientist on multiple projects.</li>
<li><strong>Example Projects</strong>:
<ul>
<li>Predictive model to locate out of school girls in India</li>
<li>FAQ Whatsapp bot for vaccine hesitancy for Govt of South Africa.</li>
<li>Service for matching beneficiaries with eligible government benefits in India.</li>
<li>Optimising school infrastructure investment for the government of Morocco.</li>
</ul></li>
</ul>
</div>
<div id="senior-data-scientist" class="section level3">
<h3>Senior Data Scientist</h3>
<p>Coles Pty Ltd</p>
<p>Melbourne, Australia</p>
<p>2020 - 2019</p>
<ul>
<li>Built forecasting engine for supermarket items at the store level.</li>
<li>Designed and led the build of a forecasting engine for new items.</li>
<li>Contributed to an internal package for discrete choice models.</li>
<li>Led knowledge sharing on choice models and causal inference.</li>
</ul>
</div>
<div id="senior-data-scientist-1" class="section level3">
<h3>Senior Data Scientist</h3>
<p>QuantumBlack, McKinsey</p>
<p>Cambridge, USA</p>
<p>2019 - 2018</p>
<ul>
<li><strong>Pharma</strong> - Mined electronic medical records to understand causes of patient switching behavior.</li>
<li><strong>Disaster recovery</strong> - Developed Monte Carlo models to quantify uncertainty in key milestones to inform mitigation strategies.</li>
<li><strong>Chemicals manufacturing</strong> - Identified root cause of variability in production yields. Optimized manufacturing process using genetic algorithms.</li>
<li><strong>Internal R&D</strong> - Contributed to an internal package for causal inference using Bayesian Networks.</li>
</ul>
</div>
<div id="graduate-research-fellow" class="section level3">
<h3>Graduate Research Fellow</h3>
<p>Centre for International Development</p>
<p>Cambridge, USA</p>
<p>2018 - 2016</p>
<ul>
<li>Developed statistical models to identify export sector growth opportunities at sub-national level in Colombia.</li>
<li>Built collaborative filtering models to predict rural agricultural diversification and recommended possible areas for investment in Colombia.</li>
<li>Used Collaborative Filtering and network analysis to understand patterns in global tourism using credit card transactions data.
<br>
<br></li>
</ul>
</div>
<div id="team-membereconomist" class="section level3">
<h3>Team Member/Economist</h3>
<p>CEA’s Office, Ministry of Finance</p>
<p>New Delhi, India</p>
<p>2016 - 2015</p>
<ul>
<li>2016 Economic Survey – Conducted analysis and wrote the chapter on fertilizer subsidy in the 2016 Indian Economic Survey.</li>
<li>Policy reform for fertilizer – Demonstrated how current policy leads to shortages and black markets. Worked with Ministry of Fertilizer & Chemicals to design a new policy that was presented to the cabinet.</li>
</ul>
</div>
<div id="senior-associate" class="section level3">
<h3>Senior Associate</h3>
<p>Clinton Health Access Initiative</p>
<p>sub-Saharan Africa</p>
<p>2014 - 2012</p>
</div>
<div id="access-to-medicinesunitaid-analyst" class="section level3">
<h3>Access to Medicines/UNITAID Analyst</h3>
<p>Clinton Health Access Initiative</p>
<p>Kampala, Uganda</p>
<p>2012 - 2011</p>
</div>
<div id="manager-technology-consulting" class="section level3">
<h3>Manager, Technology Consulting</h3>
<p>Accenture Pty. Ltd</p>
<p>Melbourne, Australia</p>
<p>2011 - 2005</p>
</div>
</div>
<div id="publications-and-presentations" class="section level2" data-icon="file">
<h2>Publications and Presentations</h2>
<div id="using-machine-learning-to-improve-education-intervention-targeting" class="section level3">
<h3>Using machine learning to improve education intervention targeting</h3>
<p>CIES 2021 Conference Session</p>
<p>N/A</p>
<p>2021</p>
</div>
<div id="redesigning-indias-urea-policy-harvard-kennedy-school" class="section level3">
<h3>Redesigning India’s Urea Policy, Harvard Kennedy School,</h3>
<p>MPA/ID Final Capstone Paper</p>
<p>N/A</p>
<p>2016</p>
</div>
<div id="economic-survey-of-india" class="section level3">
<h3>Economic Survey of India</h3>
<p>Ministry of Finance, Government of India</p>
<p>N/A</p>
<p>2016</p>
</div>
<div id="adaptive-clustering-for-network-intrusion-detection" class="section level3">
<h3>Adaptive Clustering for Network Intrusion Detection</h3>
<p>PAKDD 2004: 255-259</p>
<p>N/A</p>
<p>2004</p>
</div>
</div>
</div>
<script>
(function() {
var i, s, j, el, els;
var create_el = function(type, className, content, isHTML) {
var el = document.createElement(type);
if (className) el.className = className;
if (content) {
if (isHTML) {el.innerHTML = content;} else {el.innerText = content;}
}
return el;
}
// replace h2 title with h1
var title = document.getElementById('title').querySelector('h2');
title.parentNode.replaceChild(create_el('h1', false, title.innerHTML, true), title);
// add the class .aside to #aside
el = document.getElementById('aside');
if (el) el.className += ' aside';
// tweak class names of sections, and add icons
els = document.getElementById('main').querySelectorAll('.level2');
for (i = 0; i < els.length; i++) {
el = els[i];
if (i === 0 && el.id === 'title') continue;
el.className += ' main-block';
if (el.dataset['concise']) el.className += ' concise';
// if there is no icon, add an icon:
if (el.firstElementChild.firstChild && el.firstElementChild.firstChild.nodeName !== 'I') {
s = el.dataset['icon'] || 'bookmark';
el.firstElementChild.insertBefore(create_el('i', 'fa fa-' + s), el.firstElementChild.firstChild);
}
}
// tweak class names of blocks in sections
els = document.getElementById('main').querySelectorAll('.level3');
for (i = 0; i < els.length; i++) {
el = els[i];
if (el.parentNode.id === 'title') continue;
el.className += ' blocks';
el.innerHTML = '<div class="date"></div>' + '<div class="decorator"></div>' +
'<div class="details"><header></header><div></div></div>' + el.innerHTML;
var ps = el.querySelectorAll('p');
// move the date paragraph to the date div
if (ps.length >= 3) {
s = ps[2].innerText;
s = s === 'N/A' ? [] : s.split(' - ');
el.removeChild(ps[2]);
for (j = 0; j < s.length && j < 2; j++) {
el.children[0].appendChild(create_el('span', false, s[j]))
}
}
// move title, description, location to the details div
(function(h) {
h.appendChild(el.children[3]);
var p = el.children[3]; // description
if (p.innerText !== 'N/A') {
h.appendChild(create_el('span', 'place', p.innerHTML, true));
}
el.removeChild(p);
p = el.children[3]; // location
if (p.innerText !== 'N/A') {
s = create_el('span', 'location', p.innerHTML, true);
s.innerHTML = '<i class="fa fa-map-marker-alt"></i> ' + s.innerHTML;
h.appendChild(s);
}
el.removeChild(p);
})(el.children[2].firstElementChild);
// move the rest of content in a block into the last div of the details div
s = el.children[2];
while (j = s.nextSibling) {
if (j.className === 'aside') { s = j; continue; }
el.children[2].lastElementChild.append(j);
}
}
})();
</script>
</body>
</html>
<file_sep>/_posts/2018-11-14-another-flavour-of-the-waiting-time-or-inspection-paradox.md
---
layout: "post"
title: "Another flavour of the waiting time (or inspection) paradox"
date: "2018-11-14 14:53"
comments: true
use_math: true
---
[David McKay's Information Theory, Inference, and Learning Algorithms](http://www.inference.org.uk/itila/), in addition to being very well written and insightful, has exercises that read like a book of puzzles. Here's one I came across in chapter 2:
> <b>Excercise 2.35</b> Fred rolls an unbiased six-sides die once per second, noting the occasions when the outcome is a six.<BR>
> (a) What is the mean number of rolls from one six to the next six?<BR>
> (b) Between two rolls, the clock strikes one. What is the mean number of rolls until the next six?<BR>
> (c) Now think back before the clock struck. What is the mean number of rolls, going back in time, until the most recent six?<BR>
> (d) What is the mean number of rolls from the six before the clock struck to the next six?<BR>
> (e) Is your answer to (d) different from the your answer to (a)? Explain.<BR>
- **(a)** is easy enough. Anyone who has played any game requiring dice will tell you it's 6.
- **(b)** may seem a little puzzling to some. When people ask "what's the clock striking one got to do with it?", I put on a devilish grin and saying "Nothing!". But if you are familiar with Poisson processes, you have heard this sort of stuff many times. You note that throws are memoryless i.e. Probability of a 6 in throw $T$. $P(T)$ does not depend on any throws $t$ where $t < T$. And you say, *"These throws are memoryless so it is still 6"*. And you'd be right (even my mum, who is not a student of probability, got it right).
- For **(c)** you are thinking *"Ok so it's memoryless. Does directionality of time matter? It really shouldn't right?"* and you again correctly guess 6.
- **(d)** leads you down a trap; you add the two together and minus one (so you aren't counting the 1/2 second) and say 11.
- **(e)** Closes the trap on you. Just because an unrelated event like a clock striking one happened, why should the expected number of rolls be almost double?
McKay doesn't directly provide a solution but instead cheekily just presents you with an analogous problem and tells you to go figure that one out.
> Imagine that the buses in Poissonville arrive independently at random (a Poisson process) with, on average, one bus every six minutes. Imagine that passengers turn up at bus-stops at a uniform rate, and are scooped up by the bus without delay, so the interval between two buses remains constant. Buses that follow gaps bigger than six minutes become overcrowded. The passengers' representative complains that two-thirds of all passengers found themselves on overcrowded buses. The bus operator claim, "no, no - only one third of our buses are overcrowded." Can both these claims be true?
# The inspection paradox
The solution is that when you ask passengers, you oversample the ones on crowded buses. More people are waiting for delayed buses therefore more people get on the delayed buses and therefore delayed buses are overcrowded. There was a great post by [<NAME> on the inspection problem](http://allendowney.blogspot.com/2015/08/the-inspection-paradox-is-everywhere.html). He looks at a number of examples of the inspection paradox including something similar to the *Poissonville buses* problem that McKay poses.
<NAME> also had [a great post recently](https://jakevdp.github.io/blog/2018/09/13/waiting-time-paradox/) looking at the bus example in real life. He summarizes the inspection paradox quite nicely:
```
Briefly, the inspection paradox arises whenever the probability
of observing a quantity is related to the quantity being observed
```
But how does that relate to our problem? The bus example makes sense but who are we oversampling here? What's the unrelated clock event got to do with the die throw? It wasn't clear to me that this was even true. So I took Sir <NAME>'s advice.
# "Whenever you can, count."
Simulation can lead to a lot of insight. You are forced to make a lot of your assumptions explicit and that reveals the mechanisms that may not have been immediately obvious.
Let's setup some dummy data. Here is a function for a roll of the die. It's just a wrapper around numpy's randint function.
{% highlight python %}
def do_roll():
return np.random.randint(1, 7)
{% endhighlight %}
Now lets run a 1000 simulations and in each let's keep rolling till we get 1000 sixes.
{% highlight python %}
def do_run(n_samps=1000):
n = 0
n_rolls = np.empty(n_samps)
t = 0
while n < n_samps:
roll = do_roll()
t += 1
if roll == 6:
n_rolls[n] = t
n += 1
return n_rolls
f = np.frompyfunc(do_run, 1, 1)
simulations = np.stack(f(np.repeat(1000, 1000)))
{% endhighlight %}
Let's make sure we didn't screw anything up. We expect to see a uniform distribution since that's what throwing an unbiased die is:
{% highlight python %}
plt.figure(figsize=(10, 7))
plt.hist(simulations.ravel(), bins=100, alpha = 0.5);
sns.despine(left=True)
plt.xlabel("Throw number")
plt.ylabel("Number of sixes")
{% endhighlight %}

Looks pretty good. The tail there is because we asked for 1000 sixes so some of the simulations took longer to get it. You could instead run the simulation for "t" seconds (or throws) and that would give you a nice looking boxy histogram.
Next, let's see what the number of throws between sixes, or the wait times since we are throwing once per second, look like:
{% highlight python %}
plt.figure(figsize=(10, 7))
wait_times = simulations[:, 1:] - simulations[:, :-1]
plt.hist(wait_times.ravel(), bins=20, alpha=0.5);
plt.annotate(text="Mean wait time: {:0.2f}".format(wait_times.mean()), xy=(0.11, 0.8),
xytext=(0.15, 0.92), fontsize=14, xycoords='axes fraction', arrowprops= {'arrowstyle':"->"})
plt.axvline(x=wait_times.mean(), color='firebrick', ls="--")
{% endhighlight %}

There's the solution for (a). If you wanted to figure out what that distribution is, that's easily enough. We know that probability that it take $r$ throws is the probability that we get something that is not a six for $r-1$ throws and then a six:
$$
\mathbb{P}(r) = \left(\frac{5}{6}\right)^{r-1}\frac{1}{6}
$$
The blue line in the figure above shows this function.
## Clock strikes one
As per the exercise, let's say that the clock strikes between two throws at some time $X$:
{% highlight python %}
X = np.random.randint(0, high=simulations.max()//1.1)
X = X - 0.5
{% endhighlight %}
Note that $X$ is not really a random number (it happens at 1PM!) but to convince myself that this phenomenon is real, I ran this a number of times with different $X$s.
Let's calculate the window around when the clock strikes:
{% highlight python %}
def get_time_window(sim, X):
before_strike = sim[sim < X]
after_strike = sim[sim > X]
if (len(after_strike) == 0) or (len(before_strike) == 0):
return np.nan
else:
return after_strike.min() - before_strike.max()
window_around_strike = np.apply_along_axis(lambda a: get_time_window(a, X),
1, simulations)
{% endhighlight %}

Wow. Ok - so it is indeed 11 seconds instead of the 6 seconds.
## So whats going on?
Here's the CDF of the two windows above and we see that the window around the clock strike is indeed longer.
{% highlight python %}
pdf_bias = np.histogram(window_around_strike, bins=40)[0]
cdf_bias = np.insert(np.cumsum(pdf_bias), 0, 0)
cdf_bias = cdf_bias / 1000
pdf = np.histogram(wait_times.ravel(), bins=40)[0]
cdf = np.insert(np.cumsum(pdf), 0 , 0)
cdf = cdf / cdf.max()
plt.figure(figsize=(10, 5))
plt.plot(cdf_bias, color='limegreen',
label='CDF (# throws between 6s \naround clock strike)')
plt.axvline(window_around_strike.mean(), color='limegreen', ls = "--")
plt.plot(cdf, color='dodgerblue', label='CDF (# throws between 6s)')
plt.axvline(wait_times.mean(), color='dodgerblue', ls = "--")
plt.legend(loc=4, frameon=True)
sns.despine(left=True)
plt.grid(True, axis='both')
{% endhighlight %}

Let's just look a small sample and see what's going on. The figure below shows 10 simulations and 40 seconds before and after the clock strike. Each bar is a six being rolled. The red dotted line is when the clock strikes. The green area is the window from the six before the clock strikes and the blue area is the window to the next six after the clock strikes. Remember that the clock strikes between throws so we don't need to worry about a six being thrown at the same time as when it strikes.

The mean window between sixes in just this sample shown is 5.9 and the mean of the window around the clock strike (green plus blue) is 11.9 rolls. We see that clock strikes seem to be in wide windows i.e. there is a large gap between sixes. So something similar to a the bus example is occuring.
The clock strike is more likely to occur between large gaps. It hurts my head to think about it this way since clock strike is predetermined (it strikes at 1). It's not a random variable. But the way to think about it is that **there are more events happening in large windows**. Not just the clock striking but the dog barking, phone ringing, baby crying. There are just more seconds in those longer gaps for things to happen. So when looking from the perspective of some event occurring, it appears that the window is wider than average.
The probability of number of throws experienced around the event is not only related to the $P(r)$ but also to $r$; the longer the window between throws, the larger the probability that some event will happen within it. Let's call the probability of the number of throws experienced around the event be $P'(r)$. The math is as follows (similar to the logic Jake VP has in his blog post):
$$
\begin{aligned}
\mathbb{P}'(r) &\propto r \mathbb{P}(r)\\
\mathbb{P}'(r) &= \frac{r \mathbb{P}(r)}{\int ^\infty_0 r \mathbb{P}(r) dr}
\end{aligned}
$$
The bottom is just $\mathbb{E}_{P}{[r]}$ and we know that to be six - the solution to part (a).
$$
\begin{aligned}
\mathbb{P}'(r) &= \frac{r \mathbb{P}(r)}{6}\\
\mathbb{P}'(r) &= r\left(\frac{5}{6}\right)^{r-1}\left(\frac{1}{6}\right)^2
\end{aligned}
$$
This is the blue line in the figure in the previous section and we see that it matches our data quite well.
## The bus analogy
If all this still makes you feel woozy (from the perspective of some unrelated event, the gaps between sixes is almost double) but the Poissonville bus analogy makes intuitive sense to you, hopefully drawing parallels between them will help:
Dice throwing
- The dice is thrown every second
- There are more seconds between longer spans without a 6
- and therefore more likely that the clock strikes (or some event happens) between one of the longer spans.
Poissonville buses:
- Passengers come every second (or uniformly)
- There are more passengers waiting during longer spans without a bus
- and therefore more likely that a passenger will be on a bus that was delayed
The [notebook can be found here](https://github.com/sidravi1/Blog/blob/master/nbs/MacKay_chap2.ipynb). You should also check out [Jake VP](https://jakevdp.github.io/blog/2018/09/13/waiting-time-paradox/) and [Allen Downey's](http://allendowney.blogspot.com/2015/08/the-inspection-paradox-is-everywhere.html) blogs mentioned above.
I need to get back to McKay's book. So many more fun puzzles to solve!
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2020-11-13-optimising-allocation-of-poll-observers-to-polling-stations.md
---
layout: "post"
title: "Allocation of poll observers to polling stations with networkx"
date: "2020-11-13 09:46"
comments: true
use_math: true
---
I did a little bit of work recently to help the Wake county in North Carolina allocate poll observers to polling stations. One of the reasons poll observers cancel is because the polling station ends up being too far to travel. Now if we thought of this before we send them an allocation we can find an optimal allocation using one of the many [matching algorithms](https://brilliant.org/wiki/matching-algorithms).
If we have already sent out your assignments, we can still make your poll observers weakly better off by allowing them to trade assignments. This starts getting messy if Lián wants Rohan's polling station, Rohan wants Tere's polling station, and Tere wants Kwame's, and Kwame wants Lián's. Here we look at the Top-trading cycle, a simple algorithm with some very nice properties, that allow us to improve our allocation while making sure no one is worse off (it's pareto improving).
You can find the (really messy) code for [this here](https://github.com/sidravi1/vote2020/blob/main/playground/top_trading_cycle.ipynb).
## Let's make up some data
I'm going to evenly scatter the polling stations and observers so it's obvious to a human on what the optimal allocation would be.
{% highlight python %}
grid_dim = 5
n_names_location = grid_dim**2
x = np.arange(grid_dim)
y = np.arange(grid_dim)
xx, yy = np.meshgrid(x, y)
even_points = np.stack([xx.ravel(), yy.ravel()]).T
observers = pd.DataFrame()
polling_station = pd.DataFrame()
past_names = []
for i in range(n_names_location):
name = names.get_first_name()
while name in past_names:
name = names.get_first_name()
past_names.append(name)
observers = observers.append({
'idx':i,
'observer': name,
'location': even_points[i] /1.5 + 0.75
}, ignore_index=True)
polling_station = polling_station.append({
'idx':i,
'polling_station': f'PollingStation_{i}',
'location': even_points[i]
}, ignore_index=True)
{% endhighlight %}
Let's make a graph out of this and see what it looks like.
{% highlight python %}
G_raw = nx.DiGraph()
for n in polling_station.assigned_observer.values:
G_raw.add_node(n, node_type = 'observer')
for n in polling_station.polling_station.values:
G_raw.add_node(n, node_type = 'poll_station')
# where to draw the nodes
pos = assigment.set_index('polling_station')['location_ps'].to_dict()
pos.update(assigment.set_index('assigned_observer')['location_obs'].to_dict())
{% endhighlight %}

## Optimal Allocation
[Networkx](https://networkx.org/documentation/stable/tutorial.html) is a python library for working with graphs. It's got a tonne of algorithms already coded up for you. This includes the [Karp's matching algorithm](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.bipartite.matching.minimum_weight_full_matching.html). Let's use that to find the optimal matching.
To create our weighted bipartite graph, we need to compute the distance between all our observers and the polling stations.
{% highlight python %}
def get_distance_df(observers, polling_station):
"""
Given a dataset of observers and polling_stations, return a matrix od
distances between them.
Parameters
----------
observers: pd.Dataframe
A dataframe of observers. Should have `observer` and `location` as columns
polling_station: pd.Dataframe
A dataframe of polling_station. Should have `polling_station` and `location` as columns
Returns
-------
distance_df: pd.Dataframe
A dataframe of distances between all observers and polling_stations
"""
obs_idx, poll_st_idx = np.meshgrid(np.arange(observers.shape[0]), np.arange(polling_station.shape[0]))
distance_arr = polling_station['location'].values[poll_st_idx.ravel()] - observers['location'].values[obs_idx.ravel()]
distance_arr = np.stack(distance_arr)
distance_df = pd.DataFrame({'distance':np.linalg.norm(distance_arr, axis=1)})
distance_df['observer_idx'] = obs_idx.ravel()
distance_df['observer_name'] = observers.iloc[obs_idx.ravel()]['observer'].values
distance_df['polling_station_idx'] = poll_st_idx.ravel()
distance_df['polling_station'] = polling_station.iloc[poll_st_idx.ravel()]['polling_station'].values
return distance_df
{% endhighlight %}
Great. Now let's build our graph using networkx.
{% highlight python %}
G_full = nx.DiGraph()
G_full.add_nodes_from(G_raw.nodes(data=True))
for x in distance_df[['polling_station', 'observer_name', 'distance']].itertuples(index = False, name=None):
G_full.add_edge(x[1], x[0], distance = x[2])
{% endhighlight %}
We have added an edge between every polling station and observer. No we can use networkx to solve the matching problem and give us the ones that minimise total distance:
{% highlight python %}
from networkx.algorithms.bipartite.matching import minimum_weight_full_matching
observer_nodes, _ = nx.bipartite.sets(G_full)
optimal_matching = minimum_weight_full_matching(G_full, top_nodes = observer_nodes, weight='distance')
G_optimal = nx.DiGraph()
G_optimal.add_nodes_from(G_raw.nodes(data=True))
G_optimal.add_edges_from(zip(optimal_matching.keys(),optimal_matching.values()), edge_type = 'allocated')
f = draw_allocation(G_optimal, pos, i="")
{% endhighlight %}
`draw_allocation` just renders the graph. Check out [the notebook](https://github.com/sidravi1/vote2020/blob/main/playground/top_trading_cycle.ipynb). if you really want to know how it does that. Here's our optimal match:

### Other use cases
Pretty easy eh? There are a bunch of cases where something like this comes handy. An obvious one may be where the weight on the edges isn't geographic distance but rather reward. You have a team of workers skilled in different things, how do you assign them to tasks to maximise reward?
Another use-case is if you are doing some sort of entity matching. You have a list of names that you want to match with another (possibly larger) list of names. You can use some metric to calculate the "distance" from each name in list 1 to every name in list 2. Setup your network with this distance as edge weights and solve for the optimal match.
## Pareto-optimal reallocation
Say you have already done your allocation and you made a real hash of it because, you know, you did it in excel.

Your observers are already annoyed at you and if you make any of their travel even longer, they are sure to cancel. So we need an algorithm that makes everyone only better off and never worse. We want a Pareto improving re-allocation. The top-trading cycle, or the "House exchange" algorithm as I was taught, gives us exactly that. Here's the algorithm from wikipedia with some minor alterations:
1. Get each observer's "top" (most preferred) polling station. In our case, this will be the polling station closest to the observer.
2. Add an edge from each observer to their top choice of polling station.
3. Note that there must be at least one cycle in the graph (this might be a cycle of length 2, if some observer currently holds their own top polling station). Implement the trade indicated by this cycle (i.e., reallocate each polling station to the observer pointing to it), and remove all the involved observers and polling stations from the graph.
4. If there are remaining observers, go back to step 1.
It's not a lot of code to do this:
{% highlight python %}
def resolve_cycle(G, edges):
""" Remove old edges and add new optimal ones """
G.remove_edges_from(edges)
new_edges = []
for u, v in edges:
if v.startswith("PollingStation"):
G.add_edge(v, u, edge_type = 'allocated')
new_edges.append((v, u))
return G, new_edges
G_pref = build_pref(G_raw, [], distance_df)
resolved_nodes = []
all_cycles = list(nx.simple_cycles(G_pref))
while len(all_cycles) > 0:
for cycle in nx.simple_cycles(G_pref):
if len(cycle) == 2:
G_pref, new_edges = resolve_cycle(G_pref, [(cycle[1], cycle[0]),(cycle[0], cycle[1])])
if cycle[0].startswith("PollingStation"):
poll_node, obs_node = cycle
else:
obs_node, poll_node = cycle
else:
edges = list(zip(cycle[:-1], cycle[1:])) + [(cycle[-1], cycle[0])]
poll_nodes = [x for x in cycle if x.startswith("PollingStation")]
obs_nodes = [x for x in cycle if not x.startswith("PollingStation")]
G_pref, new_edges = resolve_cycle(G_pref, edges)
resolved_nodes += cycle
G_pref = build_pref(G_pref, resolved_nodes, distance_df)
all_cycles = list(nx.simple_cycles(G_pref))
{% endhighlight %}
Here's a series of plots showing how this works:

### Not globally optimal but Pareto optimal
Here's what the final allocation looks like:

It's a lot better than the spaghetti allocation we had at the start -- but not perfect. Check out those polling stations in the bottom left. If the allocations were swapped, total distance travelled would go down but the observer on the right may be slightly worse off.
There are some nice things about this algorithm:
1. It is a _truthful mechanism_: If you don't tell the truth about your preferences, you will only do worse. In our case, we are calculating the distance between the observer's house and the polling station and using that to objectively rank their preferences. If we were to ask them to rank their preferences, it would be a bad idea for them to misrepresent it.
2. It is _core stable_: You can't form a coalition (a subset of observers breaking off to do their own swapping) and do better than you would do if you stayed in the system.
3. Solution is _pareto optimal_: You can't make any observer better off without making someone else worse off.
### Other use cases
Extensions of this won <NAME> and <NAME> the [Nobel prize](https://www.nytimes.com/2012/10/16/business/economy/alvin-roth-and-lloyd-shapley-win-nobel-in-economic-science.html#:~:text=Two%20Americans%2C%20Alvin%20E.,to%20jobs%20to%20organ%20donations.). It has been used in many markets where the items do not have a price and but we want to allow for swapping. Kidney exchange is one such market.
I spent some time trying to adapt this to allow doctors to exchange shifts. Then life happened. Maybe I should pick that back up.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-08-22-poisson-density-estimation-with-gaussian-processes.md
---
layout: "post"
title: "Poisson Density Estimation with Gaussian Processes"
date: "2018-08-22 09:27"
comments: true
use_math: true
---
I have been slowly working my way through Efron & Hastie's [Computer Age Statistical Inference (CASI)](https://web.stanford.edu/~hastie/CASI_files/PDF/casi.pdf). Electronic copy is freely available and so far it has been a great though at time I get lost in the derivations.
In chapter 8, E&H show an example of a Poisson density estimation from a spatially truncated sample. Here, I implement the example using pymc3 and in addition to the latent linear model, I explore Gaussian Processes for the latent variable.
You can get the notebook [from here](https://github.com/sidravi1/Blog/blob/master/nbs/GP_Poisson_density_estimation.ipynb).
## The Problem
You can download the data from [here]("https://web.stanford.edu/~hastie/CASI_files/DATA/galaxy.txt"). From CASI:
> ... shows galaxy counts from a small portion of the sky: 486 galaxies have had their redshift $r$ and apparent magnitude $m$ measured. Distance from earth is an increasing function of $r$, while apparent brightness is a decreasing function of $m$.
Note that this is truncated data. $r$ and $m$ are limited to
$$
1.22 \le r \le 3.32\\
17.2 \le m \le 21.5
$$
Here's what the data table like:

Our job is to fit a density to this truncated data. We are going to model this as
$$
y_i \sim Poisson(\mu_i),\qquad i = 1,2,...,N
$$
So each observation comes from a Poisson with a mean $\mu_i$. Actually, what we'll model instead is $\lambda_i = \log(\mu_i)$.
## Using Linear latent variable
The way Efron & Hastie model $\lambda$ is:
$$
\mathbf{\lambda}(\alpha)= \mathbf{X}\,\alpha
$$
Where $\mathbf{X}$ is a "structure matrix" made up for features we crafted:
$$
\mathbf{X} = [\mathbf{r, m, r^2, rm, m^2}]
$$
Where $\mathbf{r^2}$ is the vector whose components are the square of $\textbf{r}$'s etc. If we think that the true density is bivariate normal, then this makes sense. The log density of a bivariate normal is of this form.
Let's setup this model in pymc3:
{% highlight python %}
with pm.Model() as basic_model:
alpha_0 = pm.Normal('alpha_0', 0, 10)
alpha_1 = pm.Normal('alpha_1', 0, 10)
alpha_2 = pm.Normal('alpha_2', 0, 10)
alpha_3 = pm.Normal('alpha_3', 0, 10)
alpha_4 = pm.Normal('alpha_4', 0, 10)
alpha_5 = pm.Normal('alpha_5', 0, 10)
latent = pm.Deterministic('latent', tt.dot(data_mat_n, tt.stack([alpha_0, alpha_1, alpha_2, alpha_3, alpha_4, alpha_5])))
likelihood = pm.Poisson('like', tt.exp(latent), observed=data_long['val'].values)
{% endhighlight %}
Let's see what our density looks like:

Because we setup a Bayesian GLM, not only do we have the mean values for $\mu$, we have the full distribution. The plot on the right shows the the standard deviation and as you might have expected, it's high in the region where we didn't have any data.
## Using a Gaussian Process
If we are comfortable being agnostic of the functional form -- and since I am not an astrophysicist, I'm quite comfortable -- we can use a 2-d gaussian process. You may want to out the previous posts on Gaussian Processes:
1. [Intro to gaussian processes]({{ site.baseurl }}{% post_url 2018-04-03-gaussian-processes %})
2. [Latent GP and binomial likelihood]({{ site.baseurl }}{% post_url 2018-05-15-latent-gp-and-binomial-likelihood %})
So now our lambda is:
$$
\mathbf{\lambda_i} = f^* (x_i)
$$
Here $x$ is $(r, m)$, a point on the grid and $f(x)$ is a Gaussian Process:
$$
f(x) \sim GP(m(x), k(x, x'))\\
f^* (x) = f(x) | y
$$
(Sorry about the loose notation).
Here's the model in pymc3:
{% highlight python %}
with pm.Model() as gp_model:
ro = pm.Exponential('ro', 1)
eta = pm.Exponential('eta', 1)
K = eta**2 + pm.gp.cov.ExpQuad(2, ro)
gp = pm.gp.Latent(cov_func=K)
# Note that we are just using the first two columns of
# data_mat which correspond to 'r' and 'm'
latent = gp.prior('latent', X=data_mat[:,:2])
likelihood = pm.Poisson('like', tt.exp(latent), observed=data_long['val'].values)
{% endhighlight %}
And the resulting density:

The standard deviation surface looks a lot bumpier but the general trend is similar; it is higher in areas where we have little data. Very cool, but is that model any good?
## Deviance residual
Efron & Hastie use the deviance residual to check the goodness of fit.
$$
Z = sign(y - \hat{y})D(y, \hat{y})^{1/2}
$$
Side note: this is based on KL-divergence so I couldn't figure out how they got around the problem of 0. For KL-divergence you need to have non-zero probabilities in the entire domain. I just ignore the 'NaNs' resulting from it and pretend like nothing happened.
{% highlight python %}
def deviance_resid(y, mu):
def D(mu1, mu2):
return 2 * mu1 * (((mu2/mu1) - 1) - np.log(mu2/mu1))
return np.sign(y - mu) * np.sqrt(D(y, mu))
{% endhighlight %}
Comparing the sum of squares of the residual, we get 109.7 for the GP model and 134.1 for the linear model. This next plot shows these residuals.
<div id="vis3"></div>
<script type="text/javascript">
var spec = "{{"/assets/2018_08_22_comparing_resid.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis3', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
Looks like the GP model fits the top left corner better than the linear model but it also fits that stray bottom right dot that makes me worry that it might be overfitting. One way around it would be to use a different implementation of GP that allows for additive noise.
We can check for overfitting by looking at WAIC for the two using pymc3's `compareplot`:

Looks like the GP-model is the better model. Check out [the notebook ](https://github.com/sidravi1/Blog/blob/master/nbs/GP_Poisson_density_estimation.ipynb) and let me know if there are ways you would improve this. How can we implement this using `gp.marginal` or `gp.conditional` so that we can include additive noise?
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-11-20-logit-choice-estimating-on-a-subset-of-alternatives.md
---
layout: "post"
title: "Logit Choice Model - Estimating on a subset of alternatives"
date: "2019-11-20 10:33"
comments: true
use_math: true
---
In the [last]({{ site.baseurl }}{% post_url 2019-11-10-logit-choice-model %}) [two posts]({{ site.baseurl }}{% post_url 2019-11-11-logit-choice-advantages-of-iia %}), we explored some features of the logit choice model. In the first, we looked at systematic taste variation and how that can be accounted for in the model. In the second, we explored one of nice benefits of the IIA assumption - we provided a random subset of alternatives of varying size to each decision maker and were able to use that to estimate the parameters.
In this post, we look at another feature of the logit model - estimating the $\beta$s using a subset of alternatives.
You can get the [notebook here](https://github.com/sidravi1/Blog/tree/master/nbs/logit_choice) if you'd like to play along.
## Constructing the subset
Say the decision maker chooses between $F$ different alternatives where $F$ is quite large. Estimating with that many alternative is quite hard. With a logit model, we can just use a subset of size $K$ where $K << F$. Specifically, if the decision maker chose alternative $i$ out of $F$, we can construct a smaller subset which contains $i$ and some other $K-1$ alternatives and use that for estimation.
As an example, let's say a commuter is choosing between modes of transport to get to work. She has 100 different options like drive, walk, train, uber, canoe, ... , skydive, helicopter. Say she chooses 'canoe', the lucky woman. We don't need to use all the other alternatives when estimating her tastes, we can just create a subset that includes canoe. One such subset might be *{canoe, walk, get a mate to drop you off}*.
## Uniform conditioning property
Let's call the probability of choosing a subset $K$ given the person chose alternative $i$, $q(K \vert i)$. The following is the uniform conditioning property.
$$
q(K \vert i) = q(K \vert j)\,\,\, \forall j \in K
$$
If you are picking all the other items that make up $K$ randomly, then you are are satisfying the uniform conditioning property. As your reward, you can just go ahead and estimate as we did in the previous posts where your alternatives set will be $K$ instead of $F$. This turns out to be a consistent (but not efficient) estimator of your $\beta$ parameters.
## Non-uniform conditioning
Basically, $q(K \vert i) \ne q(K \vert j)\,\,\, \exists j \in K$
Why in the world would you want to do that? If most of the options are rarely ever taken (since they are terrible), picking $K$ randomly will give you subsets made up of the chosen alternative plus a bunch of highly undesirable ones. Imagine getting the following subset: *{bus, hot air balloon, swim the Yarra}* where $i$ is *'bus'*. If you have been anywhere near the Yarra, you know what a terrible option the last one is. You won't learn much by observing the decision maker choose the bus over it.
One way that Train et al (1987a) get around this is by constructing the subset, $K$, based on its market share. So highly desirable options would be more likely to make it into the subset.
### Adjusting the likelihood
If are going to violate the uniform conditioning property then we need to calculate $q(K \vert j)$ for all $j \in K$. This is a combinatorial problem and if $K$ is large, it going to use a few CPU cycles. If you know of clever algorithms to do this, please let me know.
Now the (conditional) likelihood is:
$$
CLL(\beta) = \sum_n \sum_{i \in K_n} y_{ni} \ln\frac{exp(V_{ni} + ln(q(K \vert i)))}{\sum_{j \in K} exp(V_{nj} + ln(q(K \vert j)))}
$$
So we are basically augmenting the utility with the log of probability of that set being chosen.
## Simulation
Let's simulate this up with a simple example.
### Setup data
Let's setup the parameters for the simulation.
{% highlight python %}
np.random.seed(31)
n_alternatives = 100
n_params = 7 # 2^7 > 100 so we're good
n_choices = 3 # size of subset K
n_decision_makers = 1000
beta_trues = np.random.randint(-7, 7, size=n_params)
{% endhighlight %}
Create features for the alternatives. I'm keeping them all binary here (either the alternative has that feature or it does not) to keep it simple. Note that the option 0 is our outside option that'll give zero utility.
{% highlight python %}
all_alternative_features = []
for i in range(n_alternatives):
features = map(int, np.binary_repr(i, width = n_params))
all_alternative_features.append(list(features))
all_alternative_features = np.vstack([np.zeros((1, n_params)), np.random.permutation(all_alternative_features[1:])])
{% endhighlight %}
Let's make up some market shares. The first 5 will be "significant" and then rest are tiny.
{% highlight python %}
main_shares = np.array([0.3, 0.2, 0.15, 0.15, 0.1])
other_shares = np.random.dirichlet(np.ones(n_alternatives - 5), size=1).squeeze() * 0.1
market_shares = np.hstack((main_shares, other_shares))
{% endhighlight %}
Here's what that looks like:

Finally, unconditional probability of an item being picked is just the market share:
{% highlight python %}
probability_of_picked = market_share
{% endhighlight %}
### Make choices
Remember that the decision maker is choosing amongst *all* the alternatives. It's only for estimation that we'll be restricting it to a subset. Let's simulate this decision-making similarly to what we did in the last few posts:
{% highlight python %}
# Calculate utilities and the item chosen
utilities = all_alternative_features @ beta_trues + np.random.gumbel(0, 2, size=(n_decision_makers, n_alternatives))
# index of the item chosen
idx_chosen = np.argmax(utilities, axis=1)
{% endhighlight %}
### Make subsets $K$
We know that the alternative chosen has to be in the set. Let's pick the other ones:
{% highlight python %}
choice_sets = []
for i in range(n_decision_makers):
id_chosen = idx_chosen[i]
prob = probability_of_picked.copy()
prob[id_chosen] = 0
prob = prob / prob.sum()
other_alternatives = np.random.choice(np.arange(n_alternatives), size = n_choices,
replace = False, p = prob)
choice_set = np.hstack((id_chosen, other_alternatives))
choice_sets.append(choice_set)
choice_sets = np.array(choice_sets)
{% endhighlight %}
### Calculate $q(K | i)$
Here are some supporting functions to calculate $q(K \vert i)$. Love me a good recursion.
{% highlight python %}
def q_K(K, probs):
if len(K) == 0:
return 1
else:
total = 0
for x in K:
val, probs_new = prob(x, probs)
total += val * q_K(K[K!=x], probs_new)
return total
def prob(x, probs):
probs_new = probs.copy()
val = probs_new[x]
probs_new[x] = 0
probs_new = probs_new / probs_new.sum()
return val, probs_new
def q_Ki(i, K, probs):
probs_copy = probs.copy()
probs_copy[i] = 0
probs_copy = probs_copy / probs_copy.sum()
return q_K(K[K != i], probs_copy)
{% endhighlight %}
I'm going to vectorize `q_Ki` since we need to calculate it for $\forall j \in K$. And then just run it for all the choice sets.
{% highlight python %}
qK_i_matrix = []
for i in range(n_decision_makers):
qKi_prob = q_Ki_vec(i = choice_sets[i, :].copy(),
K = choice_sets[i, :].copy(),
probs = probability_of_picked.copy())
qK_i_matrix.append(qKi_prob)
qK_i_matrix = np.array(qK_i_matrix)
ln_qKi_matrix = np.log(qK_i_matrix)
{% endhighlight %}
Note that when we constructed our choice sets, we made the alternative that was chosen the first one item in the array. Let's make our choice matrix indicating which one was chosen.
{% highlight python %}
choice = np.zeros((n_decision_makers, n_choices + 1))
choice[:, 0] = 1
{% endhighlight %}
### Inference
The pymc3 model is pretty straightforward now:
{% highlight python %}
with pm.Model() as m_sampled_reweighted:
betas_rest = pm.Normal('betas', 0, 3, shape=n_params)
V = tt.dot(choice_set_features, betas_rest) + ln_qKi_matrix
p = tt.nnet.softmax(V)
pm.Multinomial('ll', n=1, p=p, observed = choice)
{% endhighlight %}
Hit the inference button, and you have the $\beta$ parameters recovered.

## Final words
You can find the [notebook here](https://github.com/sidravi1/Blog/tree/master/nbs/logit_choice). The ones for the previous posts are up there as well. Next up the GEV model.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2020-06-20-linear-gaussian-state-space-models.md
---
layout: "post"
title: "Linear Gaussian State Space Models"
date: "2020-06-20 14:14"
comments: true
use_math: true
---
State space models (SSM) are a tonne of fun. I sneaked one into [a this post]({{ site.baseurl }}{% post_url 2018-10-17-cross-country-convergence%}) I did a while ago. In that post, I was recreating an analysis but using a state space model where the hidden state, the true $\beta$s were following a Gaussian Random Walk and what we observed was the growth in GDP. In this post, I'm going to explore a generalised version of the model - the linear-Gaussian SSM (LG-SSM).
The notation I am following is from Chapter 18 of [Murphy's Machine Learning book](https://mitpress.mit.edu/books/machine-learning-1).
You can check out the (messy) notebook [here](https://github.com/sidravi1/Blog).
## What's an LG-SSM
A state space model is like an HMM which I wrote about in [these two]({{ site.baseurl }}{% post_url 2019-01-25-heirarchical-hidden-markov-model%}) [blog posts]({{ site.baseurl }}{% post_url 2019-02-25-em-or-baum-welch-for-hmm-learning%}). Instead of the hidden states being discrete, they are now continuous. So the model is:
$$
\begin{aligned}
\mathbf{z}_t &= g(\mathbf{u}_t, \mathbf{z}_{t-1}, \mathbf{\epsilon}_t)\\
\mathbf{y}_t &= h(\mathbf{z}_t, \mathbf{u}_t, \mathbf{\delta}_t)
\end{aligned}
$$
$\mathbf{z_t}$ is our hidden state that is evolving as a function, $g$, of:
- the previous state, $\mathbf{z}_{t-1}$,
- the input, $\mathbf{u}_t$, and
- some noise $\mathbf{\epsilon}_t$.
What we observe is $\mathbf{y}_t$. This is a some function, $h$, of:
- the hidden state, $\mathbf{z}_t$,
- the input, $\mathbf{u}_t$, and
- some measurement error $\mathbf{\delta}_t$.
If we have a model where $g$ and $h$ are both linear functions and both of those error terms are Gaussian, we have **linear-Gaussian SSM (LG-SSM)**. More explicitly, we have:
$$
\begin{aligned}
\mathbf{z}_t &= \mathbf{A}_t \mathbf{z}_{t-1} + \mathbf{B}_t \mathbf{u}_t + \epsilon_t\\
\mathbf{y}_t &= \mathbf{C}_t \mathbf{z}_t\,\,\,\, + \mathbf{D}_t \mathbf{u}_t + \delta_t
\end{aligned}
$$
and the system and observation noises are Gaussian:
$$
\begin{aligned}
\epsilon_t &\sim \mathcal{N}(0, \mathbf{Q}_t)\\
\delta &\sim \mathcal{N}(0, \mathbf{R}_t)
\end{aligned}
$$
In the growth regression model, $A_t$ was 1, $C_t$ was the GDP level, and $B_t$ & $D_t$ were 0.
## Let's simulate some data
{% highlight python %}
size = 100
np.random.seed(15)
z0 = 0.5
ut = np.random.choice(np.arange(-2, 3), size=size)
zt = np.zeros(ut.shape[0])
yt = np.zeros(ut.shape[0])
A = 0.9
B = 2
C = 2
D = -1
Q = 2.9
R = 4
for i, u in enumerate(ut):
if i == 0:
zt[i] = z0
else:
zt[i] = A[i] * zt[i - 1] + B * ut[i] + np.random.normal(0, Q)
yt[i] = C * zt[i] + D * (ut[i]) + np.random.normal(0, R)
{% endhighlight %}

Note a few simplifications:
- We are just using scalars but $\mathbf{z}_t$ can be multi-dimensional and therefore $Q$, $A$ can be appropriately sized square matrices. A local linear trend model is an example.
- Similarly, so can $\mathbf{u}_t$
- Further, these parameters can be changing over time.
## Kalman filtering / smoothing
The nice thing about LG-SSM is that if you know the parameters of the system, you
can do exact Bayesian filtering to recover the hidden state. A lot has been written about it so I won't go into this in too much detail here. I'll just leave the algorithm from Murphy's book here:


You can check out the simple implementation in the notebook. Here are the filtered values we get for $\mathbf{z}_t$:

Kalman filters tend to be [quite robust](http://henrikmadsen.org/wp-content/uploads/2014/05/Journal_article_-_2006_-_Parameter_sensitivity_of_three_Kalman_filter_schemes_for_assimilation_of_water_levels_in_shelf_sea_models.pdf) to getting the parameters a bit wrong. Which is good since you don't always know the parameters exactly. Here's the filtering with the following parameters:
{% highlight python %}
params["A"] = 0.4 # actual 0.9
params["B"] = 3 # actual 2
params["Q"] = 4.9 # actual 2.0
params["C"] = 1 # actual 1.0
params["D"] = -1 # actual -1
params["R"] = 6 # actual 4
{% endhighlight %}

And if you are smoothing (using data filter for all time periods, $T$, to estimate the value for time $t$), then you do even better:

## PYMC3 to infer parameters
PYMC3 has some time-series methods implemented for you. If you squint, the hidden process $\mathbf{z}_t$ is pretty similar to the an $AR1$ process. The only difference is that instead of:
$$
z_{t + 1} = A z_t + \epsilon_t
$$
we have:
$$
z_{t + 1} = A z_t + B u_t + \epsilon_t
$$
So let's just modify the $AR1$ implementation for this change:
{% highlight python %}
class LinearGaussianSSM(pm.distributions.distribution.Continuous):
"""
Linear Gaussian SSM with 1 lag.
Parameters
----------
k: tensor
effect of lagged value on current value
tau_e: tensor
precision for innovations
mu: tensor
the mean shift for the process
"""
def __init__(self, k, tau_e, mu, *args, **kwargs):
super().__init__(*args, **kwargs)
self.k = k = tt.as_tensor_variable(k)
self.tau_e = tau_e = tt.as_tensor_variable(tau_e)
self.tau = tau_e * (1 - k ** 2)
self.mode = tt.as_tensor_variable(0.0)
self.mu = tt.as_tensor_variable(mu)
def logp(self, x):
"""
Calculate log-probability of LG-SSM distribution at specified value.
Parameters
----------
x: numeric
Value for which log-probability is calculated.
Returns
-------
TensorVariable
"""
k = self.k
tau_e = self.tau_e # innovation precision
tau = tau_e * (1 - k ** 2) # ar1 precision
mu = self.mu
x_im1 = x[:-1]
x_i = x[1:]
boundary = pm.Normal.dist(0, tau=tau).logp
innov_like = pm.Normal.dist(k * x_im1 + mu, tau=tau_e).logp(x_i)
return boundary(x[0]) + tt.sum(innov_like)
def _repr_latex_(self, name=None, dist=None):
if dist is None:
dist = self
k = dist.k
tau_e = dist.tau_e
name = r"\text{ %s }" % name
return r"${} \sim \text{{LGSSM1}}(\mathit{{k}}={},~\mathit{{tau_e}}={},~\mathit{{mu}}={})$".format(
name, get_variable_name(k), get_variable_name(tau_e), get_variable_name(mu)
)
{% endhighlight %}
That's it. Easy. Now let's fit the model:
{% highlight python %}
with pm.Model() as model:
sig = pm.HalfNormal("σ", 4)
alpha = pm.Beta("alpha", alpha=1, beta=3)
sig1 = pm.Deterministic(
"σ1", alpha * sig
)
sig2 = pm.Deterministic(
"σ2", (1 - alpha) * sig
)
A_ = pm.Uniform("A_", -1, 1)
B_ = pm.HalfNormal("B_", 2)
mu = B_ * ut[1:]
f = LinearGaussianSSM("z", k=A_, tau_e=1 / (sig1 ** 2), mu=mu, shape=yt.shape)
C_ = pm.HalfNormal("C_", 2)
D_ = pm.Normal("D_", 0, 2)
y_mu = pm.Deterministic("y_mu", C_ * f + D_ * ut)
likelihood = pm.Normal("y", mu=y_mu, sd=sig2, observed=yt)
trace = pm.sample(1000, target_accept=0.99, tune=3000)
{% endhighlight %}
That splitting of the $\sigma$ is a trick I picked up from pymc3 discourse. The total variation needs to be distributed between the two levels. We'll introduce another parameter, $\alpha$, that determines the allocation of the variation to each.

Those divergences seems to be when $\sigma 1$ gets too small. We could try other parameterisations to shake those off. Overall, we seem to have recovered the parameters pretty well.
And here's the posterior for the hidden state:

## PYMC3 with non-stationary parameters
An SSM where the parameters don't change is called stationary. Here's one where $A$ is not static but rather changes as a cosine function.
{% highlight python %}
size = 100
np.random.seed(15)
z0 = 0.5
ut = np.random.choice(np.arange(-2, 3), size=size)
zt = np.zeros(ut.shape[0])
yt = np.zeros(ut.shape[0])
A = 0.9 * np.cos(np.linspace(0, 2 * np.pi * 2, size))
B = 2
C = 2
D = 0
Q = 2.9
R = 4
for i, u in enumerate(ut):
if i == 0:
zt[i] = z0
else:
zt[i] = A[i] * zt[i - 1] + B * ut[i] + np.random.normal(0, Q)
yt[i] = C * zt[i] + D * (ut[i]) + np.random.normal(0, R)
{% endhighlight %}
Here's what the data look like:

### Fitting the models
The key thing we are changing is that we are modelling $A$ as Gaussian Random Walk. So $A$ changes slowly over time.
{% highlight python %}
with pm.Model() as model2:
sig = pm.HalfNormal("σ", 4)
alpha = pm.Beta("alpha", alpha=1, beta=3)
sig1 = pm.Deterministic(
"σ1", alpha * sig
)
sig2 = pm.Deterministic(
"σ2", (1 - alpha) * sig
)
A_sigma = pm.HalfNormal("A_sigma", 0.2)
A_ = pm.GaussianRandomWalk(
"A_", mu=0, sigma=A_sigma, shape=(size), testval=tt.zeros(size)
)
B_ = pm.HalfNormal("B_", 2)
mu = B_ * ut[1:]
f = LinearGaussianSSM("z", k=A_[1:], tau_e=1 / (sig1 ** 2), mu=mu, shape=yt.shape)
C_ = pm.HalfNormal("C_", 2)
D_ = pm.Normal("D_", 0, 2)
y_mu = pm.Deterministic("y_mu", C_ * f + D_ * ut)
likelihood = pm.Normal("y", mu=y_mu, sd=sig2, observed=yt)
trace2 = pm.sample(1000, target_accept=0.99, tune=3000)
{% endhighlight %}
### Results
Check out the notebook. Divergences abound. Maybe you can fix it. But I just want to show you what the posterior looks like:

And most interestingly, what we learn about $A$:

Not great but generally there.
## Conclusions
When the observation error in $y_t$ and the system error in $z_t$ are both large, these models do well. If not, you can probably use a simpler model and do just fine.
### The bloopers reel
Fitting these models is tricky. I was listening to [<NAME>'s](https://twitter.com/alex_andorra) [podcast](https://www.listennotes.com/podcasts/learning-bayesian-statistics-alexandre-6QgmfqXD0GI/). Good podcast, check it out. They often talk about how tricky these models can be. I spent a lot of time debugging divergences and failed chains. One example is if specifically telling the model that $A$ follows a cosine of some frequency. Or if you even give it the frequency but you say it follows a sine with some phase. You'd think these model would fit better. I couldn't figure out why it doesn't. I also tried using `pm.Bound` to restrict $A$ to be between -1 and 1. You'd think that would help it along. Nope - I guess gradient go funny at the edges when you use `pm.Bound`.
In the model above, try making `C_` and `B_` Normals instead of a Half Normals. You see something interesting - the posterior for these values is bimodal. And your `rhat` values are wild since your chains might be exploring different modes. And that makes sense. The hidden state can be the inverted as long as you are inverting the coefficient `C_` as well. Obvious now in hindsight but not something I had thought about before I ran the model.
At some stage, I'd love to do a post of just my hacky failures. All those attempts to fit fancy models that came to nothing. Also, should talk about how good the pymc3 discourse it.
<file_sep>/_posts/2018-05-15-latent-gp-and-binomial-likelihood.md
---
layout: "post"
title: "Latent GP and Binomial Likelihood"
date: "2018-05-15 15:16"
comments: true
use_math: true
---
I did a quick [intro to gaussian processes]({{ site.baseurl }}{% post_url 2018-04-03-gaussian-processes %})
a little while back. Check that out if you haven't.
I came across [this presentation](https://www.youtube.com/watch?v=-sIOMs4MSuA) by <NAME> delivered just a few days back at PyCon 2018 on Bayesian non-parametric models. I found the idea of modeling latent variables using a Gaussian process (GP) very intriguing (and cool). We know that the latent variable has some non-linear form so instead of guessing what it might be, we can just model it using a GP.
You can get the [notebook](https://github.com/sidravi1/Blog/blob/master/nbs/Binomial%20Gaussian%20Process.ipynb) with all the code to generate the charts and the analysis here.
## Moving on from a linear model
In chapter 10 of [Statistical Rethinking](http://xcelab.net/rm/statistical-rethinking/), McElreath looks at the UC Berkeley graduate school admittance rate for men and women in a 6 departments. He models the admission rate as $logit(p_i) = \alpha_{DEPT[i]} + \beta_m m_i$. Note that he is modeling the latent variable as a linear function.
Here, we look at a similar dataset but model the latent variable as a GP using pymc3.
## The data and the question
We'll use [this census data](http://archive.ics.uci.edu/ml/datasets/Census+Income) from 1994 but only look at some of the features. We want to look at the wages for men and women at different ages.
The key outcome variable of interest is *>50k* i.e. how many people earn over 50k given the other parameters. Or, what percent of people in a given demographic earn over 50k. The other variable of interest are: *age*, *edu*, and *sex*. There are other interesting variables that you may want to use to extend this model such as *race*, *sector*, and *marital status* but we'll leave this out for now.
We also group *edu* into sensible buckets so that we end up with just 7 education groups: "Some HS", "HS Grad", "Some College", "Prof School", "Bachelors", "Masters", "Doctorate".
## Take 1: Using just age
Let's ignore education for now. We'll come back to it in the next section.
### The correlation assumption
In 'Take 1', we use just the age and sex variable and park education for the next section. By using a GP, we assume that the probability of earning over 50k at age $x$ and $x + k$ are correlated. The closer they are (the smaller $\|k\|$ is), the more correlated they are. We'll use the RBF kernel to do this since we expect it to change smoothly.
### Modeling in pymc3
For each sex, we model the latent variable as a GP with pooled hyper-parameters. So the model is as follows:
{% highlight python %}
with pm.Model() as admit_m:
rho = pm.Exponential('ρ', 1)
eta = pm.Exponential('η', 1)
K = eta**2 * pm.gp.cov.ExpQuad(1, rho)
gp1 = pm.gp.Latent(cov_func=K, )
gp2 = pm.gp.Latent(cov_func=K)
f = gp1.prior('gp_f', X=f_age)
m = gp2.prior('gp_m', X=m_age)
pi_f = pm.Deterministic('π_f', pm.invlogit(f))
pi_m = pm.Deterministic('π_m', pm.invlogit(m))
earning_f = pm.Binomial('female_over50k', p = pi_f, n=f_n.astype(int),
observed=f_over50k.astype(int))
earning_m = pm.Binomial('male_over50k', p = pi_m, n=m_n.astype(int),
observed=m_over50k.astype(int))
{% endhighlight %}
Easy enough. Now let's draw a bunch of samples and see what $p$, the probability of earning over 50k, looks like for the two sexes.

So it appears that the gap between the wages of men and women starts pretty early on and is the widest around the age of 50. Also interesting to note is that the peak for men is at 50 years while for women it's around 40 years.
But we know that education makes a different. Maybe we just have a bunch of highly educated men in this sample so it makes sense that they would earn more.
## Take 1: Using age and education
Now we include education.
### The correlation assumption
In addition to the 'correlation across ages' assumption we made above, we also assume that the effect of education is correlated i.e. effect of "Masters" is closer to the effect of "Bachelors" than to "Some HS".
We are also assuming one other thing: effect of education is the same across age groups and the effect of age is the same for all levels of education i.e. those two are independent. This doesn't sound unreasonable though you can come up with reasons why this might not be true. We can get even smarter and say the education and age together are correlated but we'll leave that for you to work out.
### Modeling in pymc3
{% highlight python %}
with pm.Model() as admit_m:
rho = pm.Exponential('ρ', 1)
eta = pm.Exponential('η', 1)
rho_edu = pm.Exponential('ρ_edu', 1)
eta_edu = pm.Exponential('η_edu', 1)
K = eta**2 * pm.gp.cov.ExpQuad(1, rho)
K_edu = eta_edu**2 * pm.gp.cov.ExpQuad(1, rho_edu)
gp1 = pm.gp.Latent(cov_func=K)
gp2 = pm.gp.Latent(cov_func=K)
gp_edu = pm.gp.Latent(cov_func=K_edu)
f = gp1.prior('gp_f', X=age_vals)
m = gp2.prior('gp_m', X=age_vals)
edu = gp_edu.prior('gp_edu', X=edu_vals)
pi_f = pm.Deterministic('π_f', pm.invlogit(f[f_age_idx] + edu[f_edu_idx]))
pi_m = pm.Deterministic('π_m', pm.invlogit(m[m_age_idx] + edu[m_edu_idx]))
earning_f = pm.Binomial('female_over50k', p = pi_f, n=f_n.astype(int),
observed=f_over50k.astype(int))
earning_m = pm.Binomial('male_over50k', p = pi_m, n=m_n.astype(int),
observed=m_over50k.astype(int))
{% endhighlight %}
Note that it is a very similar model and took me ~22 minutes to run on a oldish MacBook Pro. You might remember that GP is a 'small data' technique. It involves inverting matrices that is computationally quite expensive.
Now let's look at how this varies across education level:

We see a wage gap in all levels of education. In the lowest categories, the gap in absolute terms is not great but in relative terms it's yuge! The 'plateauing' effect for women is also interesting. The probability of earning over 50k doesn't increase by much after mid-30s/40s for women.
Note that the relationship with age is not linear in any sense. It looks like a quadratic... maybe. If you're a classical economist, you're sure it's quadratic, we're talking about age after all, but it's nice being agnostic.
Let's look at the mean probability of earning over 50k in our model as a heat map.

Darker cells represent higher probability of earning over 50k. Note that we are only showing the mean values here. Since we're all Bayesian, we have the full distribution here and can show any statistics we like. Also, we noted above that there is large variation in higher ages so we should keep that in mind.
What's with the gaps? Well, we had no data for those cells (e.g. there are no 90 year old women with Doctorates in our datasets). But fear not, we can use the model we have trained to predict it for those cells.
{% highlight python %}
age_m = samples['gp_m']
age_f = samples['gp_f']
edu_gp = samples['gp_edu']
female_pp = np.zeros((len(age_vals),len(edu_vals),2000))
male_pp = np.zeros((len(age_vals),len(edu_vals),2000))
for i in tqdm(range(len(age_vals))):
for j in edu_vals:
female_pp[i,j,:] = pm.invlogit(age_f[:,i].reshape(-1,1) + edu_gp[:,j].reshape(-1,1)).eval().T
male_pp[i,j,:] = pm.invlogit(age_m[:,i].reshape(-1,1) + edu_gp[:,j].reshape(-1,1)).eval().T
{% endhighlight %}
And plotting this:

There is just more dark green for men. The earning gap exist everywhere. Unless, maybe, if you're a kid. Anyone got a dataset of lemonade stand revenues for boys vs. girls?
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-09-04-computer-age-statistical-inference-chapter-9.md
---
layout: "post"
title: "Computer Age Statistical Inference (Chapter 9)"
date: "2018-09-04 12:56"
comments: true
use_math: true
---
I've been reading Efron & Hastie's [Computer Age Statistical Inference (CASI)](https://web.stanford.edu/~hastie/CASI_files/PDF/casi.pdf) in my downtime. Actually, I'm doing better than reading. I don't know why I didn't think of this earlier - the best way to truly understand the material is to have your favourite statistical package open and actually play around with the examples as you go.
I thought of this as I was reading Chapter 9. [Here is the notebook](https://github.com/sidravi1/CASI_Examples/blob/master/nbs/Ch9_survival_analysis.ipynb) for it. If you have the book (it's free so go get it), the notebook if pretty self-explanatory and doesn't need a full on blog post.
I'll post other chapters in the future and at some stage go back and do chapters 1-8.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-03-11-monte-carlo-methods.md
---
layout: post
title: Monte Carlo Methods
date: '2018-03-11 10:40'
use_math: true
comments: true
---
I imagine most of you have some idea of Monte Carlo (MC) methods. Here we'll try and quantify it a little bit.
Here's a common example. How would you be calculate the area of a circle if a gave you a formula for it's circumference - $ 2 \pi r$. Easy, you say. Just integrate with respect to r and you get $ \pi r^2$.
What if you couldn't easily take the integral? Say you're working with a gaussian pdf and want to take the integral. Not so easy (or even possible) to do it the standard analytical way (that's not entirely true, check out Box-Muller. But we'll call that 'non-standard' so that we are not wrong.). We fall back on numerical methods like the trapezoid rule or Simpson's rule. MC is one additional method. It is computationally less expensive that the other ways when you're working in very high dimensions ( d > 6, is where it starts beating Simpson's rule).
Back to our trivial but oh-so-illuminating circle example. Let's get the area using a MC. We draw a square around it of size 2r x 2r and throw a bunch of darts at it. We calculate the ratio of darts that fall inside the circle to all the darts thrown. This is the ratio of the area of the circle to the area of square, $ 4r^2 $ (which we know to be simply, pi).
Let's formalize this a bit. Say we want to integrate some function h(x). If we draw from any "easy" (like uniform) distribution f(x) :
$$
I = h(x) f(x) dx\\
\hat{I} = \frac{1}{N} \sum_{x_i~ f} h(x_i)
$$
So the process comes down to:
- Draw N samples from a pdf f(x) that has the same support as h(.)
- Calculate h(.) at each of the N samples you drew.
- Take the average of those values
If you're wondering where, the "divide by the integral of f(x) over the support" step is, f(x) is pdf so we know it is one. Easy peasy.
At this stage, it should start looking very familiar to the MCMC rejection/acceptance process. So why do we even need Markov Chains? Let's just take samples from multi-dimensional uniform distribution (or normal if we want), and do the process above.
This brings us on to the curse of dimensionality which we'll leave for another post.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-02-25-em-or-baum-welch-for-hmm-learning.md
---
layout: "post"
title: "Inference and EM (Baum-Welch) for HMM learning"
date: "2019-02-25 16:29"
comments: true
use_math: true
---
Last month, I did a post on how you could [setup your HMM in pymc3]({{ site.baseurl }}{% post_url 2019-01-25-heirarchical-hidden-markov-model %}). It was beautiful, it was simple. It was a little too easy. The *inference button* makes setting up the model a breeze. Just define the likelihoods and let pymc3 figure out the rest.
I have been reading [Murphy's thesis](https://pdfs.semanticscholar.org/60ed/db80f54c796750a8173f2abea3bc85a62322.pdf) for work and decided it'd be a whole lot of fun to implement the EM algorithm for learning. So here we go. The code can be [found online here](https://github.com/sidravi1/Blog/blob/master/nbs/hmm_em.ipynb). Murphy's Machine Learning book was very useful when coding up this algorithm.
Since we are going to be getting into the weeds a bit, let's define some terms. We're going to use the notation from Murphy's thesis. Time goes from $1 ... T$.
* $y_{1:t} = (y_1,...,y_t)$: the observations up to present time, $t$.
* $X_t$: The hidden state at time $t$.
* $P(X_t \vert y_{i:t})$: Belief state at time $t$.
* $P(X_t \vert X_{t-1})$: State-transition function. We assume we have a first-order Markov with transition matrix $A$.
* $\pi$: $P(X_1)$ - the initial state
There are a few types of inferences as per Murphy:
1. **Filtering**: Compute the belief state
2. **Smoothing**: Compute $P(X_t\vert y_{1:T})$ offline, given all the evidence.
3. **Fixed lag smoothing**: Slightly lagged filtering - $P(X_{t-l}\vert y_{1:t})$
4. **Prediction**: Predict the future - $P(X_{t+l}\vert y_{1:t}$)
We're just going to look at the first two: *filtering* and *smoothing*. Then use some of these functions to implement an EM algorithm for learning the parameters.
## Generate data
We'll use the utility classes from the last post to generate some data:
{% highlight python %}
n_samples = 100
t_mat = np.array([[0.8, 0.2],[0.2, 0.8]])
init = 0
sg = SampleGenerator("poisson", [{'lambda':5}, {'lambda': 10}],
2, t_mat)
vals, states_orig = sg.generate_samples(n_samples, init_state=init)
{% endhighlight %}
`vals` are all we observe.
## Filtering - The forwards algorithm
Check out Murphy for the full derivation but the forward algorithm boils down to this:
$$
\begin{aligned}
\mathbf{\alpha}_t &= P(X_t \vert y_{i:t})\\
\mathbf{\alpha}_t &\propto O_t A' \alpha_{t-1}
\end{aligned}
$$
where $A$ is the Markov transition matrix that defines $P(X_t \vert X_{t-1})$ and $O_t(i, i) = P(y_t \vert X_t = i)$ is a diagonal matrix containing the conditional likelihoods at time $t$.
Note that $\alpha_t$ is recursively defined with the base case being:
$$
\alpha_1 \propto O_1\pi
$$
And here it is in python:
{% highlight python %}
def forward_pass(y, t, dists, init, trans_mat):
x0 = dists[0]
x1 = dists[1]
all_c = []
if t == 0:
O = np.diag([x0.pmf(y[0]), x1.pmf(y[0])])
c, normed = normalize(O @ init)
return c, normed.reshape(1, -1)
else:
c_tm1, alpha_tm1 = forward_pass(y, t - 1, dists, init, trans_mat)
O = np.diag([x0.pmf(y[t]), x1.pmf(y[t])])
c, normed = normalize(O @ trans_mat.T @ alpha_tm1[-1, :])
return c_tm1 + c, np.row_stack([alpha_tm1, normed])
{% endhighlight %}
Here's the normalize function that is called in `forward_pass` that we'll use again. Pretty straightforward stuff:
{% highlight python %}
def normalize(mat, axis=None):
c = mat.sum(axis=axis)
if axis==1:
c = c.reshape(-1, 1)
elif axis == 0:
c = c.reshape(1, -1)
return c, mat / c
{% endhighlight %}
Here's what our filtered signal looks like.

The results are pretty good. You could make the problem a little harder by making the two lambdas closer together or throwing in some noise.
## Smoothing - The forwards-backwards algorithm
I like how Murphy explains why uncertainty will be lower in smoothing:
> To understand this intuitively, consider a detective trying to figure out who committed a crime. As he moves through the crime scene, his uncertainty is high until he finds the key clue; then he has an “aha” moment, his uncertainty is reduced, and all the previously confusing observations are, in hindsight, easy to explain.
Here we define two new terms:
$$
\begin{aligned}
\beta_t(j) &= P(y_{t+1:T}|x_t = j)\\
\beta_t(j) &= AO_{t+1}\beta_{t+1}\\
\\
\gamma_t(j) &= P(x_t = j | y_{1:T})\\
\gamma_t(j) &\propto \alpha_t(j) \beta_t(j)\\
\end{aligned}
$$
As with $\alpha$, $\beta$ is recursively defined with the base case:
$$
\beta_T(i) = 1
$$
Let's code this $\beta_t$ up in python:
{% highlight python %}
def backward_pass(y, T, t, dists, init, trans_mat):
x0 = dists[0]
x1 = dists[1]
all_c = []
if t == T:
c, normed = normalize(np.ones(2))
return 0, normed.reshape(1, -1)
else:
c_tm1, beta_tp1 = backward_pass(y, T, t+1, dists, init, trans_mat)
O = np.diag([x0.pmf(y[t+1]), x1.pmf(y[t+1])])
c, normed = normalize(trans_mat @ O @ beta_tp1[-1, :])
return c_tm1 + c, np.row_stack([normed, beta_tp1])
{% endhighlight %}
and then we can put the two together to get $\gamma$:
{% highlight python %}
def gamma_pass(y, T, t, dists, init, trans_mat):
consts_f, state_prob_forward = forward_pass(y, T, dists, init, trans_mat)
consts_b, state_prob_backward = backward_pass(y, T, t, dists, init, trans_mat)
gamma = (state_prob_backward * state_prob_forward)
return gamma
{% endhighlight %}
We were already doing quite well but this improves the AUC even further.

## EM (Baum-Welch) for parameter learning
All that seems fine but we gave the algorithm $A$, $\pi$, and even the parameters associated with the two hidden states. What we learned using pymc3 last time was all of the parameters using just the observations and a few assumptions.
We'll do that again using the EM algorithm.
### Two-slice distributions
We are going to code up the two-slice distribution since it's about to come in handy. It is defined as follows:
$$
\xi_{t-1,t|T}(i, j) = P(X_{t-1} = i, X_t = j | y_{1:T})
$$
and Murphy shows that it can be computed as follows:
$$
\xi_{t-1,t|T}(i, j) = A \circ (\alpha_t (O_{t+1} \circ \beta_{t+1})^T)
$$
(Note: The formula in Murphy's thesis didn't make sense to me so this is going off his book.)
So let's do it:
{% highlight python %}
def two_slice(y, T, t, dists, init, trans_mat):
cs, betas = backward_pass(y, T, t, dists, init, trans_mat)
cs, alphas = forward_pass(y, t-1, dists, init, trans_mat)
alpha = alphas[-1]
beta = betas[0]
O = np.diag([x0.pmf(y[t]), x1.pmf(y[t])])
c, normed = normalize(trans_mat * (alpha @ (O * beta).T), axis=None)
return c, normed
{% endhighlight %}
### E-step
Ugh. There is a tonne of latex here to write. So I'm going take the easy way out and just paste it from the book. Sorry Mr. Murphy if this breaks any laws. Let me know and I'll remove it immediately. Also, I'm a big fan of your work.
This also means that the notation is a little different. $z$ is the hidden state and $\mathbf{x}$ is the observation.

Since we only have one process, let's just drop the summation over $N$. In code, this is:
{% highlight python %}
def E_step(y, A, B, pi):
dists = sct.poisson(B[0]), sct.poisson(B[1])
all_gammas = gamma_pass(y, 99, 0, dists, pi, A)
En1k = all_gammas[0]
Enjk = reduce(lambda x,y : x+y, map(lambda t: two_slice(y, 99, t, dists, pi, A)[1], range(1, 100)))
Enj = reduce(lambda x,y: x + y, all_gammas)
first_term = En1k @ np.log(pi)
middle_term = (Enjk * np.log(A)).sum()
p_z = np.log(np.row_stack([dists[0].pmf(y), dists[1].pmf(y)]))
final_term = (p_z * all_gammas.T).sum()
like = first_term + middle_term + final_term
return like, En1k, Enjk, Enj, all_gammas
{% endhighlight %}
Wow. Such ease. Much elegant.
### M-step
This step is even easier. I won't bother with the math, since the code is quite obvious:
{% highlight python %}
def M_step(y, En1k, Enjk, Enj, all_gammas):
A = Enjk / Enjk.sum(axis=1).reshape(-1, 1)
pi = En1k / En1k.sum()
B = (all_gammas * y.reshape(-1, 1)).sum(axis=0) / Enj
return A, np.round(B), pi
{% endhighlight %}
### Running the EM algorithm
We just need to run the two step until we converge. EM often gets stuck at local minima so you need to be careful how you initialize the variables. Check out Murphy 17.5.2.3 for tips on how to tackle that.
{% highlight python %}
np.random.seed(55)
max_iter = 100
i = 0
pi_init = np.array([0.5, 0.5]) #npr.dirichlet(alpha=[0.5, 0.5])
z_init = npr.randint(0, 2, size=n_samples)
A_init = npr.dirichlet(alpha=[0.5, 0.5], size=2)
B_init = np.array([1, 20])
# I want to keep a copy of my init vars
z = z_init.copy()
A = A_init.copy()
B = B_init.copy()
pi = pi_init.copy()
like_new = 1e10
like_old = 1e-10
print("\n A_init:{}, B_init:{}, pi_init:{}".format(A, B, pi))
print("----------------------")
while (np.abs(like_new - like_old) > 1e-5) and (i < max_iter):
like, En1k, Enjk, Enj, all_gammas = E_step(y, A, B, pi)
like_old = like_new
like_new = like
A, B, pi = M_step(y, En1k, Enjk, Enj, all_gammas)
i += 1
{% endhighlight %}
Check out the notebook for how it does in learning $A$, $\pi$, and the parameters for the hidden state. It's not perfect (and of course, no credible intervals like in the bayesian case) but it's decent.
And here's what the smoothed signal looks like:

## Conclusion
I enjoyed that a lot. Check out the [notebook here](https://github.com/sidravi1/Blog/blob/master/nbs/hmm_em.ipynb). Might do a Kalman Filter one next.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/resume_old.md
---
layout: resume
title: Resume
---
*Data scientist and researcher with a background in Computer Science and Econometrics. Loves building bespoke machine learning models designed to inform business actions. Enjoys learning, experimentation, and building things.*
## Education
---
### MASTER IN PUBLIC ADMINISTRATION in INTERNATIONAL DEVELOPMENT (2016)
Harvard Kennedy School of Government, MA<br>
*econometrics, macroeconomics, microeconomics, data science, statistics, machine learning*
### BACHELOR OF ENGINEERING (ELEC.) /BACHELOR OF SCIENCE (COMP.) (Hons) 2004
University of Melbourne, Australia
**Tools:** Python (incl. pymc3, pytorch, pyspark), R, Stata, Scala, AWS/EC2, DataBricks<br>
**Skills:** Bayesian Inference, Optimization, Causal Inference, Statistical modelling, Machine Learning, Econometrics.
## Experience
---
### Senior Data Scientist (QuantumBlack, McKinsey & Company)
*Cambridge, MA (Sep 2018 - current)*
- **Pharma** - Mined electronic medical records to understand causes of patient switching behavior. Analytics was used to improve targeting for various marketing channels.
- **Disaster Recover** - Developed Monte Carlo models to quantify uncertainty in key milestones to inform mitigation strategies. Models were used to better understand possible states of the world prepare contingency plans.
- **Chemical manufacturing** - Identified root cause of variability in production yields. Identified levers that can used to improve yield. Optimized manufacturing process using genetic algorithms.
- **Internal R&D** - Contributed to an internal package for causal inference using Bayesian Networks.
### Graduate Research Fellow (Centre for International Development)
*Cambridge, MA (Nov 2016 - Aug 2018)*
- **Developed Machine Learning models** to identify export sector growth opportunities at sub-national level in Colombia.
- Built **collaborative filtering models** to predict rural agricultural diversification and recommended possible areas for investment in Colombia.
- **Used Collaborative Filtering and network analysis** to understand patterns and predict changes in global tourism using credit card transactions data.
### Team Member/Economist (Office of the Chief Economic Advisor, Ministry of Finance)
*New Delhi, India (June 2015 – Aug 2015 / Dec 2015 – Feb 2016)*
- **Contributing writer for the 2016 Economic Survey** – Conducted analysis and wrote the chapter on fertilizer subsidy in the 2016 Indian Economic Survey.
- **Policy reform for fertilizer** – Demonstrated how current policy leads to shortages and black markets. Worked with Ministry of Fertilizer & Chemicals to design a new policy that is was presented to the cabinet.
- **Created analytics on social and economic development** – Analysed recently released SECC census data to highlight variation in various metrics of welfare in India for presentation to the Finance Minister.
### Senior Associate, Global Markets Team (Clinton Health Access Initiative)
*sub-Saharan Africa (Aug 2012 – Aug 2014)*
- **Modelled the HIV diagnostics** - CD4, viral load and EID (early infant diagnosis) - global markets scenarios including size, projected growth, and segmentation. These models were used to identify market opportunities and negotiate pricing.
- **Negotiated lowered pricing** with leading diagnostics manufacturers for viral load testing in sub-Saharan Africa that lead to a deal that will save $150 mil over 5 years.
- **Assisted 7 countries in sub-Saharan Africa** with rational selection and deployment of new diagnostic products. Helped the ministries of health understand the gaps in country’s diagnostic coverage and develop optimal product deployment strategies.
### Access to medicines/UNITAID Analyst (Clinton Health Access Initiative)
*Kampala, Uganda (Jul 2011 – Aug 2012)*
- **Increased uptake of a new drug, Atazanavir/Ritonavir (ATV/r)** by 14% in one quarter by driving policy change at Ministry of Health and assisting major implementation partners with the transition.
- **Analysed consumption and issues data to forecast demand** for paediatric and second line anti-retroviral medications (ARVs) in country to determine national need for ARVs.
- On behalf of the Ministry of Health, **performed a quantification of the national need** for all critical lab reagents and consumables to inform national diagnostic budget.
### Manager – Technology Consulting (Accenture Pty. Ltd)
*Melbourne, Australia (Mar 2005 – Jul 2011)*
- **Analysed business and technical barriers, and designed solutions** for numerous organizations in public and private sectors including Commonwealth Bank of Australia, Telstra and the Australia Tax Office.
- **Managed large budgets and lead teams** up to 22 people to deliver on tight deadlines.
## Publications and Presentations
---
- Redesigning India's Urea Policy, Harvard Kennedy School, MPA/ID Final Capstone Paper
- Economic survey of India, Ministry of Finance, February 2016
- An overview of the antiretroviral market, Current Opinion in HIV/AIDS, November 2013 - Volume 8 - Issue 6
- HIV Testing – Market Analysis, African Society for Laboratory Medicine, Cape Town, 2012
- Adaptive Clustering for Network Intrusion Detection, PAKDD 2004: 255-259
<file_sep>/Gemfile
source 'https://rubygems.org'
gem "minima"
gem "jekyll-paginate"
gem 'disqus-for-jekyll'
gem 'jekyll-feed'
gem 'texture'
gem "kramdown", ">= 2.3.0"
gem "kramdown-parser-gfm"
gem "jekyll", ">= 3.7.4"
<file_sep>/_posts/2018-10-17-cross-country-convergence.md
---
layout: "post"
title: "You'll be blown a way by this weird trick millennials discovered to do convergence regressions."
date: "2018-10-17 00:07"
comments: true
use_math: true
---
Hat tip to [@mkessler_DC](https://twitter.com/mkessler_DC/status/1051959149494448128) for the clickbaitey title.
So economic convergence is back. <NAME>, <NAME>, and <NAME> (PSS) recently wrote a [blog post](https://www.cgdev.org/blog/everything-you-know-about-cross-country-convergence-now-wrong) to show that
> while unconditional convergence was singularly absent in the past, there has been unconditional convergence, beginning (weakly) around 1990 and emphatically for the last two decades.
They do a very straightforward analysis; they regress real per capita GDP growth rate on the log of per capita GDP for various periods and show that the coefficient is indeed reducing. They also made their code available, which is so awesome that they can be forgiven for it being in STATA. Instead of doing separate regressions for each time period, I redo their analysis as a rolling regression where we allows the coefficients to change over time.
This post borrows heavily from <NAME>i's [two](https://docs.pymc.io/notebooks/GLM-rolling-regression.html) [posts](https://twiecki.github.io/blog/2017/03/14/random-walk-deep-net/) on Gaussian random walks.
As per usual, you can find the [notebook on github](https://github.com/sidravi1/Blog/tree/master/nbs/growth_analysis).
## Why rolling regression?
Key figure in the chart is this:

So for each time period between $y$ and $y_0$, we have different coefficients as follows:
$$
\Delta GDPPC_{c, y, y_0} = \alpha_{y, y_0} + \beta_{y, y_0} * log(GDPPC_{c, y0})
$$
Going forward we will drop $y_0$ from the notation for clarity.
This implicit assumption here is that $\beta_{y}$ is independent from $\beta_{y + 1}$. But we know that's not entirely true. If you gave me $\beta_{y}$, I'd expect $\beta_{y + 1}$ to be pretty similar and deviate only slightly.
We can make this explicit and put a gaussian random-walk prior on beta.
$$
\begin{align}
\beta_{y + 1} \sim \mathcal{N}(\beta_{y}, \sigma^2) \tag{1}
\end{align}
$$
$\sigma^2$ is how quickly $\beta$ changes. It's just a hyper-parameter that we'll put a weak prior on. We do the same thing for $\alpha$ as well.
## Pre-processing
In the notebook, I tried replicate PSS's STATA code in python as closely as possible. It's not perfect. And looks like I screwed up the WDI dataset manipulations so I use only Penn World Table (PWT) and Maddison Tables (MT) in this post. Check out the notebook if you want to fix it and get it working for WDI.
Here's what 1985 looked like:
<div id="vis_1985"></div>
<script type="text/javascript">
var spec = "{{"/assets/2018_10_17_growth_1985.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis_1985', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
And here's what 2005 looked like:
<div id="vis_2005"></div>
<script type="text/javascript">
var spec = "{{"/assets/2018_10_17_growth_2005.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis_2005', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
The trend might not be so obvious in 1985 but it does appear to be negative in 2005, especially if you ignore those really tiny countries. Let's see what the random walk model says.
## Setup in pymc3
Here's the model in pymc3 for MT. The code for PWT is pretty identical.
{% highlight python %}
with pm.Model() as model_mad:
sig_alpha = pm.Exponential('sig_alpha', 50)
sig_beta = pm.Exponential('sig_beta', 50)
alpha = pm.GaussianRandomWalk('alpha', sd =sig_alpha, shape=nyears)
beta = pm.GaussianRandomWalk('beta', sd =sig_beta, shape=nyears)
pred_growth = alpha[year_idx] + beta[year_idx] * inital
sd = pm.HalfNormal('sd', sd=1.0, shape = nyears)
likelihood = pm.Normal('outcome',
mu=pred_growth,
sd=sd[year_idx],
observed=outcome)
{% endhighlight %}
- `nyears` is the number of years. So there are `nyears` alphas and betas and they are *linked* as per (1).
- `year_idx` indexed to right coefficients based on $y$.
- As in PSS, `outcome` is $\Delta GDPPC_{c, y, y_0}$ and `intial` is $log(GDPPC_{c, y0})$.
and let's run it:
{% highlight python %}
trace_mad = pm.sample(tune=1000, model=model_mad, samples = 300)
{% endhighlight %}
## Results
Let's see how alpha and beta change over the years.

So, PSS's conclusion is borne out here as well. We see that $beta$ used to be mildly positive and gradually shifted to negative in recent years. Our bounds look a little tighter and maybe the shape is slightly different. You can check out [the notebook](https://github.com/sidravi1/Blog/tree/master/nbs/growth_analysis) here. I threw this together pretty quickly so I might be screwed up the data setup. Let me know if you find any errors in my code.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2020-01-23-jackknife-and-the-bootstrap.md
---
layout: "post"
title: "Jackknife, Non-parametric and Parametric Bootstrap"
date: "2020-01-23 22:14"
comments: true
use_math: true
---
In frequentist statistics, you want to know how seriously you should take your estimates. That's easy if you're doing something straight forward like averaging:
$$
\hat{se} = \left[ \sum_{i = 1}^{n} (x_i - x)^2 / (n(n-1))\right]
$$
or OLS<sup>[1](#footnote1)</sup>:
$$
\hat{se} = \sqrt{\hat{\sigma}^2 (X'X)^{-1}}\\
$$
If you want to get any fancier, chances are you don't have a nice formula for it.
Say we observe an iid sample $\boldsymbol{x} = (x_1, x_2, ... , x_n)'$ from some probability distribution $F$:
$$
x_i \stackrel{iid}{\sim} F \,\,\,\, \text{for } i = 1, 2, ..., n
$$
And we want to calculate some real valued statistic $\hat{\theta}$ that we get by applying some algorithm $s(\cdot)$ to $\boldsymbol{x}$,
$$
\hat{\theta} = s(\boldsymbol{x})
$$
and want to get a standard error for our $\hat{\theta}$. The jackknife and the bootstrap are two extremely useful techniques that can help. In the post, I'll go through these and the parametric version of the bootstrap using a bunch of examples.
Most of this post is built around Chapter 10 of Computer Age Statistic Inference by Efron and Hastie. You can get the book freely [online here](https://web.stanford.edu/~hastie/CASI_files/PDF/casi.pdf). You can get the notebook for all the [code here](https://github.com/sidravi1/CASI_Examples/blob/master/nbs/Ch10_jackknife_bootstrap.ipynb).
## The Jackknife
Let $\boldsymbol{x}_{(i)}$ be the sample with $i^{th}$ element $x_i$ removed. Now your jacknife estimate of the standard error is:
$$
\begin{equation}
\hat{se}_{jack} = \left[ \frac{n -1}{n} \sum^n_{i = 1}\left(\hat{\theta}_{(i)} - \hat{\theta}_{(\cdot)}\right)^2\right]^{1/2}\text{ (1)}\\
\text{with }\hat{\theta}_{(\cdot)} = \sum^{n}_{i = 1} \hat{\theta}_{(i)} / n
\end{equation}
$$
Let's summarise what we are doing here. If we have $n$ samples,
1. We calculate the statistic, $\hat{\theta}$, $n$ times, with one of the sample values left out each time.
2. We take the average of these $n$ statistics and get ($\hat{\theta}_{(\cdot)}$)
3. Plug it in to (1) and you're done.
### The good stuff
It's nonparamteric - we made no assumptions about the underlying distribution $F$.
It's automatic - If you have $s(\cdot)$, you can get your $\hat{se}_{jack}$.
### The bad stuff
Assumes smooth behaviour across samples: Samples that are different by one $x_i$ should not have vasty different estimates. Check out the book (pg. 157) for similarities with Taylor series methods, and therefore, it's dependence on local derivatives. We'll see an example with *lowess* curves where this is violated.
## The Nonparametric Bootstrap
The ideal way to get standard errors would be to get new samples from $F$ and compute your statistic. But $F$ is usually not known. Bootstrap uses the estimate $\hat{F}$ instead of $F$.
Algorithm is quite simple. You take a *bootstrap sample*:
$$
\boldsymbol{x}^* = (x_1^*,x_2^*,...,x_n^* )
$$
where $x_i^* $ is drawn randomly with equal probability and with replacement from $(x_1, x_2,...,x_n)$.
Take this bootstrap sample, $\boldsymbol{x}^* $ and plug it into your estimator and get an estimate:
$$
\hat{\theta}^* = s(\boldsymbol{x}^* )
$$
Do this $B$ times where $B$ is some large number to get an estimate for each bootstrap sample.
$$
\hat{\theta}^{* b} = s(\boldsymbol{x}^{* b} )\,\,\,\,\text{for }b = 1, 2, ..., B
$$
Calculate the empirical standard deviation of the $\hat{\theta}^{* b}$ values:
$$
\hat{se}_{boot} = \left[ \sum^B_{b = 1}\left(\hat{\theta}^{* b} - \hat{\theta}^{* \cdot} \right)^2 \Big/ (B - 1)\right]^{1/2}\text{ (1)}\\
\text{with }\hat{\theta}^{* \cdot} = \sum^{B}_{b = 1} \hat{\theta}^{* b} \big/ B
$$
To summarise:
1. Get $B$ samples with replacement of size $n$ from $(x_1, x_2,...,x_n)$.
2. Calculate your statistic, $\hat{\theta}$, for each of these samples.
3. Take the empirical standard deviation of all these $\hat{\theta}$s to get your standard error.
### The good stuff
Like the jackknife, it's completely automatic.
It's more dependable than jackknife for non-smooth statistics since it doesn't depend on local derivatives.
### The bad stuff
Computationally, it can be quite expensive.
### Example 1: standard errors for `lowess`
I'm going to skip the code for the jackknife and bootstrap here since it's fairly straightforward (you can checkout the notebook if you like) and skip to the results:

Note that they are pretty similar most of the way but the jackknife estimates get funky around 25. In Efron and Hastie's words: *"local derivatives greatly overstate the sensitivity of the `lowess` curve to global changes in the sample $\boldsymbol{x}$"*
### Example 2: The "eigenratio"
We have a table of results of 22 students taking 5 tests. The pairwise correlations of these scores is:

We want to the calculate the standard errors for the "eigenratio" statistic for this table:
$$
\hat{\theta} = \text{largest eigenvalue / sum eigenvalues}
$$
which says how closely the five scores can be predicted by a single linear combination of the columns. The plot below shows the bootstrap results:

Few interesting things to note here. The jackknife estimate of standard error is larger than the bootstrap's. The distribution isn't normal. If you decided to get a confidence interval using +/- 1.96 $\hat{se}$ for a 95% coverage, you'd be quite biased.
## The Parametric Bootstrap
I like parametric methods. Often there are distributional assumptions you are willing to make that help your model along substantially. If I asked you what is the effect on sales as if you increase the discount, you'd be comfortable saying it's some monotonically increasing function. That's information that you can't include in your random forest model (easily).
The same applies here. If you are comfortable assuming your samples come from some distribution, you can just sample from that distribution to get your bootstrap samples.
For example, if your sample $\boldsymbol{x} = (x_1, x_2, ..., x_n)$ comes from a normal distribution:
$$
x_i \stackrel{iid}{\sim} \mathcal{N}(\mu, 1), i = 1,2,...,n
$$
then $\hat{\mu} = \bar{x}$, and a parametric bootstrap sample is $\boldsymbol{x}^* = (x_1^* , x_2^* , ..., x_n^* )$. The rest of it proceeds as normal.
### Example: Glomerular filtration rates (gfr)
We have binned gfr data from 211 kidney patients. Say we are comfortable claiming that this comes from a Poisson distribution and have fitted a parametric model. The figure below shows models fitted with different order of polynomials.

How accurate are these curves? We can use parametric bootstrapping to get their standard errors.
First, let's create the higher order variables.
{% highlight python %}
deg_freedom = 7
for d in range(2, deg_freedom+1):
df["xs"+str(d)] = xs**d
{% endhighlight %}
Now let's do some bootstrapping for each of the fits:
{% highlight python %}
endog = df.y.values # the bin counts
exog_cols = ['xs', 'intercept'] # the bin centre value is xs
models = []
lnk = sm.families.links
all_fitted_vals = {}
for d in range(2, deg_freedom + 1):
exog_cols.append('xs'+str(d))
# fit the model
model = sm.GLM(endog=df.y.values, exog=df[exog_cols].values,
family=sm.families.Poisson()).fit()
# Generate samples from fitted model
samples = np.random.poisson(model.fittedvalues,
size=(200, len(df)))
# For each sample, run the 'statistic' i.e. the fit again
fitted_vals = []
for sample in samples:
sample_model = sm.GLM(endog=sample, exog=df[exog_cols].values, family=sm.families.Poisson()).fit()
fitted_vals.append(sample_model.fittedvalues)
# Take the std of the estimate
all_fitted_vals[d] = np.array(fitted_vals).std(axis=0, ddof=1)
{% endhighlight %}
Let's see what +/- 1.96$\hat{se}$ looks like<sup>[2](#footnote2)</sup>.

What if we had done it non-paramterically?

Increasing the degrees of freedom (df) of the fit increases the standard error. As df approaches 32, the number of bins, the standard errors approach the non-parametric one. So again, "nonparametric" just means "very high parameterised".
### Example: The "eigenratio": take 2
We can apply the non-parametric method to the eigenratio problem as well. The distributional assumption here is that the sample comes from a 5-dimensional multivariate normal:
$$
x_i \sim \mathcal{N}_5(\mu, \Sigma )\,\, \text{for } i = 1, 2, ... , n
$$
where $n$ is the number of students. We can draw a bootstrap sample:
$$
x_i^* \sim \mathcal{N}_5(\bar{x}, \hat{\Sigma} )
$$
where $\bar{x}$ and $\hat{\Sigma}$ are MLEs of the mean and covariance of the data.
The code is pretty straightforward:
{% highlight python %}
def eigenratio2(arr):
corr_mat = np.corrcoef(arr, rowvar=False)
eig_vals, _ = eig(corr_mat)
return np.max(eig_vals)/np.sum(eig_vals)
# MLE estimates
mean = data.mean().values
covar = np.cov(data, rowvar=False)
# draw bootstrap samples
samples = np.random.multivariate_normal(mean, covar, size=(2000, len(data)))
# get estimate for each sample
eigr_ls = []
for sample in tqdm(samples):
eigr_ls.append(eigenratio2(sample))
{% endhighlight %}
As before, we get a smaller estimate for the SE than if used the non-parametric method.

## Influence Functions, Robust Estimation, and the Bootstrap
Check out this data

It has a little bit of a heavy tail. Would it be more efficient to estimate the center of the distribution by trimming the extreme values and then taking a mean? When you have a heavy tailed distribution, those tail have a large influence on your mean. Let's formalise this a bit.
Say you have a sample $\boldsymbol{x} = (x_1, x_2, ... , x_n)$ from some unknown distribution $F$. The influence function (IF) of some statistic evaluated at a point $x$ in $\mathcal{X}$, is the differential effect of modifying F by putting more probability on $x$.
$$
\text{IF}(x) = \lim_{\epsilon \rightarrow 0}\frac{T((1 - \epsilon)F + \epsilon\delta_x) - T(F)}{\epsilon}
$$
$\delta_x$ is puts probability 1 on $x$ (and zero everywhere else). You'll note that this is basically taking the gradient of your statistic over $\epsilon$. Let's do this for the mean:
$$
\begin{aligned}
T((1-\epsilon)F + \epsilon\delta_x) &= \mathbb{E}((1-\epsilon)F + \epsilon \delta_x)\\
&= \mathbb{E}((1 - \epsilon)F) + \mathbb{E}(\epsilon \delta_x)\\
&= (1 - \epsilon)\mathbb{E}(F) + \epsilon x\\
\\
T(F) &= \mathbb{E}(F)
\end{aligned}
$$
Plugging these into our formula for $\text{IF}(x)$:
$$
\begin{aligned}
\text{IF}(x) &= \lim_{\epsilon \rightarrow 0}\frac{((1 - \epsilon)\mathbb{E}(F) + \epsilon x) - \mathbb{E}(F)}{\epsilon}\\
&= \lim_{\epsilon \rightarrow 0}\frac{((1 - \epsilon)\mathbb{E}(F) + \epsilon x) - \mathbb{E}(F)}{\epsilon}\\
&= x - \mathbb{E}(x)
\end{aligned}
$$
The last line looks like hocus-pocus but it's basically taking the derivative with respect to $\epsilon$. So the farther away $x$ gets from the mean, the more influence it has. This should agree with your intuition about means. So if $F$ is heavy tailed, your estimate would be very unstable.
These "unbounded" IFs make $\bar{x}$ unstable. One thing we can do is to calculate the *trimmed* mean. We throw away the portion of $F$ that is above a certain percentile. What does bootstrap tell us about the standard error if we do this?
Here's are functions to trim and get the IF:
{% highlight python %}
def get_IF(data_sr, alpha):
""" Get Influence function when trimmed at alpha """
low_α = np.percentile(data_sr, alpha*100,
interpolation = 'lower')
high_α = np.percentile(data_sr, (1-alpha) * 100,
interpolation = 'higher')
mask_low = (data_sr < low_α)
mask_high = (data_sr > high_α)
vals = data_sr.copy()
vals[mask_low] = low_α
vals[mask_high] = high_α
return (vals - vals.mean()) / (1 - 2*alpha)
def get_trimmed(data_sr, alpha):
""" Get the trimmed data """
low_α = np.percentile(data_sr, alpha*100,
interpolation = 'higher')
high_α = np.percentile(data_sr, (1-alpha) * 100,
interpolation = 'lower')
mask02_low = (data_sr < low_α)
mask02_high = (data_sr > high_α)
return data_sr[~(mask02_low | mask02_high)]
{% endhighlight %}
where `alpha` is the percentage at the ends that we want to trim away. For different levels of `alpha` we can get a mean and a bootstrapped sd:
{% highlight python %}
mean_tr = []
mean_if = []
res = []
for α in [0, 0.1, 0.2, 0.3, 0.4, 0.5]:
mean_tr = []
mean_if = []
for i in range(1000):
sample= np.random.choice(data_all, size=len(data_all))
trimmed_sample = get_trimmed(sample, α)
mean_tr.append(trimmed_sample.mean())
N = len(trimmed_sample)
mean_if.append(get_IF(sample, α).std()/np.sqrt(len(data_all)))
res.append({"Trim":α,
"Trimmed Mean": np.mean(mean_tr),
"Bootstrap sd":np.std(mean_tr),
"IFse":np.mean(mean_if)})
{% endhighlight %}
Let's look at the results:

The bootstrap standard error for our sample mean is the smallest with an alpha of 0.2. We might be better off using a trim of 0.2 than no trim.
## Conclusions
Do a bootstrap. Go parametric if you can. Use bootstrap to figure out the more efficient estimator.
Check out the notebook for all the [code here](https://github.com/sidravi1/CASI_Examples/blob/master/nbs/Ch10_jackknife_bootstrap.ipynb).
## Footnotes
<a name="footnote1"><sup>1</sup></a> Yes - i know, only for homoscedastic errors.
<a name="footnote2"><sup>2</sup></a> if you're looking for confidence intervals, this is not a great way to do it. It assumes normality for each of the estimates which is obviously not true -- support is only positive numbers. Bias corrected confidence intervals are explored in Chapter 11 of CASI.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-12-02-athey-s-matrix-completion-methods.md
---
layout: "post"
title: "Athey's Matrix Completion Methods"
date: "2018-12-02 08:28"
comments: true
use_math: true
---
If you want to measure the causal effect of a treatment what you need is a counterfactual. What would have happened to the units if they had *not* got the treatment? Unless your unit is Gwyneth Paltrow in Sliding Doors, you only observe one state of the world. So the key to causal inference is to reconstruct the *untreated* state of the world. Athey et al. in [their paper](https://arxiv.org/pdf/1710.10251.pdf) show how matrix completion can be used to estimate this unobserved counterfactual world. You can treat the unobserved (untreated) states of the treated units as missing and use a penalized SVD to reconstruct these from the rest of the dataset. If you are familiar with the econometric literature on synthetic controls, fixed effects, or unconfoundedness you should definitely read the paper; it shows these as special cases of matrix completion with the missing data of a specific form. Actually, you should read the paper anyway. Most of it is quite approachable and it's very insightful.
Also, check out [this great twitter thread](https://twitter.com/causalinf/status/1067126856070168579) by <NAME> and [Cyrus Samii's notes](http://cyrussamii.com/?p=2712)] on it.
# Data setup
Say you have some panel data with $N$ units and $T$ time periods. At some time period $t_{0,n}$ (which can be different for each unit), some of the units get the treatment. So from $(t_{0,n}, T)$ you don't really see the untreated state of the world. It is "missing". We'll use the same dataset, the Abadie 2010 California smoking data, that the authors use in the paper for the demo:
{% highlight python %}
import numpy as np
import pandas as pd
import scipy as sp
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqdm
BASE_URL = "https://raw.githubusercontent.com/susanathey/MCPanel/master/tests/examples_from_paper/california/"
Y = pd.read_csv(BASE_URL + "smok_outcome.csv", header=None).values.T
Y = Y[1:,:] # drop the first row since it is treated and the untreated values for that unit are not available.
N, T = Y.shape
{% endhighlight %}
Let's allow each unit to have a different $t_0$ with the minimum being 16 and pick 15 random units to be treated.
{% highlight python %}
t0 = 16
N_treat_idx = np.random.choice(np.arange(N), size = 15, replace=False)
T_treat_idx = np.random.choice(np.arange(t0, T), size = 15, replace=False)
treat_mat = np.ones_like(Y)
for n, t in zip(N_treat_idx, T_treat_idx):
treat_mat[n, t:] = 0
{% endhighlight %}
What we will observe is `Y_obs`:
{% highlight python %}
Y_obs = Y * treat_mat
{% endhighlight %}
and we'll try and recreate `Y`. The figure below shows what these datasets look like. The white bits on the right are the "missing" entries in the matrix.

# The algorithm
Our job is to reconstruct a matrix $L$ such that:
$$
\mathbf{Y} = \mathbf{L^* } + \epsilon
$$
Before we get to the estimator for $L^* $, let's define a few support functions:
$$
\text{shrink}_{\lambda}(\mathbf{A}) = \mathbf{S \tilde{\Sigma} R}^{\text{T}}
$$
where $\mathbf{\tilde{\Sigma}}$ is equal to $\mathbf{\Sigma}$ with the i-th singular value $\sigma_i(\mathbf{A})$ replaced $\text{max}(\sigma_i(\mathbf{A}) - \lambda, 0)$. So you are doing a SVD and shrinking the eigenvalues towards zero. Here's the python code for it:
{% highlight python %}
def shrink_lambda(A, lambd):
S,Σ,R = np.linalg.svd(A, full_matrices=False)
#print(Σ)
Σ = Σ - lambd
Σ[Σ < 0] = 0
return S @ np.diag(Σ) @ R
{% endhighlight %}
And then
$$
\begin{aligned}
\mathbf{P_{\mathscr{O}}(A)} =
\begin{cases}
A_{it}& \text{if } (i,t) \in \mathscr{O}\\
0 & \text{if } (i,t) \notin \mathscr{O}
\end{cases}, &&
\mathbf{P^{\perp}_{\mathscr{O}}(A)} =
\begin{cases}
0 & \text{if } (i,t) \in \mathscr{O}\\
A_{it}& \text{if } (i,t) \notin \mathscr{O}
\end{cases}
\end{aligned}
$$
In python:
{% highlight python %}
def getPO(A, O):
A_out = np.zeros_like(A)
A_out[tuple(O.T)] = A[tuple(O.T)]
return A_out
def getPOinv(A, O):
A_out = A.copy()
A_out[tuple(O.T)] = 0
return A_out
{% endhighlight %}
And now for the main algorithm. The paper shows the general form of the estimator but here we will implement the iterative (probably slower) version. It's quite beautiful in its simplicity. For $k = 1,2,...,$ define:
$$
\mathbf{L}_{k+1}(\lambda, \mathscr{O}) = \text{shrink}_{\frac{\lambda|\mathscr{O}|}{2}} \{ \mathbf{P_{\mathscr{O}}(Y)} + \mathbf{P^{\perp}_{\mathscr{O}}(L_{\lambda})} \}
$$
and we initialize it as
$$
\mathbf{L}_{1}(\lambda, \mathscr{O}) = \mathbf{P_{\mathscr{O}}(A)}
$$
Note that $\mathscr{O}$ is the set of coordinates of the matrix where the data is not missing i.e. the units were not treated. \\
\\
We run this until $\mathbf{L}$ converges. Here's the python code:
{% highlight python %}
def run_MCNNM(Y_obs, O, lambd = 10, threshold = 0.01, print_every= 200, max_iters = 20000):
L_prev = getPOinv(Y_obs, O)
change = 1000
iters = 0
while (change > threshold) and (iters < max_iters):
PO = getPO(Y_obs, O)
PO_inv = getPOinv(L_prev, O)
L_star = PO + PO_inv
L_new = shrink_lambda(L_star, lambd)
change = np.linalg.norm((L_prev - L_new))
loss = ((Y_obs - L_new) ** 2).sum() / Y.sum()
real_loss = ((Y - L_new) ** 2).sum() / Y.sum()
L_prev = L_new
iters += 1
if (print_every is not None) and ((k % print_every) == 0):
print(loss, change, real_loss)
return L_new
{% endhighlight %}
# Cross-validation
We still need to figure what $\lambda$ needs to be so we cross-validate. The implementation below is not perfect since it doesn't simulate the full dataset exactly. I'm picking a random subset of coordinates to take out as the test set and training using the rest. I'm not removing everything after a some time $t$ for each unit as I really should. Check out the note in the paper on cross validation for $\lambda$. But the implementation below should give you a good sense (and a good start if you want to improve it) of how to do it. While you're at it, you may want to use dask distributed to parallelize it.
{% highlight python %}
from sklearn.model_selection import KFold
def get_CV_score(Y_obs, O, lambd, n_folds = 4, verbose=False):
kfold = KFold(n_splits=n_folds, shuffle=True)
mse = 0
for i, (Otr_idx, Otst_idx) in enumerate(kfold.split(O)):
Otr = O[Otr_idx]
Otst = O[Otst_idx]
if verbose: print(".", end="")
L = run_MCNNM(Y_obs, Otr, lambd, threshold = 1e-10, print_every= 15000, max_iters = 20000)
mse += ((Y_obs[tuple(Otst.T)] - L[tuple(Otst.T)]) ** 2).sum()
return mse / n_folds
def do_CV(Y_obs, O, lambdas = [5, 10, 20, 40], n_tries = 10, verbose=False):
score = {}
for t in tqdm(range(n_tries)):
run_score = {}
for l in tqdm(lambdas, leave=False):
if verbose: print(f"lambda {l}:", end="")
run_score[l] = get_CV_score(Y_obs, O, l, n_folds = 4, verbose=verbose)
if verbose: print(f" : {run_score[l]}")
score[t] = run_score
return score
{% endhighlight %}
Let's run the cross-validation and check out the results:
{% highlight python %}
cv_score = do_CV(Y_obs, O, lambdas=[5, 7, 9, 10, 11, 13, 15, 20], n_tries = 20)
cv_score_df = pd.DataFrame(cv_score)
plt.figure(figsize=(8, 5))
ax = sns.heatmap(cv_score_df, linewidths=1, cbar=False)
ax.set_xticks([]);
ax.set_xlabel("Iteration")
ax.set_ylabel("λ")
plt.savefig("../../sidravi1.github.io/assets/2018_12_02_cross_val.png")
cv_score_df.mean(axis=1)
{% endhighlight %}
Here are the results (darker is smaller MSE) and it looks like 9 is the optimal lambda.

# Final run and results
Using 9 as our lambda, let's run it once more and check out the results.
{% highlight python %}
lambd = 9
threshold = 1e-10
O = np.argwhere(treat_mat)
L = run_MCNNM(Y_obs, O, lambd, threshold, print_every= 1000, max_iters = 20000)
# plot the results
vmin = Y.min()
vmax = Y.max()
f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))
sns.heatmap(Y, linewidths=0, vmax=vmax, vmin=vmin, ax = ax1, cmap = 'mako_r', cbar=False)
ax1.set_title("Y: Original Matrix")
sns.heatmap(Y_obs, linewidths=0, vmax=vmax, vmin=vmin, ax = ax2, cmap = 'mako_r', cbar=False)
ax2.set_title("Y_obs: Observed Matrix")
ax2.set_yticks([])
sns.heatmap(L, linewidths=0, vmax=vmax, vmin=vmin, ax = ax3, cmap = 'mako_r', cbar=False)
ax3.set_title("L: Completed Matrix")
ax3.set_yticks([])
plt.tight_layout()
plt.savefig("../../sidravi1.github.io/assets/2018_12_02_athey_reconstructed.png")
{% endhighlight %}

Not bad at all! Looks like we lost some resolution there but we only had 38 records so pretty decent. I bet with a larger dataset with more controls, it would do even better.
# Next steps
We don't include any covariate here but the paper shows how you can do that. Athey and team has also made their code and test data available online which deserves a round of applause. It is still such a rare thing in economics. You can go check out their code [here](https://github.com/susanathey/MCPanel). It also includes a R package which will be a hell of a lot faster than my quick and dirty code.
The notebook with all my code can [be found here](https://github.com/sidravi1/Blog/blob/master/nbs/Athey_matrix_completion.ipynb). Happy matrix completing!
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2019-03-27-back-to-basic-with-david-mackay-ii.md
---
layout: "post"
title: "Back to Basics with David Mackay #2: Fancy k-means"
date: "2019-03-27 10:24"
comments: true
use_math: true
---
Following <NAME>ackay's book along with his videos online has been a real joy. In [lecture 11](http://videolectures.net/mackay_course_11/), as an example of an inference problem, he goes over many variations of the k-means algorithm. Let's check these out.
## The datasets
All the sample data used in his lectures and the book can be found on his [website here](http://www.inference.org.uk/itprnn/code/kmeans/). It also has octave code for the algorithms but we'll implement them again in python.
## The simple k-means
This is now a classic data science interview question and you probably know how to do this in your sleep. Here's my simple implementation of it. You can make this a lot more efficient by using numpy's vectorized functions but I don't bother with it here.
{% highlight python %}
def assigment_step(centroids, xs):
assignments = []
for x in xs:
best_centroid = 0
best_distance = np.inf
for c_id, c in enumerate(centroids):
x_to_c = sp.spatial.distance.euclidean(x, c)
if x_to_c < best_distance:
best_centroid = c_id
best_distance = x_to_c
assignments.append(best_centroid)
return np.array(assignments)
def update_step(xs, assignments, n):
all_centroid = []
for i in range(n):
i_idx = np.argwhere(assignments == i).squeeze()
assigned_xs = xs[i_idx].reshape(-1, 2)
centroid = np.sum(assigned_xs, axis = 0) / assigned_xs.reshape(-1, 2).shape[0]
all_centroid.append(centroid)
return np.row_stack(all_centroid)
{% endhighlight %}
and here's the code that runs the simulation which doesn't change much between the different versions so we'll skip it going forward.
{% highlight python %}
def run_simulation(xs, n_clusters):
# We don't want to intialize two clusters to the same point
unique_xs = np.unique(xs, axis=0)
# initialize clusters
centroids_idx = np.random.choice(np.arange(unique_xs.shape[0]), size=n_clusters, replace=False)
new_centroids = unique_xs[centroids_idx]
prev_centroids = np.zeros_like(new_centroids)
assignments = assigment_step(new_centroids, xs)
iteration = 0
while not np.isclose(new_centroids, prev_centroids, atol=1e-10, rtol=1e-8).all():
prev_centroids = new_centroids
new_centroids = update_step(xs, assignments, n_clusters)
assignments = assigment_step(new_centroids, xs)
iteration += 1
assignments2 = np.invert(assignments, dtype=np.int8) + 2
assignments = np.column_stack([assignments2, assignments])
return assignments, new_centroids, []
{% endhighlight %}
We're going to look at the 7 different datasets and see how this code does in picking up the clusters.

It does a fine job with the first ones but struggles with the rest. One problem is that we dichotomize the allocation for each point - it either belongs to cluster 1 or cluster 2. Some points may be ambiguous and we want to take that into account. Let's fix that in the next section.
## Simple k-means with soft-thresholding
Now each cluster has a "responsibility" for each point. The total responsibility for a point adds up to 1. We do a softmax instead of the hard threshold in the assignment step. And when updating the cluster center, we weight the points based on this responsibility.
{% highlight python %}
def assignment_step_soft(centroids, xs, beta):
assignments = []
distance_to_centroids = np.zeros((xs.shape[0], centroids.shape[0]))
for x_id, x in enumerate(xs):
for c_id, c in enumerate(centroids):
distance_to_centroids[x_id, c_id] = -beta * sp.spatial.distance.euclidean(x, c)
return softmax(distance_to_centroids, axis=1)
def update_step_soft(xs, assignments, n):
all_centroid = []
for i in range(n):
centroid_resps = assignments[:, i]
centroid = centroid_resps @ xs / centroid_resps.sum()
all_centroid.append(centroid)
return np.row_stack(all_centroid)
{% endhighlight %}
Note the new parameter `beta` that we now need to set. The higher the `beta`, the more hard the thresholding. In its limit, it approaches the basic k-means algorithm.
Here are the results with `beta` set to 2:

Do we do any better? Well, not really. Though we are able to identify the ones we are uncertain about - the circles in light-blue - we now have an additional parameter, `beta`, to set. The other limitation of the algorithm is that each cluster is assumed to be the same size. We see from the data that this is not always true. Let's allow for variable sizes in the next section.
## K-means with variable cluster sizes
Now we are going to think of each cluster as a gaussian. They can be of varying sizes i.e. different variances. So the distance of each point to the gaussian center is the likelihood of observing that point given the gaussian parameters weighted by the cluster's importance (`pi`). And what is importance? The total amount of relative responsibility of the cluster across all the points.
{% highlight python %}
def gaussian_dist(c, sigma, x, pi):
responsibility = pi * sp.stats.multivariate_normal(mean=c, cov=np.array([[sigma**2, 0],[0, sigma**2]])).pdf(x)
return responsibility
{% endhighlight %}
So we are still keeping the idea of responsibility around but *look ma, no beta!*. Our *update* and *assignment* steps now need to keep track of importance and also update the variance or size for each of the clusters.
{% highlight python %}
def assignment_step_softv2(centroids, xs, sigmas, pis):
assignments = []
distance_to_centroids = np.zeros((xs.shape[0], centroids.shape[0]))
for x_id, x in enumerate(xs):
for c_id, c in enumerate(centroids):
sigma = sigmas[c_id]
pi = pis[c_id]
distance_to_centroids[x_id, c_id] = gaussian_dist(c, sigma, x, pi)
normed_distances = distance_to_centroids / distance_to_centroids.sum(axis=1).reshape(-1, 1)
normed_distances[np.isnan(normed_distances)] = 0
return normed_distances
def update_step_softv2(xs, assignments, n, curr_sigmas, curr_centroids):
all_centroid = []
all_sigma = []
for i in range(n):
centroid_resps = assignments[:, i]
curr_sigma = curr_sigmas[i]
curr_centroid = curr_centroids[i,:]
total_resp = centroid_resps.sum()
if total_resp == 0:
all_centroid.append(curr_centroid)
all_sigma.append(curr_sigma)
print("no resp for cluster %s" % str(i))
else:
# m
centroid = centroid_resps @ xs / total_resp
# sigma
sigma = (centroid_resps @ ((xs - centroid) ** 2).sum(axis=1)) / (xs.shape[1] * total_resp)
if sigma == 0:
sigma = 0.1
all_centroid.append(centroid)
all_sigma.append(np.sqrt(sigma))
# pi
pi = assignments.sum(axis=0) / assignments.sum()
return np.row_stack(all_centroid), np.array(all_sigma), pi
{% endhighlight %}
The update step suddenly looks quite long. This is because, we need to handle the corner cases where a cluster has no importance or has just one point assigned to it, reducing the variance to almost zero. The algorithm falls over during those scenarios. We don't change the cluster details if it has no importance and if `sigma` shrinks to zero, we set it to something small - 0.1 in this case. You may have more elegant ways of handling this.
So what did we get for all this hard work?

Good news is that all the ambiguity in the second and fourth dataset is now gone - we have a small cluster and a large cluster. Bad news is that there is a little more ambiguity about the some of the peripheral points in the first dataset since the blue cluster is now larger and more important. It still does a shitty job of the circles and the last dataset with skinny clusters.
We can't do much about the circles unless we change coordinate systems / do some transformations and I'll leave that out for now (another reason to use HDBSCAN or Spectral Clustering if this is a real life problem). But we can do something about the skinny clusters. So far we have kept the cluster round - i.e. the variance in the two dimensions are constrained to be equal. Let's relax that in the next section.
## K-means with adaptive covariance
I'm adding a try/except since the covariance matrix becomes invalid under some scenarios (the same ones as above). In these cases, we just pick a tiny round cluster.
{% highlight python %}
def gaussian_dist_v4(c, cov, x, pi):
try:
responsibility = pi * sp.stats.multivariate_normal(mean=c, cov=cov).pdf(x)
except np.linalg.LinAlgError as err:
responsibility = pi * sp.stats.multivariate_normal(mean=c, cov=np.array([[0.01, 0],[0, 0.01]])).pdf(x)
return responsibility
{% endhighlight %}
The *assignment* step is exactly the same as before. So let's look at the update step.
{% highlight python %}
def update_step_softv4(xs, assignments, n, curr_sigmas, curr_centroids):
all_centroid = []
all_sigma = []
for i in range(n):
centroid_resps = assignments[:, i]
curr_sigma = curr_sigmas[i]
curr_centroid = curr_centroids[i,:]
total_resp = centroid_resps.sum()
if total_resp == 0:
all_centroid.append(curr_centroid)
all_sigma.append(curr_sigma)
print("no resp for cluster %s" % str(i))
else:
# m
centroid = centroid_resps @ xs / total_resp
# diag terms
w_dist = xs - centroid
# cov matrix
cov_matrix = np.cov(w_dist.T, aweights=centroid_resps)
cov_matrix = np.nan_to_num(cov_matrix)
all_centroid.append(centroid)
all_sigma.append(cov_matrix)
# pi
pi = assignments.sum(axis=0) / assignments.sum()
return np.row_stack(all_centroid), np.stack(all_sigma), pi
{% endhighlight %}
Here are the results:

Not too bad, I think. Datasets 2 and 4 look ok. Circle ones are still rubbish. The last one with long clusters is perfect. Dataset 5 is a bit weird, but sure! That is valid way of clustering.
## Conclusions
I cheated a little. EM algorithms tend to be sensitive to initial conditions. There is a lot of literature on how to handle that. If you are going to use this in real life for some insane reason, at least run it multiple times from different initial conditions to make sure it is stable. If not, take some sort of ensemble of all of them.
Here are all the results together.

As always you can find [the notebook](https://github.com/sidravi1/Blog/blob/master/nbs/Mackay_kmeans.ipynb) with the code online. You may want to try these again with three clusters.
{% highlight python %}
{% endhighlight %}
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-06-15-empirical-and-hierarchical-bayes.md
---
layout: "post"
title: "Empirical and Hierarchical Bayes"
date: "2018-06-15 14:34"
comments: true
use_math: true
---
In [chapter 2 of BDA3](https://www.amazon.com/gp/product/1439840954/), the authors provide an example where they regularize the cancer rates in counties in the US using an empirical Bayesian model. In this post, I repeat the exercise using county level data on suicides using firearms and other means.
<div id="vis3"></div>
<script type="text/javascript">
var spec = "{{"/assets/2018-06-15_country_pop.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis3', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
(maps won't work if you have an ad-blocker. Disable it or allow this page for pretty maps: https://vega.github.io/vega-datasets/data/us-10m.json)
A lot of the methodology here is borrowed from BDA3. You should pick up that book if you want to check out the math at a deeper here. Unlike McElreath's, you can't easily read it cover to cover; it's sometimes a little dense but I found it to be a good reference book. If you have the book (or check out the notebook), you'll see that it has a 10 floating around. It's so that we talk about 1 year death rates instead of the 10 years we have in the data. I've skipped that in the model specification below for clarity.
You can get the [notebook here](https://github.com/sidravi1/Blog/blob/master/nbs/US_suicide_rates.ipynb).
## Data
I downloaded the data from [CDC's WONDER](https://wonder.cdc.gov/) for the years 2007 - 2016 (inclusive). ICD-10 Codes X60 to X84 are for intentional self-harm and within that, codes X72, X73, and X73 relate to intentional self-harm using a firearm or handgun. I downloaded county population data from the [US Census website](https://www.census.gov/data/tables/2016/demo/popest/counties-total.html) since counties that have no suicides are not in the CDC WONDER dataset.
## The problem
What is the *suicide rate* in each of the counties? We'll model this first using empirical Bayes then repeat the exercise using hierarchical Bayes and note the differences between them.
### The raw suicide rate
Since we have deaths by county, we can calculate the *raw* death rate as:
$$
\theta_j = \frac{d_j}{pop_j}
$$
where $d_j$ is the number of deaths in county $j$ and the $pop_j$ is the population in county $j$.
Here's what this looks like:
<div id="vis5"></div>
<script type="text/javascript">
var spec = "{{"/assets/2018-06-15_raw_rates.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis5', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
The next plot just highlights the counties with the highest and lowest rates:
<div id="vis4"></div>
<script type="text/javascript">
var spec = "{{"/assets/2018-06-15_high_low_rate.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis4', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
Run your mouse over the counties and note that the both, lowest and highest rates, are in counties with small populations.
As Gelman et al point out in the kidney cancer example, though there may be a number of explanations for the difference in suicide rates, a large part of this variation can be explained by just one factor: sample size or, in our context, population size.
In a small county, with say a 50k people, if 1 person dies of suicide, the rate would be 1/50k = 0.00002 which would make it a pretty high suicide rate. If that one person does not die, it would be 0 and the lowest possible rate. Because the county has such a small population, one or two deaths can change the death rate drastically.
What we ideally want to do is 'borrow' some statistical power from the larger counties that have greater population sizes to regularize the death rate in the smaller counties. In other words, we want the posterior death rates to be dominated by an informative prior for noisy small-population counties and by the likelihood for large-population counties.
Why can we do this? Let's say I tell you a county 997 has a suicide rate of 5 deaths per 100,000. This should influence what your estimate is for the suicide rate county 850. Especially if the sample size in county 997 was large. If you think that one county tells you nothing about another county then this model is flawed and we need to look at other ways of modeling it.
## Coming up with a model
Let's start by coming up with a generative model for these suicides. Let's say that there is a $\theta_j$ that is the probability of a person committing suicide. So the **likelihood** $pi(d_j \vert \theta_j)$ is a Binomial:
$$
\pi(d_j|\theta_j) \sim Bin(pop_j, \theta_j)
$$
Since we know $pop_j$ is large and $\theta_j$ is tiny, we can use the [Poisson approximation](https://en.wikipedia.org/wiki/Binomial_distribution#Poisson_approximation) for the Binomial:
$$
\pi(d_j|\theta_j) \sim Poisson(\theta_j \cdot pop_j)
$$
Now we need a **prior** on $\theta$ that satisfies two constraints:
1. $\theta_j$ must be positive.
2. Most $\theta$s should be similar.
A *gamma* distribution satisfies both of these. *Gamma* is also the conjugate prior for a *Poisson* so it can be solved analytically. The posterior is just:
$$
\begin{aligned}
\pi(\theta_j|d_j) &\propto \pi(d_j|\theta_j) \pi(\theta_j)\\
\pi(\theta_j|d_j) &\sim Gamma(\alpha + d_j, \beta + pop_j)
\end{aligned}
$$
A *beta* distribution may also be nice and we also get the added benefit of constraining $\theta$ between 0 and 1 though that's not that big of a deal. Coming up with the posterior and the prior predictive involves some algebra (and integrals) but that's not a problem if we are using Monte Carlo methods.
## Choosing prior parameters
Let's choose a *Gamma* distribution as in BDA3. Now we need to choose appropriate $alpha$ and $beta$.
### Empirical Bayes
We can use the data itself to come up with $\alpha$ and $\beta$. This is what puts the 'empirical' in empirical Bayes and is an approximation for the full bayesian treatment with hyper-parameters that we'll do next.
The prior-predictive for our Poisson-Gamma model $d_i$ is *Negative-Binomial*.
$$
\begin{aligned}
\pi(d_j) &\sim \int \pi(d_j)\pi(\theta_j) d\theta_j\\
\pi(d_j) &\sim Neg\text{-}bin(\alpha, \frac{\beta}{pop_j} )
\end{aligned}
$$
*Side note: [Wikipedia](https://en.wikipedia.org/wiki/Conjugate_prior#Table_of_conjugate_distributions) has a very handy table with all the conjugate distributions.*
The mean and variation of a *Negative-Binomial* are :
$$
\begin{aligned}
\pi(d_j) &\sim Neg\text{-}bin(\alpha, \frac{\beta}{pop_j})\\
\mathbb{E}(d_j) &= \frac{\alpha}{\beta}\\
\mathbb{V}(d_j) &= \frac{\alpha}{\beta} + \frac{\alpha}{\beta^2}
\end{aligned}
$$
Let's use the one sample that we have (starts sounding a little frequentist here), to match the moments, i.e. set the mean and variance of our sample to the moments and solve for $\alpha$ and $\beta$.
The following chart shows draws from $Gamma(\alpha, \beta)$ along with the distribution of $d_j$ or suicide rates from the data.

Not a great fit is it? It's mainly because of that large mass at zero. If you squint, you may be able to convince yourself that the first two moments are indeed the same for the two distributions.
#### Running the models
We don't really need to write any code here since we are working with conjugate pairs. But let's do it anyway for fun.
{% highlight python %}
with pm.Model() as mmatching:
rate_gun = pm.Gamma('rate_gun', a_gun, b_gun, shape=len(suicides_gun))
likelihood_gun = pm.Poisson('likelihood_gun', mu = 10*pop_gun*rate_gun,
observed = deaths_gun)
rate_other = pm.Gamma('rate_other', a_other, b_other, shape=len(suicides_other))
likelihood_deaths = pm.Poisson('likelihood_other', mu = 10*pop_other*rate_other,
observed = deaths_other)
{% endhighlight %}
The following plot shows the mean and hpd of the posterior of `rate_gun`.

Note that the suicide rates for the small counties has been shrunk substantially and it has a pretty wide credible interval. That's what you might expect. We can't be confident on the exact suicide rate for the small counties but we know it's probably higher than a zero.
### Hierarchical Bayes
Instead of using the data to come up with values for the $\alpha$ and $\beta$ parameters of the Gamma prior, we could just create priors on these and let the model learn these.
So now our model is:
$$
\begin{aligned}
\pi(\theta_j, \alpha, \beta |d_j) &\propto \pi(d_j | \theta_j) \pi(\theta_j | \alpha, \beta) \pi(\alpha, \beta)\\
\pi(\theta_j, \alpha, \beta |d_j) &\propto \pi(d_j | \theta_j) \pi(\theta_j | \alpha, \beta) \pi(\alpha|\beta) \pi(\beta)\\
\pi(\theta_j, \alpha, \beta |d_j) &\propto \pi(d_j | \theta_j) \pi(\theta_j | \alpha, \beta) \pi(\alpha) \pi(\beta)
\end{aligned}
$$
The first line is because $d_j$ is independent of $\alpha$ and $\beta$ when conditioning on $\theta_j$ i.e. $\alpha$ and $\beta$ effect $d_j$ only through $\theta_j$. The last line follows from $\alpha$ and $\beta$ being independent.
We need some priors on $\alpha$ and $\beta$. These hyper-parameters should be positive and can be large ($\beta from the empirical Bayes was around 400k), so let's use a Half-Cauchy which has fat-tails allowing for large values.
$$
\pi(\alpha) \sim Half\text{-}Cauchy(4)\\
\pi(\beta) \sim Half\text{-}Cauchy(4)
$$
Why 4? Because it seemed reasonable to me. You could choose a large number or call it a parameter $\tau$ and setup prior for that. Once you go high enough, and aren't being too restrictive, it doesn't make much of a difference.
Here's the pymc3 code to run this model:
{% highlight python %}
with pm.Model() as mhyper:
alpha_gun = pm.HalfCauchy('alpha_gun', 4)
beta_gun = pm.HalfCauchy('beta_gun', 4)
alpha_other = pm.HalfCauchy('alpha_other', 4)
beta_other = pm.HalfCauchy('beta_other', 4)
rate_gun = pm.Gamma('rate_gun', alpha_gun, beta_gun, shape=len(suicides_gun))
rate_other = pm.Gamma('rate_other', alpha_other, beta_other, shape=len(suicides_other))
likelihood_gun = pm.Poisson('likelihood_gun', mu = 10 * rate_gun * pop_gun,
observed = deaths_gun)
likelihood_other = pm.Poisson('likelihood_other', mu = 10 * rate_other * pop_other,
observed = deaths_other)
{% endhighlight %}
Here the plot again showing the mean and hpd of the posterior of `rate_gun`.

The plot below shows how the posteriors compare for the two models.

First, it's remarkable how similar they are. At least in this context, empirical Bayes provides a decent approximation. Having said that, we see more shrinkage in the hierarchical model (more points above the orange 40 degree line).
### Turtles all the way down
We are making an modeling assumption in the previous section: the parameters, $\theta$s, are *exchangable*. BDA3 describes it as follows:
> "If no information -- other that the data y -- is available to distinguish any of the $\theta_j$s from any of the other, and no ordering or grouping of the parameters can be made, one must assume symmetry among the parameters in their prior distribution (page 104, ch5)"
This assumption might not really be true. We may believe that counties can be grouped by state or by how they voted in the last election. Say we want to do it by party. We can allow of different $\alpha$ and $\beta$ for each party and then tie them with another hierarchy. Here's the pymc3 model:
{% highlight python %}
with pm.Model() as mhyper_party:
hyper_alpha = pm.HalfCauchy('hyper_alpha',1)
hyper_beta = pm.HalfCauchy('hyper_beta',1)
alpha_gun = pm.HalfCauchy('alpha_gun', hyper_alpha, shape=2)
beta_gun = pm.HalfCauchy('beta_gun', hyper_beta, shape=2)
alpha_other = pm.HalfCauchy('alpha_other', hyper_alpha, shape=2)
beta_other = pm.HalfCauchy('beta_other', hyper_beta, shape=2)
rate_gun = pm.Gamma('rate_gun', alpha_gun[party_gun], beta_gun[party_gun], shape=len(suicides_gun))
#rate_other = pm.Gamma('rate_other', alpha_other[party_other], beta_other[party_other], shape=len(suicides_other))
likelihood_gun = pm.Poisson('likelihood_gun', mu = 10 * rate_gun * pop_gun,
observed = deaths_gun)
likelihood_other = pm.Poisson('likelihood_other', mu = 10 * rate_other * pop_other,
{% endhighlight %}
Since a lot of the red counties are tiny and the blue counties are huge coastal one, the shrinkage for the small counties is less:

Here's a comparison of the shrinkage between the previous model and this 'party' model.

They are very similar except some counties (I'm guessing GOP ones) see less shrinkage.
## What else?
Here are the two suicide rate posteriors means. We are only showing means but we have the whole distribution so really should keep the credible interval in mind. Some of the counties that seem to have very different rates may have significant overlap in their credible intervals.
<div id="vis"></div>
<script type="text/javascript">
var spec = "{{"/assets/posterior_suicide_rates.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
This is a good starting point to do some deeper analysis.
It would be interesting to model the suicides in a county a little differently. Opponents of gun-laws often claim that people will find another way to commit suicide and having access to guns doesn't really increase that rate.
We could setup a mixture model and see if this is indeed true. But may be for another time. These last two posts have been pretty morose and I need to model ice cream or puppies for a bit.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-07-08-fader-hardie-clv.md
---
layout: "post"
title: "Implementing Fader Hardie (2005) in pymc3 "
date: "2018-07-08 00:11"
comments: true
use_math: true
---
This posts gives the [Fader and Hardie (2005)](http://brucehardie.com/papers/018/fader_et_al_mksc_05.pdf) model the full Bayesian treatment. You can check out the [notebook here](https://github.com/sidravi1/Blog/blob/master/nbs/Fader_Hardie.ipynb).
Here's the first paragraph from the introduction introducing the problem:
> Faced with a database containing information on the frequency and timing of transactions for a list of customers, it is natural to try to make forecasts about future purchasing. These projections often range from aggregate sales trajectories (e.g., for the next 52 weeks), to individual-level conditional expectations (i.e., the best guess about a particular customer’s future purchasing, given information about his past behavior). Many other related issues may arise from a customer-level database, but these are typical of the questions that a manager should initially try to address. This is particularly true for any firm with serious interest in tracking and managing “customer lifetime value” (CLV) on a systematic basis. There is a great deal of interest, among marketing practitioners and academics alike, in developing models to accomplish these tasks.
They construct a beta-geometric model to model the number of repeat transactions for a customer.
## The model
All this is in the paper so I'll go over it quickly. Here are the modeling assumptions:
1. If active, time between customer $i$'s transactions are a Poisson process:\\
$$
t_j - t_{j-1} \sim Poisson(\lambda_i)
$$
2. Each customer has her own $\lambda$ but it follows a gamma distribution\\
$$
\lambda \sim Gamma(\alpha, \beta)
$$
3. After (a key difference from the Pareto/NBD model) any transaction, customer $i$ can go inactive with probability $p_i$. So after
$$
P(\text{i is in-active after j transactions}) = p_i(1 - p_i)^{j-1}
$$
4. Each customer has her own $p$ but it follows a beta distribution\\
$$
p \sim Beta(a, b)
$$
## Likelihood
F&H derive the following likelihood (eq. 3 in their paper):
$$
L(\lambda, p | X=x, T) = (1 - p)^x\lambda^x e^{-\lambda T} + \delta_{x>0} p(1-p)^{x-1}\lambda_{x}e^{-\lambda t_x}
$$
If you try to implement this, you'll quickly run into numerical issues. So let's clean this up a bit:
$$
\begin{aligned}
L(\lambda, p | X=x, T) &= (1 - p)^x\lambda^x e^{-\lambda T} + \delta_{x>0} p(1-p)^{x-1}\lambda_{x}e^{-\lambda t_x}\\
L(\lambda, p | X=x, T) &= (1 - p)^x\lambda^x e^{-\lambda t_x} (e^{-\lambda(T - t_x)} + \delta_{x>0} \frac{p}{1-p})\\
\end{aligned}
$$
Taking logs to calculate the log-likelihood:
$$
l(\lambda, p | X=x, T) = x log(1 - p) + x log(\lambda) - \lambda t_x + log(e^{-\lambda (T - t_x)} +
\delta_{x>0}e^{log(\frac{p}{1-p})})
$$
Now that last term can be written using 'logsumexp' in theano to get around the numerical issues. [Here's an explanation](https://am207.github.io/2017/wiki/marginaloverdiscrete.html#the-log-sum-exp-trick-and-mixtures) for how it works. Numpy also has an implementation of this function.
## PYMC3 model
You can get the data [from here](http://www.brucehardie.com/notes/004/). I couldn't find their test set online (for 39 - 78 weeks). Let me know if you find it.
{% highlight python %}
{% endhighlight %}
### Load the data
{% highlight python %}
data_bgn = pd.read_excel("./bgnbd.xls", sheetname='Raw Data')
n_vals = len(data_bgn)
x = data_bgn['x'].values
t_x = data_bgn['t_x'].values
T = data_bgn['T'].values
int_vec = np.vectorize(int)
x_zero = int_vec(x > 0) # to implement the delta function
{% endhighlight %}
### Setup and run model
We need write our own custom density using the equation above. We're working with tensors.
{% highlight python %}
import pymc3 as pm
import numpy as np
import theano.tensor as tt
with pm.Model() as model:
# Hypers for Gamma params
a = pm.HalfCauchy('a',4)
b = pm.HalfCauchy('b',4)
# Hypers for Beta params
alpha = pm.HalfCauchy('alpha',4)
[id]: url "title" = pm.HalfCauchy('beta',4)
lam = pm.Gamma('lam', alpha, r, shape=n_vals)
p = pm.Beta('p', a, b, shape=n_vals)
def logp(x, t_x, T, x_zero):
log_termA = x * tt.log(1-p) + x * tt.log(lam) \
- t_x * lam
termB_1 = -lam * (T - t_x)
termB_2 = tt.log(p) - tt.log(1-p)
log_termB = pm.math.switch(x_zero,
pm.math.logaddexp(termB_1, termB_2), termB_1)
return tt.sum(log_termA) + tt.sum(log_termB)
like = pm.DensityDist('like', logp,
observed = {'x':x, 't_x':t_x, 'T':T, 'x_zero':x_zero})
{% endhighlight %}
and let's run it:
{% highlight python %}
with model:
trace = pm.sample(draws=6000, target_accept = 0.95, tune=3000)
{% endhighlight %}
## Hyper-parameters
Remember that each customer $i$ has her own $p_i$ and $\lambda_i$. So let's look at what the hyper-parameters look like:

The mean value for each of these hyper-parameters is what Fader and Hardie get but we have the entire distribution.
## Model Checks
You should do the Gelman-Rubin and Geweke tests at the least to make sure our model has converged. I won't do it here but it's in the notebook.
## Posterior predictive checks
We can be pretty confident this model is right but it's a good habit to do some posterior predictive checks so let's do them anyway,
Usually we'd just run `pm.sample_ppc` and get some posterior predictives but that won't work for us since we have a custom likelihood. Fader and Hardie derive $E(X(t)\vert\lambda,p)$ in equation 7. We can just use that formula to calculate the posterior predictives and see how well the models match the data observed.
{% highlight python %}
p_post = trace['p']
lam_post = trace['lam']
expected_all = (1/p_post) * (-np.expm1(-lam_post * p_post * T))
{% endhighlight %}
Note that we factor out $\frac{1}{p}$ so allows us to use [np.expm1](https://docs.scipy.org/doc/numpy/reference/generated/numpy.log1p.html) to avoid any overflow/underflow numerical issues. Theano and pymc3 also provide this function in case you need it while constructing a model.
Let's see what this looks like. You can run this code multiple times to get a different random set of 16 customers and convince yourself that the model looks good:
{% highlight python %}
# pick some random idx
idx = np.random.choice(np.arange(len(x)), size=16, replace=False)
f, axes = plt.subplots(4,4, figsize=(10,10))
for ax, i in zip(axes.ravel(), idx):
_ = ax.hist(expected_all[:,i], density=True, alpha = 0.7, bins=20)
_ = ax.axvline(x[i],ls='--', color='firebrick')
_ = ax.set_title('cust: {numb}'.format(numb=i))
_ = plt.tight_layout()
{% endhighlight %}
This gives us the following plots.

Looks pretty good to me though there seem to be some shrinkage for the large values. The data points (the line) are in the high probability region of the distribution of $E(X(t)\vert\lambda, p)$.
## Why Bayesian
The mean values for $\alpha, r, a, b$ are around what Fader and Hardie find in their paper. So why do we bother setting up a full Bayesian model? The main advantage is that we now have a distribution so we can add some credible intervals when reporting the expected number of transactions for a customer. Also knowing the entire distribution, allows a business to design more effective targeting.
The cost is speed. Fader and Hardie use the optimizer in Excel to maximize the likelihood. In Python that would take you seconds and you have your pick of the latest optimizers. Running MCMC to draw samples from the posterior is slow. One option around it is to use variational inference to get approximations (check out the end of the [notebook](https://github.com/sidravi1/Blog/blob/master/nbs/Fader_Hardie.ipynb)).
There are also other ways to get around this problem. You could use a ["coreset"](https://github.com/trevorcampbell/bayesian-coresets/). Or you could assume hypers don't change and just do a forward pass with new $x$ and $t_x$ and re-run the full model once every few months.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
<file_sep>/_posts/2018-05-22-what-happened-in-2006.md
---
layout: "post"
title: "What happened in 2006?"
date: "2018-05-22 20:59"
comments: true
use_math: true
---
Anyone else feel that US mass shootings have increased over the past few years? My wife thinks that it's just availability heuristic at play. Well, luckily there is data out there that we can use to test it. This analysis in this blog uses the dataset from [Mother Jones](https://www.motherjones.com/politics/2012/12/mass-shootings-mother-jones-full-data/). I did some minor cleaning that you can see in [the notebook](https://github.com/sidravi1/Blog/blob/master/nbs/US_Shootings_Altair.ipynb).
<div id="vis"></div>
<script type="text/javascript">
var spec = "{{"/assets/US_mass_shooting_map.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
*Trigger Warning: This ended up being a pretty morbid post about mass shootings and fatalities.*
I have been enjoying visualizations in [Altair](https://altair-viz.github.io/) of late. Once you get accustomed to the declarative style, it's hard to go back to matplotlib and seaborn. There are still some things that can't easily be done in Altair and I had to fall back on seaborn and matplotlib. The map above and the plot below were done with Altair. Run your mouse over the bars in the chart above and select an area (and move it) on the scatter below for some fancy interactions. If you use an ad-blocker, the map may not load correctly. So pause it for the site and reload this page.
<div id="vis2" align="center"></div>
<script type="text/javascript">
var spec = "{{"/assets/US_mass_shooting_byyear.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis2', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
Ok. On to the analysis.
## Number of fatalities
The bar chart under the map seems to suggest that fatalities have increased.
[Coal mining disaster](http://docs.pymc.io/notebooks/getting_started#Case-study-2:-Coal-mining-disasters) is the canonical example for bayesian change point analysis. What I do here is not that different. The model is as follows:
$$
y \vert \tau, \lambda_1, \lambda_2 \sim Poisson(r_t)\\
r_t = \lambda_1 \,{\rm if}\, t < \tau \,{\rm else}\, \lambda_2 \,{\rm for}\, t \in [t_l, t_h]\\
\tau \sim DiscreteUniform(t_l, t_h)\\
\lambda_1 \sim Exp(a)\\
\lambda_2 \sim Exp(b)\\
$$
(borrowed shamelessly from [AM207](https://am207.github.io/2017/wiki/switchpoint.html))
We model the occurrence of a mass shooting fatality as a Poisson RV. At some discreter time, $\tau$, the rate parameter (or mean) of the Poisson RV changes from $\lambda_1$ to $\lambda_2$.
Modeling this in pymc3 is pretty simple and you can check the notebook for the implementation.
{% highlight python %}
import pymc3 as pm
from pymc3.math import switch
with pm.Model() as us_mass_fatal:
early_mean = pm.Exponential('early_mean', 1)
late_mean = pm.Exponential('late_mean', 1)
switchpoint = pm.DiscreteUniform('switchpoint', lower=0, upper=n_years)
rate = switch(switchpoint >= np.arange(n_years), early_mean, late_mean)
shootings = pm.Poisson('shootings', mu=rate, observed=fatality_data)
{% endhighlight %}
And this give us a switch point of 2006 (with a pretty tight hpd). The following plot shows a random 500 draws of switch points and the two rates. The rate changed substantially! And 2018 is not even half way done. Ugh.

## Number of mass shootings
One thing that makes me uncomfortable with this analysis is that we are modeling fatalities as independent draws from a Poisson RV. But we know that is not the correct model for the 'generating process' (that sounds so callous, I'm sorry). The *occurrence* of a mass shooting can be modeled as independent draws from a Poisson and the number of fatalities per incident should be modeled separately.
Let's just look at the number of mass shootings first. The code is the same as above.
{% highlight python %}
import pymc3 as pm
from pymc3.math import switch
with pm.Model() as us_mass_sh:
early_mean = pm.Exponential('early_mean', 1)
late_mean = pm.Exponential('late_mean', 1)
switchpoint = pm.DiscreteUniform('switchpoint', lower=0, upper=n_years)
rate = switch(switchpoint >= np.arange(n_years), early_mean, late_mean)
shootings = pm.Poisson('shootings', mu=rate, observed=shootings_data)
{% endhighlight %}
The switch point in this case is not so clear cut. The histogram of the sample draws for posterior $\tau$ is bimodal.
<div align="center">
<img src="{{"/assets/2018-05-22_shootings_switchpoint.png" | absolute_url}}" alt="Switch points distribution" style="width: 600px;"/>
</div>
Let's look at these separately; we'll consider the values of $\lambda_1$ and $\lambda_2$ in the two modes.
The chart below shows the associated posteriors for the lambdas in the two modes. Though there is substantial overlap, $\lambda_1$ seems similar in the two modes while $\lambda_2$ is more different.

The plot below makes it a little clearer. So, we have two most probable switch points (we're considering the top two modes - though we have an entire distribution of switch points). $\lambda_2$ (or the late rate) is lower for the switch point around 2006 (in red) compared to the one for the switch point around 2011.

## Something happened in 2006 (or 2011)
Note that in either case, the distribution of $\lambda_1$ and $\lambda_2$ have barely any common support. The rate definitely went up recently. We can argue if it was around 2006 or 2011.
So what happened around here? Number of guns go up? [New legislation](http://time.com/5169210/us-gun-control-laws-history-timeline/)? Did Mother Jones just hire a more diligent data collector?
## Next up: Rate of fatalities
<div id="vis3"></div>
<script type="text/javascript">
var spec = "{{"/assets/US_mass_shooting_venue.json" | absolute_url}}";
var opt = {"actions":false}
vegaEmbed('#vis3', spec, opt).then(function(result) {
// access view as result.view
}).catch(console.error);
</script>
What about the rate of fatalities i.e. how many die per mass shooting? Has that increased over the years?
There are a few models to compare:
- It's a year effect: More people are killed every year (maybe due to easier access to higher powered guns).
- It's a venue effect: More people are killed because of WHERE the shootings take place. Some venues just lead to larger number of deaths and that's where the shootings are now occurring.
- It's a bit of both: There is a year trend and a venue effect.
And in many of these cases, we can have a fully pooled or a partially pooled model. I'll do a separate post for this and properly compare these models.
{% if page.comments %}
{%- include disqus_tags.html -%}
{% endif %}
| eb50112ca642fe3c9f7b3b88682fee6131c0e080 | [
"Markdown",
"Ruby",
"HTML"
]
| 39 | Markdown | sidravi1/sidravi1.github.io | bcafcd8fcede5d2362bd850bb8e0ff48a2a83447 | 4d3ea011eee18c1f8c0a9e6f307b6288d3701ace |
refs/heads/master | <repo_name>tenzorOne/CPP_HARD_GEEKBRAINS<file_sep>/DZ_CPPHARD_01/DZ_CPPHARD_01/DZ_CPPHARD_01.cpp
#include <iostream>
#include <algorithm>
#include <optional>
#include <string>
#include <fstream>
#include <vector>
#include <iomanip>
using namespace std;
// Задание 1: Структура Person
struct Person {
string surname;
string name;
optional <string> patronymic;
};
bool operator<(const Person& p1, const Person& p2)
{
return tie(p1.surname, p1.name, p1.patronymic.has_value() ? p1.patronymic.value() : "") < tie(p2.surname, p2.name, p2.patronymic.has_value() ? p2.patronymic.value() : "");
}
bool operator==(const Person& p1, const Person& p2)
{
return tie(p1.surname, p1.name, p1.patronymic.has_value() ? p1.patronymic.value() : "") == tie(p2.surname, p2.name, p2.patronymic.has_value() ? p2.patronymic.value() : "");
}
ostream& operator<<(ostream& os, const Person& p)
{
os << setw(11) << p.surname << " " << setw(11) << p.name << " ";
if (p.patronymic)
os << setw(16) << *p.patronymic;
else
os << " ";
return os;
}
//
// Задание 2: Структура PhoneNumber
struct PhoneNumber {
int country_code = 0;
int city_code = 0;
string number;
optional<int> additional_number;
};
bool operator<(const PhoneNumber& pn1, const PhoneNumber& pn2)
{
return tie(pn1.country_code, pn1.city_code, pn1.number, pn1.additional_number) < tie(pn2.country_code, pn2.city_code, pn2.number, pn2.additional_number);
}
ostream& operator<<(ostream& os, const PhoneNumber& pn)
{
os << setw(4) << "+" << pn.country_code << "(" << pn.city_code << ")" << pn.number << " ";
if (pn.additional_number)
os << *pn.additional_number;
cout << endl;
return os;
}
//
// Задание 3: Класс PhoneBook
class PhoneBook {
private:
vector<pair<Person, PhoneNumber>> pb;
public:
PhoneBook(ifstream& f)
{
string str_buff, temp_surn, temp_n, temp_num; //
int temp_ccode, temp_cicode; // буфер-переменные в которые считываются
optional<string> temp_patron; // данные из файла
optional<int> temp_addnum; // str_buff главный буфер, который является хранилищем всего, что считали с файла, перед тем, как переместить данные в нужную буфер-переменную
const size_t MAX_ELEMENT_PER_LINE = 7; // максимальное число элементов в строке
size_t data_id = 0; // индекс для различных данных из файла (Фамилия, Имя и т.д.)
size_t pair_id = 0; // индекс для вектора пар pb
while (!f.eof())
{
for (size_t i = 0; i < MAX_ELEMENT_PER_LINE; i++)
{
getline(f, str_buff, ';'); // читаем файл (и пишем в str_buff) до ';' (сепаратор того, что мы встретили конец одного элемента, например Фамилии, и начало другого, например Имени)
if (str_buff.find(';'))
{
if (!str_buff.find('!')) // если встречаем '!' (сепаратор того, что у человека нет Отчества и/или добавочного номера), то устанавливаем nullopt...
{
if (data_id == 2 || data_id == 6) // если data_id == 2, то речь идет об отсутсвии Отчества, если 6, то об отсутствии добавочного номера
{
if (data_id < 3)
temp_patron = nullopt;
else
temp_addnum = nullopt;
data_id++; // ...и инкрементируем индекс, чтобы switch корректно функционировал далее
}
}
else
{
// исходя из значения data_id присваиваем некой буфер-переменной значение из str_buff. stoi() нужна в тех случаях, когда из str_buff (string) нам надо записать цифры, то есть в int
// также не забываем инкрементировать data_id, чтобы следующий case оказался верным
switch (data_id)
{
case 0: temp_surn = str_buff; data_id++; break;
case 1: temp_n = str_buff; data_id++; break;
case 2: temp_patron = str_buff; data_id++; break;
case 3: temp_ccode = stoi(str_buff); data_id++; break;
case 4: temp_cicode = stoi(str_buff); data_id++; break;
case 5: temp_num = str_buff; data_id++; break;
case 6: temp_addnum = stoi(str_buff); break;
}
}
}
}
pb.resize(pair_id + 1); // когда все временные буфера с данными из файла готовы, то изменим размер вектора (текущий размер + 1)
pb.push_back(make_pair(pb[pair_id].first = { temp_surn, temp_n, temp_patron }, pb[pair_id].second = { temp_ccode, temp_cicode, temp_num, temp_addnum })); // push всех данных в pair_id-элемент вектора
pair_id++; // инкремент для следующего элемента вектора
data_id = 0; // сбросим индекс для данных из файла, поскольку будем читать новую строку
f.get(); // пропустим символ новой строки ('\n')
}
pb.pop_back(); // после того, как мы полностью заполнили вектор, удалим самый последний элемент. Исходя из подхода с pb.resize(pair_id + 1) будет создан один лишний элемент в векторе со строкой, которой на самом деле нет
}
// сортировка по телефону
void SortByPhone()
{
sort(pb.begin(), pb.end(), [](const pair<Person, PhoneNumber>& l_pair, const pair<Person, PhoneNumber>& r_pair) { return l_pair.second < r_pair.second; });
}
// сортировка по ФИО
void SortByName()
{
sort(pb.begin(), pb.end(), [](const pair<Person, PhoneNumber>& l_pair, const pair<Person, PhoneNumber>& r_pair) { return l_pair.first < r_pair.first; });
}
tuple<string, PhoneNumber> GetPhoneNumber(const string& surname)
{
tuple<string, PhoneNumber> find_pn, find_more_pn, not_find_pn;
int count = 0;
for_each(pb.begin(), pb.end(), [surname, &count, &find_pn, &find_more_pn, ¬_find_pn](const pair<Person, PhoneNumber>& item) {
if (item.first.surname == surname) // если фамилия в контейнере и фамилия переденная в функцию совпадают...
{
count++; // ...то увеличить счетчик совпадений: если он станет больше единицы, то можно утверждать, что в векторе есть люди с одинаковой фамилией
count > 1 ? find_more_pn = make_tuple("found more than 1", item.second) : find_pn = make_tuple("", item.second); // если count == 1, то мы нашли человека и выведем его телефон, если > 1,
} // то укажем, что подобных людей больше одного
else
{
not_find_pn = make_tuple("not found", item.second); // если совпадений по фамилии нет, то ничего не найдено
}
});
if (count > 0 && count < 2)
return find_pn;
else if (count > 1)
return find_more_pn;
else
return not_find_pn;
}
void ChangePhoneNumber(const Person& p, const PhoneNumber& pn)
{
find_if(pb.begin(), pb.end(), [p, pn](pair<Person, PhoneNumber>& item) {
if (item.first == p) // если ФИО совпадают
item.second = pn; // записываем новый телефон этого человека в контейнер
else
return false; // иначе ничего не делаем
});
}
friend ostream& operator<<(ostream& os, const PhoneBook& pb);
};
ostream& operator<<(ostream& os, const PhoneBook& pb)
{
for (const auto& [person, number] : pb.pb)
{
os << person << number;
}
return os;
}
int main()
{
ifstream file("PhoneBook.txt");
PhoneBook book(file);
cout << " ==== UNSORTED LIST ==== " << endl;
cout << book;
cout << endl;
cout << " ==== SORT BY PHONE ==== " << endl;
book.SortByPhone();
cout << book;
cout << endl;
cout << " ==== SORT BY NAME ==== " << endl;
book.SortByName();
cout << book;
cout << endl;
cout << " ==== GET PHONE NUMBER ==== " << endl;
auto print_phone_number = [&book](const string& surname) {
cout << surname << "\t";
auto answer = book.GetPhoneNumber(surname);
if (get<0>(answer).empty())
cout << get<1>(answer);
else
cout << get<0>(answer) << endl;
};
print_phone_number("Ivanov");
print_phone_number("Petrov");
print_phone_number("Solovev");
cout << endl;
cout << " ==== CHANGE PHONE NUMBER ==== " << endl;
book.ChangePhoneNumber(Person{ "Kotov", "Vasilii", "Eliseevich" }, PhoneNumber{ 7, 123, "15344458", nullopt });
book.ChangePhoneNumber(Person{ "Mironova", "Margarita", "Vladimirovna" }, PhoneNumber{ 16, 465, "9155448", 13 });
cout << book;
}<file_sep>/DZ_CPPHARD_02/DZ_CPPHARD_02/DZ_CPPHARD_02.cpp
#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
#include <fstream>
#include <string>
#include <string_view>
#include "Timer.h"
using namespace std;
// Задание 1
template <class T>
void Swap(T& ptr1, T& ptr2)
{
swap(ptr1, ptr2);
}
//
// Задание 2
template <class T>
void SortPointer(vector<T*>& ptr)
{
sort(ptr.begin(), ptr.end(), [](T* p1, T* p2) { return *p1 < *p2; });
}
//
// Задание 3
// использование std::count_if() и string::find()
void FindVowelsVAR1(ifstream& f)
{
Timer timer("std::count_if() and string::find()");
string str;
string_view str_v;
size_t count = 0;
auto IsValidChar = [&str_v](const char& ch) {
switch (str_v.at(str_v.find(ch)))
{
case 'A': return true;
case 'a': return true;
case 'E': return true;
case 'e': return true;
case 'I': return true;
case 'i': return true;
case 'O': return true;
case 'o': return true;
case 'U': return true;
case 'u': return true;
case 'Y': return true;
case 'y': return true;
default: return false;
};
};
while (true)
{
if (!f.eof())
{
getline(f, str);
str_v = str;
count += count_if(str_v.begin(), str_v.end(), IsValidChar);
}
else
break;
}
cout << count << " vowels in the text." << " Method: ";
timer.print();
cout << " execution time";
cout << endl;
}
// использование только std::count_if()
void FindVowelsVAR2(ifstream& f)
{
Timer timer("only std::count_if()");
string str;
string_view str_v;
size_t count = 0;
auto IsValidChar = [&str_v](const char& ch) {
for (size_t i = 0; i < str_v.length(); i++)
{
switch (ch)
{
case 'A': return true;
case 'a': return true;
case 'E': return true;
case 'e': return true;
case 'I': return true;
case 'i': return true;
case 'O': return true;
case 'o': return true;
case 'U': return true;
case 'u': return true;
case 'Y': return true;
case 'y': return true;
default: return false;
};
}
};
while (true)
{
if (!f.eof())
{
getline(f, str);
str_v = str;
count += count_if(str_v.begin(), str_v.end(), IsValidChar);
}
else
break;
}
cout << count << " vowels in the text." << " Method: ";
timer.print();
cout << " execution time";
cout << endl;
}
// использование только string::find()
void FindVowelsVAR3(ifstream& f)
{
Timer timer("only string::find()");
string str;
string_view str_v;
size_t count = 0;
while (true)
{
if (!f.eof())
{
getline(f, str);
str_v = str;
for (size_t i = 0; i < str_v.length(); i++)
{
switch (str_v.at(str_v.find(str_v[i])))
{
case 'A': count++; break;
case 'a': count++; break;
case 'E': count++; break;
case 'e': count++; break;
case 'I': count++; break;
case 'i': count++; break;
case 'O': count++; break;
case 'o': count++; break;
case 'U': count++; break;
case 'u': count++; break;
case 'Y': count++; break;
case 'y': count++; break;
};
}
}
else
break;
}
cout << count << " vowels in the text." << " Method: ";
timer.print();
cout << " execution time";
cout << endl;
}
// использование вложенных циклов for
void FindVowelsVAR4(ifstream& f)
{
Timer timer("double FOR");
string str;
string_view str_v;
size_t count = 0;
while (true)
{
if (!f.eof())
{
getline(f, str);
str_v = str;
size_t i = 0;
size_t j = str_v.length() - 1;
for (; i < str_v.length(); i++)
{
switch (str_v[i])
{
case 'A': count++; break;
case 'a': count++; break;
case 'E': count++; break;
case 'e': count++; break;
case 'I': count++; break;
case 'i': count++; break;
case 'O': count++; break;
case 'o': count++; break;
case 'U': count++; break;
case 'u': count++; break;
case 'Y': count++; break;
case 'y': count++; break;
};
if (i < j)
{
for (; j != 0;)
{
switch (str_v[j])
{
case 'A': count++; j--; break;
case 'a': count++; j--; break;
case 'E': count++; j--; break;
case 'e': count++; j--; break;
case 'I': count++; j--; break;
case 'i': count++; j--; break;
case 'O': count++; j--; break;
case 'o': count++; j--; break;
case 'U': count++; j--; break;
case 'u': count++; j--; break;
case 'Y': count++; j--; break;
case 'y': count++; j--; break;
};
break;
}
}
else
break;
}
}
else
break;
}
cout << count << " vowels in the text." << " Method: ";
timer.print();
cout << " execution time";
cout << endl;
}
//
// main()
int main()
{
//
int a = 25;
int b = 50;
int* a_ptr = &a;
int* b_ptr = &b;
string first_name = "Nikita";
string second_name = "Maksim";
string* f_ptr = &first_name;
string* s_ptr = &second_name;
//
cout << "Before swap: " << endl; /// Поменять местами значения на которые указывают указатели
cout << *a_ptr << " " << *b_ptr << endl; //
Swap(a_ptr, b_ptr);
cout << "After swap: " << endl;
cout << *a_ptr << " " << *b_ptr << endl;
cout << "Before swap: " << endl;
cout << *f_ptr << " " << *s_ptr << endl;
Swap(f_ptr, s_ptr);
cout << "After swap: " << endl;
cout << *f_ptr << " " << *s_ptr << endl;
cout << endl;
//
//
int num1 = 2;
int num2 = 7845;
int num3 = 35;
int num4 = 999;
int num5 = 41;
vector<int*> ptr_to_ints { &num1, &num2, &num3, &num4, &num5 };
string str1 = "Zodiac";
string str2 = "Bob";
string str3 = "David";
string str4 = "Gregor";
string str5 = "Jack";
vector<string*> ptr_to_strings { &str1, &str2, &str3, &str4, &str5 };
vector<int*>::const_iterator it_int;
cout << "Before sort: " << endl;
for (it_int = ptr_to_ints.begin(); it_int < ptr_to_ints.end(); it_int++)
{
cout << **it_int << " ";
}
cout << endl;
//
SortPointer(ptr_to_ints); /// Сортировка вектора указателей по значениям на которые указывают указатели
//
cout << "After sort: " << endl;
for (it_int = ptr_to_ints.begin(); it_int < ptr_to_ints.end(); it_int++)
{
cout << **it_int << " ";
}
cout << endl;
vector<string*>::const_iterator it_str;
cout << "Before sort: " << endl;
for (it_str = ptr_to_strings.begin(); it_str < ptr_to_strings.end(); it_str++)
{
cout << **it_str << " ";
}
cout << endl;
SortPointer(ptr_to_strings);
cout << "After sort: " << endl;
for (it_str = ptr_to_strings.begin(); it_str < ptr_to_strings.end(); it_str++)
{
cout << **it_str << " ";
}
cout << endl << endl;
//
//
cout << "Find all vowels in War and Peace" << endl;
ifstream file("War and Peace.txt");
FindVowelsVAR1(file);
file.seekg(0);
FindVowelsVAR2(file); //
/// Подсчет гласных букв разными методами
file.seekg(0); //
FindVowelsVAR3(file);
file.seekg(0);
FindVowelsVAR4(file);
//
} | 6064c2cc3a770c4dc124075dbccfce8f22d12951 | [
"C++"
]
| 2 | C++ | tenzorOne/CPP_HARD_GEEKBRAINS | 8310015c8c7c11e7af97d0e4ef06d0aac8599725 | 2afaf01f529b62d959f6ecee61d0f56a880b98eb |
refs/heads/master | <repo_name>pbinkley/ZotScan<file_sep>/README.md
ZotScan
==========
Google Apps Script to take emailed attachments and generate RIS file suitable for import into [Zotero](http://www.zotero.org/)
This is script is to be deployed as a webapp with [Google Apps Script](https://developers.google.com/apps-script/).
Use case: I'm working through a print journal, copying lots of short articles and ads with my phone (I use [TurboScan](https://itunes.apple.com/ca/app/turboscan-quickly-scan-multipage/id342548956?mt=8) on the iPhone, or, even better, [CamScanner](https://play.google.com/store/apps/details?id=com.intsig.camscanner&hl=en) on an Android tablet). I want to import them into Zotero.
So: I email them to my Gmail account (hosted at my own domain - I haven't worked out yet whether this will work with a consumer gmail account). I enter the metadata in RIS format in the body of the email, and attach the PDF. The subject line contains "ZoteroScan", which triggers GMail to attach a label. Once I've sent a few items, I visit the webapp. It fetches all the labelled emails, uploads their attaachments to a Google Site, and gives me a script which I run on my workstation. That script downloads all the PDFs from the site, and gives me an RIS file which contains links to the downloaded PDFs. I check the RIS file and make any necessary changes, then import it into Zotero. I can then delete the emails and do more scanning.
###Installation:
* go to https://script.google.com and create a project. Copy the two files, myCode.gs and myPage.html into it.
* add several project properties to the script (see the comments in myCode.gs).
* save a version and authorize it to access your apps by clicking the "Play" icon
* publish it as a webapp
###Running:
* scan some items and email them to yourself with the appropriate subject line and with RIS metadata in the message body
* visit the webapp with your browser
* copy the script into your working directory and run it
* import zoteroscan.ris into Zotero
###RIS example:
This is a template I used when working through the 1936 volume of Library Journal. I would paste this into the email, then fill in the article-level fields such as author, title, issue number and date, and start page and end page. KW entries will become Zotero tags. An AB entry will become an abstract. To see what Zotero expects for different item types, try exporting an existing item as RIS.
```
TY - JOUR
AU -
TI -
T2 - Library Journal
DA - 1936/
VL - 61
IS -
KW - LJ1936
SP -
EP -
ER -
```
###Output
The output is a shell script that downloads each PDF to the current directory using wget, and generates an RIS file with the item-level RIS from each message, augmented with an L1 link to the local copy of the PDF. It's necessary to link to a local PDF in order to get Zotero to import it, rather than just save the URL of a remote PDF.
```
# Message 13c27da1c6e5ef3e: ZoteroScan
wget https://sites.google.com/a/yourgoogleappdomain.com/zoteroscan/ZoteroScan/13c27da1c6e5ef3e_1.pdf
...
TY - JOUR
AU -
TI - Denver Conference
T2 - Library Journal
DA - 1935/09/15/
VL - 60
IS - 16
KW - LJ1935
SP - 706
EP - 710
AB - lengthy discussion of federal aid; quotes Lydenberg
L1 - file:///Users/peterbinkley/Downloads/13c27da1c6e5ef3e_1.pdf
ER -
```
<file_sep>/myCode.gs
function doGet() {
var t = HtmlService.createTemplateFromFile('myPage');
t.script = processZoteroScan();
return t.evaluate();
}
function processZoteroScan() {
// config - set project properties with your values
// domain: your google app domain e.g. "example.com"
var domain = ScriptProperties.getProperty('domain');
// sitename: the name of the Google Site which you'll use to host this webapp e.g. "zoteroscan"
var sitename = ScriptProperties.getProperty('sitename');
// fcname: the name of the File Cabinet Page within your Site where the attachments will be hosted e.g. "ZoteroScan"
var fcname = ScriptProperties.getProperty('fcname');
// gmlabel: the GMail gmlabel which is assigned to the messages e.g. "ZoteroScan"
var gmlabel = ScriptProperties.getProperty('gmlabel');
// gmlimit: number of threads to process e.g. 100
var gmlimit = ScriptProperties.getProperty('gmlimit');
// localpath: the directory on your local machine where you will run the script, download the attachments, and generate the RIS file
// e.g. /Users/me/Downloads
var localpath = ScriptProperties.getProperty('localpath');
// url of the file cabinet page
var pageurl = "https://sites.google.com/a/" + domain + "/" + sitename + "/" + fcname;
// prepare to add attachments to site
var site = null;
try {
site = SitesApp.getSite(domain, sitename);
}
catch(e) {
site = SitesApp.createSite(domain, sitename, "ZoteroScan", "ZoteroScan managment site");
}
var fileCabinet = null;
try {
fileCabinet = SitesApp.getPageByUrl(pageurl);
}
catch(e) {
fileCabinet = site.createFileCabinetPage("ZoteroScan", "ZoteroScan", "<h1>Files</h1>")
}
var ris = "";
var download = "#!/bin/sh\n# ZoteroScan script generated at " + Date();
var conversations = GmailApp.search('label:' + gmlabel, 0, gmlimit);
for (i in conversations) {
var messages = conversations[i].getMessages();
for (j in messages) {
// individual message
var message = messages[j];
var messageid = message.getId();
var subject = message.getSubject();
download += "\n\n# Message " + messageid + ": " + subject + "\n\n";
// strip html tags from body, retaining line breaks, and remove blank lines
var body = message.getBody().replace(/(<(br\s?\/?)>)/ig,"\n").replace(/(<(\/div)>)/ig,"\n").replace(/(<([^>]+)>)/ig,"").replace(/^\s*$[\n\r]{1,}/gm, '');
ris += body;
var attachments = message.getAttachments();
var attnum = 0;
for (k in attachments) {
attnum++;
// rename with message id and attachment num prefix, to prevent clashes
// when two messages have attachments with same name
var attname = messageid + "_" + attnum + "_" + attachments[k].getName();
attachments[k].setName(attname);
// add attachment to file cabinet
try {
var fcAttachment = fileCabinet.addHostedAttachment(attachments[k]);
}
catch(e) {
download += "\n# " + attname + " already exists in file cabinet\n";
}
// add attachment entries to ris and download script
ris += "\nL1 - file://" + localpath + "/" + encodeURIComponent(attname) + "\n";
download += "wget " + pageurl + "/" + encodeURIComponent(attname) + "\n"
}
ris += "ER -\n";
}
}
// assemble the script
var script = download;
script += "\n# Generate RIS file\n\ncat > zoteroscan.ris <<EOF\n";
script += ris;
script += "\nEOF\necho RIS file: zoteroscan.ris\n";
return script;
}
| 3ecdbe1258fc7e43fd66c228bb42b00ae07bc0d6 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | pbinkley/ZotScan | 2a4b80c846199b608c4b3a3b0aa9983466dd56bf | bc00984db4abd42e2ed899c2550d0861681aae5b |
refs/heads/master | <file_sep>$(document).ready(function(){
$("#guitarScheduler").submit(function(event){
var userName = $("input#userName").val();
var apptDescrip = $("input#apptDescrip").val();
var date = $("input#date").val();
var time = $("input#time").val();
$(".userName").text(userName);
$(".apptDescrip").text(apptDescrip);
$(".date").text(date);
$(".time").text(time);
$("#hiddenConfirm").show()
event.preventDefault();
});
});
| d22735c8f0f4e6b8dd1035040d8277eff42c0c23 | [
"JavaScript"
]
| 1 | JavaScript | darkknightsds/appt-sched | 3d6dfc468d0a74f25bf1af2e3af1c60359b821dd | bc0d6c6cd92c1115ef0e52810d051d0e219289d9 |
refs/heads/master | <file_sep>import ReactDOM from 'react-dom';
// React package for constructing components (and all non-DOM related actions)
import React from 'react';
import MainView from './views/mainView.js';
import { Router, Route, Link } from 'react-router';
ReactDOM.render(<MainView />, document.getElementById('app'));<file_sep>import React from 'react';
export default class MainView extends React.Component{
constructor(props){
super(props);
this.state = {
input: '',
vowels: ['a', 'e', 'i', 'o', 'u', 'oo', 'y']
}
}
componentDidMount(){
console.log("Mounted!");
}
render(){
var component = this;
return(
<div className='main'>
<label>
Type in here
</label>
<br/>
<input
className='.input'
defaultValue={component.state.input}
onChange= {
e=>{component.state.input = e.currentTarget.value;
component.forceUpdate();}
}
/>
<div>
<h1>{component.convert(component.state.input)}</h1>
</div>
</div>
)
}
convert(str){
//return str.replace(/[aeiouAEIOU]/g, this.state.vowels[Math.floor(Math.random() * this.state.vowels.length)]);
var toRet = "";
for(var i = 0; i < str.length; i++){
if(/[aeiouAEIOU]/.test(str.charAt(i))) toRet += this.state.vowels[Math.floor(Math.random() * this.state.vowels.length)];
else toRet += str.charAt(i);
}
return toRet.toUpperCase();
}
} | 89bd4fa9a5ec3583fbf4cb2d9b1f6b3e3e29f343 | [
"JavaScript"
]
| 2 | JavaScript | npmcdn-to-unpkg-bot/speech | ad4f90987561bd6de380f97432aecac51e7a2525 | 6c4da68bac88bdf2c9f66f78148bbbd5f8227de2 |
refs/heads/master | <file_sep>import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/Home.vue';
import NotFound from '@/views/NotFound.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/docs',
name: 'Docs',
component: () => import('@/views/Docs'),
children: [
{
path: 'vt-burger',
name: 'VTBurger',
component: () => import('@/examples/Burger'),
},
{
path: 'vt-button',
name: 'VTButton',
component: () => import('@/examples/Button'),
},
{
path: 'vt-hoverbox',
name: 'VTHoverbox',
component: () => import('@/examples/Hoverbox'),
},
{
path: 'vt-loading',
name: 'VTLoading',
component: () => import('@/examples/Loading'),
},
{
path: 'vt-modal',
name: 'VTModal',
component: () => import('@/examples/Modal'),
},
{
path: 'vt-navbar',
name: 'VTNavbar',
component: () => import('@/examples/Navbar'),
},
{
path: 'vt-pagination',
name: 'VTPagination',
component: () => import('@/examples/Pagination'),
},
{
path: 'vt-popup',
name: 'VTPopup',
component: () => import('@/examples/Popup'),
},
{
path: 'vt-scrolltop',
name: 'VTScrolltop',
component: () => import('@/examples/Scrolltop'),
},
{
path: 'vt-searchbar',
name: 'VTSearchbar',
component: () => import('@/examples/Searchbar'),
},
{
path: 'vt-tooltip',
name: 'VTTooltip',
component: () => import('@/examples/Tooltip'),
},
{
path: 'vt-toggle',
name: 'VTToggle',
component: () => import('@/examples/Toggle'),
},
{
path: 'vt-video',
name: 'VTVideo',
component: () => import('@/examples/Video'),
},
{
path: 'vt-toast',
name: 'VTToast',
component: () => import('@/examples/Toast'),
},
{
path: 'vt-tabber',
name: 'vtTabber',
component: () => import('@/examples/Tabber'),
},
],
},
{ path: '/:pathMatch(.*)', component: NotFound },
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
router.beforeEach(to => {
// Update title
document.title = to.name + ' | Vuelity';
});
export default router;
<file_sep>import { reactive } from 'vue';
import router from '@/router';
const root = getComputedStyle(document.documentElement);
const global = reactive({
$primary: root.getPropertyValue('--primary'),
$white: root.getPropertyValue('--white'),
$black: root.getPropertyValue('--black'),
$lightGrey: root.getPropertyValue('--light-grey'),
$darkGrey: root.getPropertyValue('--dark-grey'),
$tooltipStyles: { width: '300px', minWidth: 'unset' },
$tooltipContainerStyles: { maxWidth: '100%' },
$tooltipPosition: 'right',
});
const tooltipResponsive = () => {
const tips = document.querySelectorAll('.vt__tooltip');
if (window.matchMedia('(max-width: 992px)').matches) {
global.$tooltipPosition = 'top';
// Overrule default function
setTimeout(() => {
tips.forEach(tip => {
const codepenTip = tip.innerHTML.includes('Codepen');
const columnTip = tip.parentElement.parentElement.className.includes('column');
const exampleTip = tip.parentElement.parentElement.className.includes('example');
if (codepenTip || columnTip || exampleTip) return;
tip.style.justifyContent = 'unset';
});
}, 0);
} else {
global.$tooltipPosition = 'right';
}
};
window.addEventListener('load', tooltipResponsive);
window.addEventListener('resize', tooltipResponsive);
router.afterEach(() => setTimeout(() => tooltipResponsive(), 0));
export default global;
<file_sep># Config for the Netlify Build Plugin: netlify-plugin-minify-html
[[plugins]]
package = "netlify-plugin-prerender-spa"
[plugins.inputs]
source = "dist" | 123945c9b06e8c5d38335d30fbfa867928d32dd2 | [
"JavaScript",
"TOML"
]
| 3 | JavaScript | Daniel-Knights/vuelity-docs | c3c9c0466da3df26186b040084014a5aade4c8cf | 6094ce28193520eee4278608f187bc04d0cbeb06 |
refs/heads/master | <repo_name>aobeuang/line-bot-exam-php<file_sep>/fc/bot.php
<?php // callback.php
function func1($param1, $param2)
{
echo $param1 . ', ' . $param2;
}
?><file_sep>/webhooks.php
<?php // callback.php
require "vendor/autoload.php";
require_once('vendor/linecorp/line-bot-sdk/line-bot-sdk-tiny/LINEBotTiny.php');
include_once 'fc/bot.php';
include_once 'profile.php';
$baseurl = "https://" . $_SERVER['SERVER_NAME'];
$accessToken = "<KEY>;//copy Channel access token ตอนที่ตั้งค่ามาใส่
$content = file_get_contents('php://input');
$arrayJson = json_decode($content, true);
$arrayHeader = array();
$arrayHeader[] = "Content-Type: application/json";
$arrayHeader[] = "Authorization: Bearer {$accessToken}";
//รับข้อความจากผู้ใช้
$message = $arrayJson['events'][0]['message']['text'];
#ตัวอย่าง Message Type "Text"
// if(strpos($message, 'ไอ้บอท') !== false){
//config bot
$botname = "นุ้งบอท";
if(strpos($message, $botname) !== false){
if(strpos($message, 'สวัสดี') || strpos($message, 'ดีจ้า') || strpos($message, 'หวัดดี') !== false){
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0]['type'] = "text";
$arrayPostData['messages'][0]['text'] = "สวัสดีจ้าาา";
replyMsg($arrayHeader,$arrayPostData);
}
#ตัวอย่าง Message Type "Sticker"
else if(strpos($message, 'ฝันดี') !== false){
// else if($message == "ฝันดี"){
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0]['type'] = "text";
$arrayPostData['messages'][0]['text'] = 'ฝันดี';
$arrayPostData['messages'][1]['type'] = "sticker";
$arrayPostData['messages'][1]['packageId'] = "2";
$arrayPostData['messages'][1]['stickerId'] = "46";
replyMsg($arrayHeader,$arrayPostData);
}
#ตัวอย่าง Message Type "Image"
else if(strpos($message, 'รูปน้องแมว') !== false){
$image_url = $baseurl.'/img/cats/'.rand(1,11).'.jpg';
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0]['type'] = "image";
$arrayPostData['messages'][0]['originalContentUrl'] = $image_url;
$arrayPostData['messages'][0]['previewImageUrl'] = $image_url;
replyMsg($arrayHeader,$arrayPostData);
}
#ตัวอย่าง Message Type "Location"
else if($message == "พิกัดสยามพารากอน"){
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0]['type'] = "location";
$arrayPostData['messages'][0]['title'] = "สยามพารากอน";
$arrayPostData['messages'][0]['address'] = "13.7465354,100.532752";
$arrayPostData['messages'][0]['latitude'] = "13.7465354";
$arrayPostData['messages'][0]['longitude'] = "100.532752";
replyMsg($arrayHeader,$arrayPostData);
}
#ตัวอย่าง Message Type "Text + Sticker ใน 1 ครั้ง"
else if(strpos($message, 'ลาก่อน') !== false){
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0] = array (
'type' => 'template',
'altText' => 'this is a buttons template',
'template' =>
array (
'type' => 'buttons',
'actions' =>
array (
0 =>
array (
'type' => 'postback',
'label' => 'sss',
'text' => 'นุ้งบอทฝันดี',
'data' => 'test=นุ้งบอทฝันดี',
),
),
'title' => 'Title',
'text' => 'Text',
),
);
replyMsg($arrayHeader,$arrayPostData);
}
else{
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0]['type'] = "text";
$arrayPostData['messages'][0]['text'] = "555";
replyMsg($arrayHeader,$arrayPostData);
}
}
#ตัวอย่าง Message Type "Location"
if(strpos($message, 'เทส') !== false){
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0] = gProfile($arrayJson['events'][0]['source']['userId']);
replyMsg($arrayHeader,$arrayPostData);
}
print_r(gProfile($arrayJson['events'][0]['source']['userId']));
$arrayPostData['replyToken'] = $arrayJson['events'][0]['replyToken'];
$arrayPostData['messages'][0]['type'] = "text";
$arrayPostData['messages'][0]['text'] = $arrayJson['events'][0]['postback']['data'];
replyMsg($arrayHeader,$arrayPostData);
function gProfile($userid)
{
$userss = json_decode(gUserdetail($userid));
$userdetail = array (
'type' => 'flex',
'altText' => 'Flex Message',
'contents' =>
array (
'type' => 'bubble',
'hero' =>
array (
'type' => 'image',
'url' => $userss->pictureUrl,
'size' => 'full',
'aspectRatio' => '20:13',
'aspectMode' => 'cover',
'action' =>
array (
'type' => 'uri',
'label' => 'Line',
'uri' => $userss->pictureUrl,
),
),
'footer' =>
array (
'type' => 'box',
'layout' => 'vertical',
'flex' => 0,
'spacing' => 'sm',
'contents' =>
array (
0 =>
array (
'type' => 'spacer',
'size' => 'sm',
),
1 =>
array (
'type' => 'text',
'text' => $userss->displayName,
'size' => 'xl',
'align' => 'center',
'gravity' => 'center',
'color' => '#050505',
),
2 =>
array (
'type' => 'text',
'text' => '!! Welcome !!',
'size' => 'xl',
'align' => 'center',
'gravity' => 'center',
'weight' => 'bold',
'color' => '#1200FF',
),
),
),
),
);
return $userdetail;
}
function replyMsg($arrayHeader,$arrayPostData){
$strUrl = "https://api.line.me/v2/bot/message/reply";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$strUrl);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrayHeader);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($arrayPostData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close ($ch);
}
// func1('Hello', 'world');
//echo "https://" . $_SERVER['SERVER_NAME'] ;
exit;
?><file_sep>/profile.php
<?php
function gUserdetail($userid)
{
# code...
$access_token = '<KEY>';
$url = 'https://api.line.me/v2/bot/profile/'.$userid;
$headers = array('Authorization: Bearer ' . $access_token);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
// echo $ss->userId;
// echo $ss->displayName;
// echo $ss->pictureUrl;
}
?> | ca17b3fc5fbcdcd7fa34cf39be27f2c66f17021e | [
"PHP"
]
| 3 | PHP | aobeuang/line-bot-exam-php | eac966f33ca4523bb722a74c261e142533e53004 | 734f1accbde1f422904b21c618b1073373d36450 |
refs/heads/master | <file_sep>package com.example.stackoverflowclient.login;
import android.content.Context;
import android.net.Uri;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.example.stackoverflowclient.utils.PreferenceHelper;
import com.example.stackoverflowclient.utils.StringConstants;
class LoginInteractor implements ILoginInterface.ILoginInteractor {
private PreferenceHelper preference;
private LoginPresenter presenter;
LoginInteractor(Context context, LoginPresenter presenter) {
preference = PreferenceHelper.getInstance(context);
this.presenter = presenter;
}
@Override
public LoginWebViewClient getWebViewClientInstance() {
return new LoginWebViewClient();
}
class LoginWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
Uri uri = request.getUrl();
return shouldOverrideUrlLoading(uri.toString());
}
private boolean shouldOverrideUrlLoading(final String url) {
return url.contains("access_token");
}
public void onPageFinished(WebView view, String url) {
if (url.contains("access_token")) {
presenter.onSuccess();
String accessToken = getAccessTokenFromURL(url);
storeDataInSharedPreference(StringConstants.ACCESS_TOKEN, accessToken);
}
}
}
private String getAccessTokenFromURL(String url) {
String[] separated = url.split("=");
return separated[1].trim();
}
@Override
public void storeDataInSharedPreference(String key, String accessToken) {
preference.put(key, accessToken);
}
}
<file_sep>package com.example.stackoverflowclient.feed.viewmodel;
import com.example.stackoverflowclient.base.BaseConstants;
import com.example.stackoverflowclient.feed.datasource.ItemDataSource;
import com.example.stackoverflowclient.feed.datasource.ItemDataSourceFactory;
import com.example.stackoverflowclient.model.ItemModel;
import com.example.stackoverflowclient.network.ApiService;
import com.example.stackoverflowclient.network.NetworkState;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
public class ItemViewModel extends ViewModel {
private LiveData<PagedList<ItemModel>> itemPagedList;
private LiveData<NetworkState> networkStateLiveData;
private LiveData<ItemDataSource> dataSource;
private Executor executor;
public ItemViewModel(ApiService apiService, String accessToken, String serviceName, String sortType) {
executor = Executors.newFixedThreadPool(5);
ItemDataSourceFactory factory = new ItemDataSourceFactory(apiService, accessToken, serviceName, sortType, executor);
dataSource = factory.getMutableLiveData();
networkStateLiveData = Transformations.switchMap(factory.getMutableLiveData(), new Function<ItemDataSource, LiveData<NetworkState>>() {
@Override
public LiveData<NetworkState> apply(ItemDataSource source) {
return source.getNetworkState();
}
});
PagedList.Config pageConfig = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(BaseConstants.PAGE_SIZE)
.build();
itemPagedList = (new LivePagedListBuilder<Integer, ItemModel>(factory, pageConfig))
.setFetchExecutor(executor)
.build();
}
public LiveData<PagedList<ItemModel>> getItemPagedList() {
return itemPagedList;
}
public LiveData<NetworkState> getNetworkStateLiveData() {
return networkStateLiveData;
}
}
<file_sep>package com.example.stackoverflowclient.userquestions;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.stackoverflowclient.R;
import com.example.stackoverflowclient.base.BaseActivity;
import com.example.stackoverflowclient.base.BaseConstants;
import com.example.stackoverflowclient.model.QuestionsResponseModel;
import com.example.stackoverflowclient.network.ApiResponse;
import com.example.stackoverflowclient.network.ApiResponseListener;
import com.example.stackoverflowclient.network.ApiService;
import com.example.stackoverflowclient.network.ErrorModel;
import com.example.stackoverflowclient.network.RestApiClient;
import com.example.stackoverflowclient.utils.PreferenceHelper;
import com.example.stackoverflowclient.utils.StringConstants;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
public class UserQuestionsActivity extends BaseActivity {
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.tv_error)
TextView errorTextView;
ApiService apiService;
PreferenceHelper preference;
private String accessToken;
QuestionsAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_questions);
ButterKnife.bind(this);
apiService = RestApiClient.getClientInstance().getApiService();
preference = PreferenceHelper.getInstance(this);
accessToken = preference.get(StringConstants.ACCESS_TOKEN);
setupRecyclerView();
sendRequest();
}
private void setupRecyclerView() {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
}
private void sendRequest() {
Call<QuestionsResponseModel> call = apiService.getQuestionsByUser(accessToken, BaseConstants.KEY, BaseConstants.ORDER_DESCENDING, BaseConstants.SORT_BY_ACTIVITY, BaseConstants.SITE, BaseConstants.FILTER);
showProgress(this, "Loading...");
ApiResponse.sendRequest(call, BaseConstants.QUESTIONS_BY_USER_API_SERVICE, new ApiResponseListener() {
@Override
public void onSuccess(String strApiName, Object response) {
hideProgress();
QuestionsResponseModel model = (QuestionsResponseModel) response;
if (!model.getItems().isEmpty()) {
errorTextView.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
adapter = new QuestionsAdapter(UserQuestionsActivity.this, model);
recyclerView.setAdapter(adapter);
} else {
errorTextView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
errorTextView.setText("You have not posted any questions");
}
}
@Override
public void onError(String strApiName, ErrorModel errorModel) {
hideProgress();
errorTextView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
errorTextView.setText(errorModel.getError_message());
}
@Override
public void onFailure(String strApiName, String message) {
hideProgress();
errorTextView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
errorTextView.setText(message);
}
});
}
}
<file_sep>package com.example.stackoverflowclient.network
import java.io.Serializable
data class ErrorModel(
var error_id: Int = 0,
var error_message: String = "",
var error_name: String = "",
var apiName: String = ""
) : Serializable<file_sep>package com.example.stackoverflowclient.network;
import com.example.stackoverflowclient.base.BaseConstants;
import com.example.stackoverflowclient.model.QuestionsResponseModel;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface ApiService {
/**
* Logout request - Since there is no proper way to logout, Access token is invalidated and cache is cleared
*
* @param accessToken Current user's access token
* @return json object with empty "items" object
*/
@GET(BaseConstants.ACCESS_TOKEN_INVALIDATION_END_POINT)
Call<QuestionsResponseModel> invalidateAccessToken(@Path("accessTokens") String accessToken);
@GET(BaseConstants.QUESTIONS_END_POINT)
Call<QuestionsResponseModel> getQuestionsForLoggedInUser(
@Query(value = "access_token", encoded = true) String accessToken,
@Query(value = "key", encoded = true) String key,
@Query("page") int page,
@Query("pagesize") int pageSize,
@Query("order") String order,
@Query("sort") String sortCondition,
@Query("site") String site,
@Query(value = "filter", encoded = true) String filter
);
@GET(BaseConstants.QUESTIONS_END_POINT)
Call<QuestionsResponseModel> getQuestionsForAll(
@Query("page") int page,
@Query("pagesize") int pageSize,
@Query("order") String order,
@Query("sort") String sortCondition,
@Query("site") String site,
@Query(value = "filter", encoded = true) String filter
);
@GET(BaseConstants.USER_QUESTIONS_END_POINT)
Call<QuestionsResponseModel> getQuestionsByUser(
@Query(value = "access_token", encoded = true) String accessToken,
@Query(value = "key", encoded = true) String key,
@Query("order") String order,
@Query("sort") String sortCondition,
@Query("site") String site,
@Query(value = "filter", encoded = true) String filter
);
}
<file_sep>package com.example.stackoverflowclient.utils;
import android.content.Context;
import android.content.SharedPreferences;
public class PreferenceHelper {
private static PreferenceHelper preference;
private SharedPreferences sharedPreferences;
private static String fileName = "SOCPreference";
private SharedPreferences.Editor editor;
public PreferenceHelper(Context context) {
sharedPreferences = context.getApplicationContext().getSharedPreferences(fileName, Context.MODE_PRIVATE);
}
public static PreferenceHelper getInstance(Context context) {
if (null == preference)
preference = new PreferenceHelper(context);
return preference;
}
public void put(String key, String value) {
editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public String get(String key) {
return sharedPreferences.getString(key, null);
}
public void putInt(String key, int value) {
editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public int getInt(String key) {
return sharedPreferences.getInt(key, 0);
}
public void clear() {
editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
public void remove() {
editor = sharedPreferences.edit();
editor.remove(fileName);
editor.commit();
}
}
<file_sep>package com.example.stackoverflowclient.model
import java.io.Serializable
data class QuestionsResponseModel(
val has_more: Boolean = false,
val items: List<ItemModel> = emptyList(),
val quota_max: Int = 10000,
val quota_remaining: Int = 1
) : Serializable
data class ItemModel(
val tags: List<String> = emptyList(),
val owner: OwnerModel? = null,
val is_answered: Boolean = false,
val view_count: Int = 0,
val up_vote_count: Int = 0,
val answer_count: Int = 0,
val creation_date: Long = 0,
val question_id: Int = 0,
val link: String = "",
val title: String = ""
) : Serializable
data class OwnerModel(
val display_name: String = "",
val link: String = "",
val profile_image: String = "",
val user_id: Int = 0,
val user_type: String = ""
) : Serializable<file_sep>package com.example.stackoverflowclient.model
import java.io.Serializable
import java.security.acl.Owner
data class AnswerModel(
var owner: Owner? = null,
var accepted: Boolean? = false,
var up_vote_count: Int? = 0,
var is_accepted: Boolean? = false,
var score: Int? = 0,
var last_activity_date: Long? = 0,
var creation_date: Long? = 0,
var answer_id: Int? = 0,
var question_id: Int? = 0,
var last_edit_date: Int? = null
) : Serializable | 3d784043d5637f61e659cffc6c9a1c2dd266d01d | [
"Java",
"Kotlin"
]
| 8 | Java | AkshayaSivakumar/StackOverflowClient | d031c7ea06772a4a807092ca9306c4608be4d0aa | 6aa7a039c8566c2f42a76166bd937f83dddc1d21 |
refs/heads/master | <repo_name>zhj0811/gm-crypto<file_sep>/go.mod
module github.com/zhj0811/gm-crypto
go 1.14
require (
github.com/golang/protobuf v1.4.2
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3
google.golang.org/grpc v1.15.0
)
<file_sep>/tls/credentials/credentials_test.go
package credentials
import (
"context"
"fmt"
"io/ioutil"
"log"
"net"
"testing"
"github.com/zhj0811/gm-crypto/tls"
"github.com/zhj0811/gm-crypto/tls/credentials/echo"
"github.com/zhj0811/gm-crypto/x509"
"google.golang.org/grpc"
)
const (
port = ":50051"
address = "localhost:50051"
)
var DefaultTLSCipherSuites = []uint16{
tls.GMTLS_SM2_WITH_SM4_SM3,
}
var end chan bool
type server struct{}
func (s *server) Echo(ctx context.Context, req *echo.EchoRequest) (*echo.EchoResponse, error) {
return &echo.EchoResponse{Result: req.Req}, nil
}
const cacrt = "../gmcert/ca.crt"
const cakey = "../gmcert/ca.key"
const servercrt = "../gmcert/server.crt"
const serverkey = "../gmcert/server.key"
const clientcrt = "../gmcert/client.crt"
const clientkey = "../gmcert/client.key"
func serverRun() {
cert, err := tls.LoadX509KeyPair(servercrt, serverkey)
if err != nil {
log.Fatal(err)
}
certPool := x509.NewCertPool()
cacert, err := ioutil.ReadFile(cacrt)
if err != nil {
log.Fatal(err)
}
certPool.AppendCertsFromPEM(cacert)
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("fail to listen: %v", err)
}
creds := NewTLS(&tls.Config{
GMSupport: &tls.GMSupport{},
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{cert,cert},
ClientCAs: certPool,
CipherSuites: DefaultTLSCipherSuites,
})
s := grpc.NewServer(grpc.Creds(creds))
echo.RegisterEchoServer(s, &server{})
err = s.Serve(lis)
if err != nil {
log.Fatalf("Serve: %v", err)
}
}
func clientRun() {
cert, err := tls.LoadX509KeyPair(clientcrt, clientkey)
if err != nil {
log.Fatal(err)
}
certPool := x509.NewCertPool()
cacert, err := ioutil.ReadFile(cacrt)
if err != nil {
log.Fatal(err)
}
certPool.AppendCertsFromPEM(cacert)
creds := NewTLS(&tls.Config{
GMSupport: &tls.GMSupport{},
ServerName: "tls.testserver.com",
Certificates: []tls.Certificate{cert,cert},
RootCAs: certPool,
CipherSuites: DefaultTLSCipherSuites,
})
conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds))
if err != nil {
log.Fatalf("cannot to connect: %v", err)
}
defer conn.Close()
c := echo.NewEchoClient(conn)
echoTest(c)
end <- true
}
func echoTest(c echo.EchoClient) {
r, err := c.Echo(context.Background(), &echo.EchoRequest{Req: "###hello###"})
if err != nil {
log.Fatalf("failed to echo: %v", err)
}
fmt.Printf("%s\n", r.Result)
}
func Test(t *testing.T) {
end = make(chan bool, 64)
go serverRun()
go clientRun()
<-end
}
<file_sep>/tls/tls_test.go
package tls
import (
"bufio"
"github.com/zhj0811/gm-crypto/x509"
"io/ioutil"
"log"
"net"
"testing"
)
var DefaultTLSCipherSuites = []uint16{
GMTLS_SM2_WITH_SM4_SM3,
}
var (
AuthType = RequestClientCert //fabric单证书模式
//AuthType = RequireAndVerifyClientCert //fabric双证书模式
SERVER_CA = "./gmcert/ca.crt" //服务端根证书
SERVER_SIGN_CERT = "./gmcert/server.crt" //服务端签名证书
SERVER_SIGN_KEY = "./gmcert/server.key" //服务端签名私钥
SERVER_ENC_CERT = "./gmcert/server.crt" //服务端加密证书
SERVER_ENC_KEY = "./gmcert/server.key" //服务端加密私钥
CLIENT_CA = "./gmcert/ca.crt" //客户端根证书
CLIENT_SIGN_CERT = "./gmcert/client.crt" //客户端签名证书
CLIENT_SIGN_KEY = "./gmcert/client.key" //客户端签名私钥
CLIENT_ENC_CERT = "./gmcert/client.crt" //客户端加密证书
CLIENT_ENC_KEY = "./gmcert/client.key" //客户端签名私钥
)
func TestTLS(t *testing.T) {
signcert, err := LoadX509KeyPair(SERVER_SIGN_CERT, SERVER_SIGN_KEY)
if err != nil {
log.Println(err)
return
}
//enccert, err := LoadX509KeyPair(SERVER_ENC_CERT, SERVER_ENC_KEY)
// //if err != nil {
// // log.Println(err)
// // return
// //}
caPem, err := ioutil.ReadFile(SERVER_CA)
if err != nil {
log.Fatalf("Failed to load ca cert %v", err)
}
certpool := x509.NewCertPool()
certpool.AppendCertsFromPEM(caPem)
c := &Config{
GMSupport: &GMSupport{},
ClientAuth: AuthType,
Certificates: []Certificate{signcert /*, enccert*/},
ClientCAs: certpool,
CipherSuites: DefaultTLSCipherSuites,
}
ln, err := Listen("tcp", ":8080", c)
if err != nil {
log.Println(err)
return
}
log.Printf("Start to server address:%v clientAuthType=%v\n", ln.Addr(),AuthType)
go client()
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
r := bufio.NewReader(conn)
for {
msg, err := r.ReadString('\n')
if err != nil {
log.Println(err)
return
}
log.Println(msg)
n, err := conn.Write([]byte("server pong!\n"))
if err != nil {
log.Println(n, err)
return
}
}
}
func client() {
caPem, err := ioutil.ReadFile(CLIENT_CA)
if err != nil {
log.Fatal(err)
}
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(caPem) {
log.Fatal("credentials: failed to append certificates")
}
signcert, err := LoadX509KeyPair(CLIENT_SIGN_CERT, CLIENT_SIGN_KEY)
if err != nil {
log.Fatal("Failed to Load client keypair")
}
//enccert, err := LoadX509KeyPair(CLIENT_ENC_CERT, CLIENT_ENC_KEY)
//if err != nil {
// log.Fatal("Failed to Load client keypair")
//}
c := &Config{
ServerName: "tls.testserver.com",
GMSupport: &GMSupport{},
Certificates: []Certificate{signcert /*, enccert*/},
RootCAs: cp,
CipherSuites: DefaultTLSCipherSuites,
//InsecureSkipVerify: true, // Client verifies server's cert if false, else skip.
}
serverAddress := "127.0.0.1:8080"
log.Printf("start client connect %s\n", serverAddress)
conn, err := Dial("tcp", serverAddress, c)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
n, err := conn.Write([]byte("client write ping!\n"))
if err != nil {
log.Println(n, err)
return
}
buf := make([]byte, 100)
n, err = conn.Read(buf)
if err != nil {
log.Println(n, err)
return
}
log.Println(string(buf[:n]))
}
| 846989dbe2276069f754c0179d9f1b9d2751b2b2 | [
"Go",
"Go Module"
]
| 3 | Go Module | zhj0811/gm-crypto | 4415ab9704b001c8cbed5ca5315440da1d5d2fb7 | 4ce953449bd628faddfa20ffd8aaa29583ad5871 |
refs/heads/main | <repo_name>Asmodeus96/MyDiscographyList<file_sep>/MyDiscographyList/Model/ArtistStatusModel.cs
using System.ComponentModel;
using System.Windows.Media;
namespace MyDiscographyList.Model
{
public class ArtistStatusModel : INotifyPropertyChanged
{
private int _statusId;
private string _statusLabel;
private Brush _statusColor;
private int _nbOfStatus;
public int StatusId { get { return _statusId; } set { _statusId = value; OnPropertyChanged("StatusId"); } }
public string StatusLabel { get { return _statusLabel; } set { _statusLabel = value; OnPropertyChanged("StatusLabel"); } }
public Brush StatusColor { get { return _statusColor; } set { _statusColor = value; OnPropertyChanged("StatusColor"); } }
public int NbOfStatus { get { return _nbOfStatus; } set { _nbOfStatus = value; OnPropertyChanged("NbOfStatus"); } }
#region INotifyPropertyChanged Artis
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
<file_sep>/MyDiscographyList/View/AddArtistModalWindowView.xaml.cs
using MyDiscographyList.ViewModel;
using System;
using System.Windows;
namespace MyDiscographyList.View
{
public partial class AddArtistModalWindowView : Window
{
public AddArtistModalWindowView()
{
InitializeComponent();
AddArtistViewModel vm = new AddArtistViewModel();
this.DataContext = vm;
vm.CloseAction = new Action(this.Close);
}
}
}
<file_sep>/MyDiscographyList/ViewModel/DeleteArtistViewModel.cs
using DataAccessLibrary;
using MyDiscographyList.Command;
using MyDiscographyList.Model;
using System;
using System.Windows.Input;
namespace MyDiscographyList.ViewModel
{
class DeleteArtistViewModel
{
private ArtistModel _artist;
private ICommand _deleteArtistCommand;
private readonly bool canExecute = true;
public DeleteArtistViewModel(ArtistModel artist)
{
Artist = artist;
DeleteArtistCommand = new RelayCommand(DeleteArtist, param => this.canExecute);
}
public ArtistModel Artist { get { return _artist; } set { _artist = value; } }
public Action CloseAction { get; set; }
public ICommand DeleteArtistCommand { get { return _deleteArtistCommand; } set { _deleteArtistCommand = value; } }
public void DeleteArtist(Object obj)
{
DataAccess.DeleteArtist(_artist); CloseAction();
CloseAction();
}
}
}
<file_sep>/README.md
# MyDiscographyList
<file_sep>/MyDiscographyList/Extention/ArtistRoutedEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace MyDiscographyList.Extention
{
public class ArtistRoutedEventArgs : RoutedEventArgs
{
private readonly int _artistId;
public ArtistRoutedEventArgs(int artistId)
{
this._artistId = artistId;
}
public int ArtistID
{
get { return _artistId; }
}
}
}
<file_sep>/MyDiscographyList/ViewModel/ArtistDetailsViewModel.cs
using DataAccessLibrary;
using MyDiscographyList.Command;
using MyDiscographyList.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using SpotifyAPI.Web;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace MyDiscographyList.ViewModel
{
class ArtistDetailsViewModel : INotifyPropertyChanged
{
private ArtistModel _artist;
private ArtistModel _artistSelected;
private ObservableCollection<ArtistModel> _artistsRecommandationList;
private ObservableCollection<ArtistModel> _artistsRelatedList;
private List<ArtistStatusModel> _artistStatusList;
private List<ArtistScoreModel> _artistScoreList;
private string _deezerId;
private string _spotifyId;
private bool _showRelatedArtitList;
private bool _noRelatedToAdd;
private ICommand _updateArtistUpToDateCommand;
private ICommand _changeArtistNameCommand;
private ICommand _changeArtistAliasCommand;
private ICommand _getDeezerRecommandationCommand;
private ICommand _getSpotifyRecommandationCommand;
private ICommand _insertSelectedArtistCommand;
private readonly bool canExecute = true;
public ArtistDetailsViewModel(int id)
{
Artist = DataAccess.GetArtistById(id);
ArtistStatuses = DataAccess.GetStatusList();
ArtistScores = DataAccess.GetScoreList();
ArtistSelected = new ArtistModel();
ArtistsRecommandationList = DataAccess.GetRelatedArtist(Artist.ArtistId);
ArtistsRelatedList = new ObservableCollection<ArtistModel>();
ShowRelatedArtistList = false;
NoRelatedToAdd = false;
UpdateArtistUpToDateCommand = new RelayCommand(UpdateArtistUpToDate, param => this.canExecute);
ChangeArtistNameCommand = new RelayCommand(ChangeArtistName, param => this.canExecute);
ChangeArtistAliasCommand = new RelayCommand(ChangeArtistAlias, param => this.canExecute);
GetDeezerRecommandationCommand = new RelayCommand(GetDeezerRecommandation, param => this.canExecute);
GetSpotifyRecommandationCommand = new RelayCommand(GetSpotifyRecommandation, param => this.canExecute);
InsertSelectedArtistCommand = new RelayCommand(InsertSelectedArtist, param => this.canExecute);
}
public ArtistModel Artist { get { return _artist; } set { _artist = value; } }
public ObservableCollection<ArtistModel> ArtistsRecommandationList { get { return _artistsRecommandationList; } set { _artistsRecommandationList = value; } }
public ObservableCollection<ArtistModel> ArtistsRelatedList { get { return _artistsRelatedList; } set { _artistsRelatedList = value; } }
public ArtistModel ArtistSelected { get { return _artistSelected; } set { _artistSelected = value; } }
public List<ArtistStatusModel> ArtistStatuses { get { return _artistStatusList; } set { _artistStatusList = value; } }
public List<ArtistScoreModel> ArtistScores { get { return _artistScoreList; } set { _artistScoreList = value; } }
public string DeezerId { get { return _deezerId; } set { _deezerId = value; } }
public string SpotifyId { get { return _spotifyId; } set { _spotifyId = value; } }
public bool ShowRelatedArtistList { get { return _showRelatedArtitList; } set { _showRelatedArtitList = value; OnPropertyChanged("ShowRelatedArtistList"); } }
public bool NoRelatedToAdd { get { return _noRelatedToAdd; } set { _noRelatedToAdd = value; OnPropertyChanged("NoRelatedToAdd"); } }
public ICommand UpdateArtistUpToDateCommand { get { return _updateArtistUpToDateCommand; } set { _updateArtistUpToDateCommand = value; } }
public ICommand ChangeArtistNameCommand { get { return _changeArtistNameCommand; } set { _changeArtistNameCommand = value; } }
public ICommand ChangeArtistAliasCommand { get { return _changeArtistAliasCommand; } set { _changeArtistAliasCommand = value; } }
public ICommand GetDeezerRecommandationCommand { get { return _getDeezerRecommandationCommand; } set { _getDeezerRecommandationCommand = value; } }
public ICommand GetSpotifyRecommandationCommand { get { return _getSpotifyRecommandationCommand; } set { _getSpotifyRecommandationCommand = value; } }
public ICommand InsertSelectedArtistCommand { get { return _insertSelectedArtistCommand; } set { _insertSelectedArtistCommand = value; } }
public void ChangeArtistName(Object obj) { DataAccess.UpdateArtistName(_artist); }
public void ChangeArtistAlias(Object obj) { DataAccess.UpdateArtistAlias(_artist); }
public void UpdateArtistUpToDate(Object obj) { DataAccess.UpdateArtistUpToDate(_artist); }
public void UpdatedArtistStatus() { DataAccess.UpdateArtistStatus(_artist); }
public void UpdateArtistScore() { DataAccess.UpdateArtistScore(_artist); }
public async void GetDeezerRecommandation(Object obj)
{
if (!string.IsNullOrEmpty(DeezerId))
{
List<string> nameList = new List<string>();
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.deezer.com/artist/" + DeezerId + "/related"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json");
var response = await httpClient.SendAsync(request);
var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);
foreach (var name in json["data"])
{
nameList.Add(name["name"].ToString());
}
}
}
UpdateRelatedList(nameList);
}
}
public async void GetSpotifyRecommandation(Object obj)
{
if (!string.IsNullOrEmpty(SpotifyId))
{
List<string> nameList = new List<string>();
var config = SpotifyClientConfig.CreateDefault();
var request = new ClientCredentialsRequest("<KEY>", "<KEY>");
var response = await new OAuthClient(config).RequestToken(request);
var spotify = new SpotifyClient(config.WithToken(response.AccessToken));
var related = await spotify.Artists.GetRelatedArtists(SpotifyId);
foreach (var name in related.Artists)
{
nameList.Add(name.Name.ToString());
}
UpdateRelatedList(nameList);
}
}
public void UpdateRelatedList(List<string> nameList)
{
foreach (var artist in ArtistsRecommandationList)
{
nameList.Remove(artist.ArtistName);
nameList.Remove(artist.ArtistAlias);
}
if (nameList.Count > 0)
{
var relatedArtistRegistred = DataAccess.CheckRelatedArtists(nameList);
foreach (var artist in relatedArtistRegistred)
{
ArtistsRelatedList.Add(artist);
}
foreach (var name in ArtistsRelatedList)
{
nameList.Remove(name.ArtistName);
nameList.Remove(name.ArtistAlias);
}
}
foreach (var name in nameList)
{
ArtistsRelatedList.Add(new ArtistModel() {ArtistId = -1, ArtistName = name, ArtistScore = ArtistScores[0], ArtistStatus = ArtistStatuses[5], ArtistAlias = "", ArtistUpToDate = false });
}
if (ArtistsRelatedList.Count > 0)
{
ShowRelatedArtistList = true;
NoRelatedToAdd = false;
}
else
{
ShowRelatedArtistList = false;
NoRelatedToAdd = true;
}
}
public void UpdateSelectedArtistStatus() { DataAccess.UpdateArtistStatus(_artistSelected); }
public void UpdateSelectedArtistScore() { DataAccess.UpdateArtistScore(_artistSelected); }
public void InsertSelectedArtist(Object obj)
{
int insertedId;
if (ArtistSelected.ArtistId < 0)
{
insertedId = DataAccess.AddArtist(_artistSelected);
_artistSelected.ArtistId = insertedId;
}
else
{
insertedId = ArtistSelected.ArtistId;
}
DataAccess.AddRecommandation(Artist.ArtistId, insertedId);
ArtistsRelatedList.Remove(_artistSelected);
if (ArtistsRelatedList.Count > 0)
{
ShowRelatedArtistList = true;
NoRelatedToAdd = false;
}
else
{
ShowRelatedArtistList = false;
NoRelatedToAdd = true;
}
ArtistsRecommandationList.Add(DataAccess.GetArtistById(insertedId));
}
public void DeleteSelectedArtist() { ArtistsRecommandationList.Remove(ArtistSelected); }
#region INotifyPropertyChanged Artist
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
<file_sep>/MyDiscographyList/ViewModel/AddArtistViewModel.cs
using DataAccessLibrary;
using MyDiscographyList.Command;
using MyDiscographyList.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
namespace MyDiscographyList.ViewModel
{
public class AddArtistViewModel
{
private ArtistModel _artist;
private List<ArtistStatusModel> _artistStatusList;
private List<ArtistScoreModel> _artistScoreList;
private ICommand _addArtistCommand;
private readonly bool canExecute = true;
public AddArtistViewModel()
{
Artist = new ArtistModel();
ArtistStatuses = DataAccess.GetStatusList();
ArtistScores = DataAccess.GetScoreList();
Artist.ArtistStatus = ArtistStatuses[5];
Artist.ArtistScore = ArtistScores[0];
Artist.ArtistUpToDate = false;
Artist.ArtistAlias = "";
AddArtistCommand = new RelayCommand(AddArtist, param => this.canExecute);
}
public ArtistModel Artist { get { return _artist; } set { _artist = value; } }
public List<ArtistStatusModel> ArtistStatuses { get { return _artistStatusList; } set { _artistStatusList = value; } }
public List<ArtistScoreModel> ArtistScores { get { return _artistScoreList; } set { _artistScoreList = value; } }
public Action CloseAction { get; set; }
public ICommand AddArtistCommand { get { return _addArtistCommand; } set { _addArtistCommand = value; } }
public void AddArtist(Object obj) { DataAccess.AddArtist(_artist); CloseAction(); }
}
}
<file_sep>/MyDiscographyList/ViewModel/ArtistListViewModel.cs
using DataAccessLibrary;
using MyDiscographyList.Command;
using MyDiscographyList.Enum;
using MyDiscographyList.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace MyDiscographyList.ViewModel
{
class ArtistListViewModel
{
private ObservableCollection<ArtistModel> _artistList;
private List<ArtistStatusModel> _artistStatusList;
private List<ArtistScoreModel> _artistScoreList;
private List<string> _firstLetterFilterList;
private ArtistModel _artistSelected;
private ICommand _updateArtistUpToDateCommand;
private ICommand _firstLetterFilterCommand;
private readonly bool canExecute = true;
private TypeListEnum _typeList;
public ArtistListViewModel(TypeListEnum type, string filter = "All")
{
ArtistStatuses = DataAccess.GetStatusList();
ArtistScores = DataAccess.GetScoreList();
TypeList = type;
ArtistList = DataAccess.GetArtistList(TypeList, filter);
FirstLetterFilterList = Enumerable.Range('A', 26).Select(x => (char) x).Select(c => c.ToString()).ToList();
FirstLetterFilterList.Insert(0, "All");
FirstLetterFilterList.Add("0-9");
FirstLetterFilterList.Add("*");
ArtistSelected = new ArtistModel();
UpdateArtistUpToDateCommand = new RelayCommand(UpdateArtistUpToDate, param => canExecute);
FirstLetterFilterCommand = new RelayCommand(FirstLetterFilter, param => canExecute);
}
public ObservableCollection<ArtistModel> ArtistList { get { return _artistList; } set { _artistList = value; }}
public List<ArtistStatusModel> ArtistStatuses { get { return _artistStatusList; } set { _artistStatusList = value; }}
public List<ArtistScoreModel> ArtistScores { get { return _artistScoreList; } set { _artistScoreList = value; }}
public List<string> FirstLetterFilterList { get { return _firstLetterFilterList; } set { _firstLetterFilterList = value; } }
public ArtistModel ArtistSelected { get { return _artistSelected; } set { _artistSelected = value; }}
public TypeListEnum TypeList { get { return _typeList; } set { _typeList = value; } }
public ICommand UpdateArtistUpToDateCommand { get { return _updateArtistUpToDateCommand; } set { _updateArtistUpToDateCommand = value; }}
public ICommand FirstLetterFilterCommand { get { return _firstLetterFilterCommand; } set { _firstLetterFilterCommand = value; }}
public void UpdateArtistUpToDate(Object obj) { DataAccess.UpdateArtistUpToDate(_artistSelected); }
public void UpdateSelectedArtistStatus()
{
DataAccess.UpdateArtistStatus(ArtistSelected);
switch (TypeList)
{
case TypeListEnum.Listened:
if (_artistSelected.ArtistStatus.StatusId == 6)
{
ArtistList.Remove(_artistSelected);
}
break;
case TypeListEnum.Unlistened:
if (_artistSelected.ArtistStatus.StatusId == 6)
{
ArtistList.Add(_artistSelected);
}
ArtistList.Remove(_artistSelected);
break;
}
}
public void UpdateSelectedArtistScore() { DataAccess.UpdateArtistScore(ArtistSelected); }
public void DeleteSelectedArtist() { ArtistList.Remove(ArtistSelected); }
public void FirstLetterFilter(Object obj)
{
ArtistList.Clear();
ObservableCollection<ArtistModel> listTmp = DataAccess.GetArtistList(TypeList, obj.ToString());
foreach (var tmp in listTmp)
{
ArtistList.Add(tmp);
}
}
}
}
<file_sep>/MyDiscographyList/ViewModel/DashboardViewModel.cs
using DataAccessLibrary;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using SciChart.Charting.Common.Helpers;
using SciChart.Charting.Visuals;
using SciChart.Core.Extensions;
using System.ComponentModel;
using MyDiscographyList.Model;
namespace MyDiscographyList.ViewModel
{
class DashboardViewModel
{
private readonly ObservableCollection<IPieSegmentViewModel> _donutModels;
private List<ArtistStatusModel> _artistStatusList;
public DashboardViewModel()
{
_artistStatusList = DataAccess.CountStatusDisco();
_donutModels = new ObservableCollection<IPieSegmentViewModel>();
foreach(var status in _artistStatusList)
{
_donutModels.Add(new DonutSegmentViewModel { Value = status.NbOfStatus, Name = status.StatusLabel, Stroke = ToShade(status.StatusColor.ExtractColor(), 0.8), Fill = ToGradient(status.StatusColor.ExtractColor()), StrokeThickness = 2 });
}
}
// Binds to ItemsSource of Donut Chart
public ObservableCollection<IPieSegmentViewModel> DonutModels { get { return _donutModels; } }
// Helper functions to create nice brushes out of colors
private Brush ToGradient(Color baseColor)
{
return new LinearGradientBrush(new GradientStopCollection()
{
new GradientStop(baseColor, 0.0),
new GradientStop(ToShade(baseColor, 0.7).Color, 1.0),
});
}
private SolidColorBrush ToShade(Color baseColor, double shade)
{
return new SolidColorBrush(Color.FromArgb(baseColor.A, (byte)(baseColor.R * shade), (byte)(baseColor.G * shade), (byte)(baseColor.B * shade)));
}
}
public class DonutSegmentViewModel : INotifyPropertyChanged, IPieSegmentViewModel
{
public double _Value;
public double _Percentage;
public bool _IsSelected;
public string _Name;
public Brush _Fill;
public Brush _Stroke;
public double _strokeThickness;
public double StrokeThickness { get { return _strokeThickness; } set { _strokeThickness = value; OnPropertyChanged("StrokeThickness"); }}
public double Value { get { return _Value; } set { _Value = value; OnPropertyChanged("Value"); }}
public double Percentage { get { return _Percentage; } set { _Percentage = value; OnPropertyChanged("Percentage"); }}
public bool IsSelected { get { return _IsSelected; } set { _IsSelected = value; OnPropertyChanged("IsSelected"); }}
public string Name { get { return _Name; } set { _Name = value; OnPropertyChanged("Name"); }}
public Brush Fill { get { return _Fill; } set { _Fill = value; OnPropertyChanged("Fill"); }}
public Brush Stroke { get { return _Stroke; } set { _Stroke = value; OnPropertyChanged("Stroke"); }}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
<file_sep>/MyDiscographyList/View/DeleteArtistConfirmView.xaml.cs
using MyDiscographyList.Model;
using MyDiscographyList.ViewModel;
using System;
using System.Windows;
namespace MyDiscographyList.View
{
public partial class DeleteArtistConfirmView : Window
{
public event EventHandler ArtistDeleted;
public DeleteArtistConfirmView(ArtistModel artist)
{
InitializeComponent();
DeleteArtistViewModel vm = new DeleteArtistViewModel(artist);
DataContext = vm;
vm.CloseAction = new Action(this.Close);
}
private void DeleteArtist(object sender, RoutedEventArgs e)
{
RoutedEventArgs artistREA = new RoutedEventArgs();
ArtistDeleted(this, artistREA);
}
}
}
<file_sep>/MyDiscographyList/View/ArtistDetailsView.xaml.cs
using MyDiscographyList.Extention;
using MyDiscographyList.Model;
using MyDiscographyList.ViewModel;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace MyDiscographyList.View
{
public partial class ArtistDetailsView : UserControl
{
public event EventHandler ArtistSelected;
private bool isUserInteraction = false;
public ArtistDetailsView()
{
InitializeComponent();
dgArtistListRecommandation.MouseDoubleClick += new MouseButtonEventHandler(GoToArtistDetail);
}
private void UpdateScoreHandler(object sender, RoutedEventArgs e)
{
if (!IsLoaded || !isUserInteraction) { return; }
ArtistModel selectedItem = dgArtistListRecommandation.CurrentItem as ArtistModel;
var vm = DataContext as ArtistDetailsViewModel;
if (selectedItem != null && vm != null)
{
vm.UpdateSelectedArtistScore();
}
else if (vm != null)
{
vm.UpdateArtistScore();
}
isUserInteraction = false;
}
private void UpdateStatusHandler(object sender, RoutedEventArgs e)
{
if (!IsLoaded || !isUserInteraction) { return; }
var selectedItem = dgArtistListRecommandation.CurrentItem as ArtistModel;
var vm = DataContext as ArtistDetailsViewModel;
if (selectedItem != null && vm != null)
{
vm.UpdateSelectedArtistStatus();
}
else if (vm != null)
{
vm.UpdatedArtistStatus();
}
isUserInteraction = false;
}
private void GoToArtistDetail(object sender, RoutedEventArgs e)
{
if (dgArtistListRecommandation.SelectedItem == null) return;
var selectedArtist = dgArtistListRecommandation.SelectedItem as ArtistModel;
ArtistRoutedEventArgs artistREA = new ArtistRoutedEventArgs(selectedArtist.ArtistId);
ArtistSelected(this, artistREA);
}
private void DeleteBtnClick(object sender, RoutedEventArgs e)
{
var selectedItem = dgArtistListRecommandation.CurrentItem as ArtistModel;
if (selectedItem != null)
{
DeleteArtistConfirmView modalWindow = new DeleteArtistConfirmView(selectedItem);
modalWindow.ArtistDeleted += new EventHandler(RemoveArtist);
modalWindow.ShowDialog();
}
}
private void RemoveArtist(Object sender, EventArgs e)
{
var selectedItem = dgArtistListRecommandation.CurrentItem as ArtistModel;
var vm = DataContext as ArtistDetailsViewModel;
if (selectedItem != null && vm != null)
{
vm.DeleteSelectedArtist();
}
}
private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
isUserInteraction = true;
}
private void GoToArtistWebPage(object sender, RoutedEventArgs e)
{
var vm = DataContext as ArtistDetailsViewModel;
System.Diagnostics.Process.Start("https://www.google.com/search?q=" + vm.Artist.ArtistName);
}
}
}<file_sep>/MyDiscographyList/Model/ArtistScoreModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyDiscographyList.Model
{
public class ArtistScoreModel : INotifyPropertyChanged
{
private int _scoreId;
private string _scoreLabel;
public int ScoreId { get { return _scoreId; } set { _scoreId = value; OnPropertyChanged("ScoreId"); } }
public string ScoreLabel { get { return _scoreLabel; } set { _scoreLabel = value; OnPropertyChanged("ScoreLabel"); } }
#region INotifyPropertyChanged Artis
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
<file_sep>/MyDiscographyList/DataAccess/DataAccess.cs
using Microsoft.Data.Sqlite;
using MyDiscographyList.Enum;
using MyDiscographyList.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
namespace DataAccessLibrary
{
public static class DataAccess
{
static readonly string dbpath = System.Environment.CurrentDirectory + "\\DiscoDB.db";
public static List<ArtistStatusModel> GetStatusList()
{
List<ArtistStatusModel> statusList = new List<ArtistStatusModel>();
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand();
selectCommand.Connection = db;
selectCommand.CommandText = "SELECT * FROM Status";
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
statusList.Add(new ArtistStatusModel() { StatusId = query.GetInt32(0), StatusLabel = query.GetString(1), StatusColor = (Brush)new BrushConverter().ConvertFromString(query.GetString(2)) });
}
db.Close();
}
return statusList;
}
public static List<ArtistScoreModel> GetScoreList()
{
List<ArtistScoreModel> statusList = new List<ArtistScoreModel>();
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand("SELECT * FROM Score", db);
selectCommand.Connection = db;
selectCommand.CommandText = "SELECT * FROM Score";
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
statusList.Add(new ArtistScoreModel() { ScoreId = query.GetInt32(0), ScoreLabel = query.GetString(1) });
}
db.Close();
}
return statusList;
}
public static int AddArtist(ArtistModel artist)
{
int insertedId = 0;
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand insertCommand = new SqliteCommand();
insertCommand.Connection = db;
insertCommand.CommandText = "INSERT INTO Artist (name, alias, scoreId, statusId, upToDate, date) VALUES (@Name, @Alias, @scoreId, @StatusId, @UpToDate, @Date); SELECT last_insert_rowid()";
insertCommand.Parameters.AddWithValue("@Name", artist.ArtistName);
insertCommand.Parameters.AddWithValue("@Alias", artist.ArtistAlias);
insertCommand.Parameters.AddWithValue("@scoreId", artist.ArtistScore.ScoreId);
insertCommand.Parameters.AddWithValue("@StatusId", artist.ArtistStatus.StatusId);
insertCommand.Parameters.AddWithValue("@UpToDate", artist.ArtistUpToDate);
insertCommand.Parameters.AddWithValue("@Date", DateTime.Now);
SqliteDataReader query = insertCommand.ExecuteReader();
while (query.Read())
{
insertedId = query.GetInt32(0);
}
db.Close();
}
return insertedId;
}
public static ObservableCollection<ArtistModel> GetArtistList(TypeListEnum type, string filter)
{
ObservableCollection<ArtistModel> artistList = new ObservableCollection<ArtistModel>();
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand();
selectCommand.Connection = db;
selectCommand.CommandText = "SELECT a.id, a.name, a.alias, a.upToDate, a.date, st.id, st.label, st.color, sc.id, sc.label FROM Artist a LEFT JOIN Status st ON st.id = a.statusId LEFT JOIN Score sc ON sc.id = a.scoreId ";
switch (type)
{
case TypeListEnum.Listened:
selectCommand.CommandText += "WHERE a.statusId <> 6 ";
break;
case TypeListEnum.Unlistened:
selectCommand.CommandText += "WHERE a.statusId = 6 ";
break;
case TypeListEnum.Searched:
selectCommand.CommandText += "WHERE 0 = 0 ";
break;
}
if (!string.IsNullOrEmpty(filter) && filter != "All")
{
if (filter == "0-9")
{
selectCommand.CommandText += "AND a.name GLOB '[0-9]*' ";
}
else if (filter == "*")
{
selectCommand.CommandText += "AND a.name NOT GLOB '[0-9]*' AND a.name NOT GLOB '[A-Z]*' ";
}
else
{
selectCommand.CommandText += "AND a.name LIKE '" + filter + "%' ";
}
}
switch (type)
{
case TypeListEnum.Listened:
selectCommand.CommandText += "ORDER BY a.name ";
break;
case TypeListEnum.Unlistened:
selectCommand.CommandText += "ORDER BY a.date ";
break;
}
selectCommand.CommandText += " ";
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
artistList.Add(new ArtistModel()
{
ArtistId = query.GetInt32(0),
ArtistName = query.GetString(1),
ArtistAlias = query.GetString(2),
ArtistUpToDate = query.GetBoolean(3),
ArtistDate = query.GetDateTime(4),
ArtistStatus = new ArtistStatusModel() { StatusId = query.GetInt32(5), StatusLabel = query.GetString(6), StatusColor = (Brush)new BrushConverter().ConvertFromString(query.GetString(7)) },
ArtistScore = new ArtistScoreModel() { ScoreId = query.GetInt32(8), ScoreLabel = query.GetString(9) }
});
}
db.Close();
}
return artistList;
}
public static void UpdateArtistScore(ArtistModel artist)
{
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand updateCommand = new SqliteCommand();
updateCommand.Connection = db;
updateCommand.CommandText = "UPDATE Artist SET scoreId = @scoreId WHERE id = @Id ";
updateCommand.Parameters.AddWithValue("@Id", artist.ArtistId);
updateCommand.Parameters.AddWithValue("@scoreId", artist.ArtistScore.ScoreId);
updateCommand.ExecuteReader();
db.Close();
}
}
public static void UpdateArtistStatus(ArtistModel artist)
{
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand updateCommand = new SqliteCommand();
updateCommand.Connection = db;
updateCommand.CommandText = "UPDATE Artist SET statusId = @statusId, date = @Date WHERE id = @Id ";
updateCommand.Parameters.AddWithValue("@Id", artist.ArtistId);
updateCommand.Parameters.AddWithValue("@statusId", artist.ArtistStatus.StatusId);
updateCommand.Parameters.AddWithValue("@Date", DateTime.Now);
updateCommand.ExecuteReader();
db.Close();
}
}
public static void UpdateArtistUpToDate(ArtistModel artist)
{
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand updateCommand = new SqliteCommand();
updateCommand.Connection = db;
updateCommand.CommandText = "UPDATE Artist SET upToDate = @UpToDate WHERE id = @Id ";
updateCommand.Parameters.AddWithValue("@Id", artist.ArtistId);
updateCommand.Parameters.AddWithValue("@UpToDate", artist.ArtistUpToDate);
updateCommand.ExecuteReader();
db.Close();
}
}
public static void UpdateArtistName(ArtistModel artist)
{
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand updateCommand = new SqliteCommand();
updateCommand.Connection = db;
updateCommand.CommandText = "UPDATE Artist SET name = @Name WHERE id = @Id ";
updateCommand.Parameters.AddWithValue("@Id", artist.ArtistId);
updateCommand.Parameters.AddWithValue("@Name", artist.ArtistName);
updateCommand.ExecuteReader();
db.Close();
}
}
public static void UpdateArtistAlias(ArtistModel artist)
{
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand updateCommand = new SqliteCommand();
updateCommand.Connection = db;
updateCommand.CommandText = "UPDATE Artist SET alias = @Alias WHERE id = @Id ";
updateCommand.Parameters.AddWithValue("@Id", artist.ArtistId);
updateCommand.Parameters.AddWithValue("@Alias", artist.ArtistAlias);
updateCommand.ExecuteReader();
db.Close();
}
}
public static ArtistModel GetArtistById(int id)
{
ArtistModel artist;
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand();
selectCommand.Connection = db;
selectCommand.CommandText = "SELECT a.id, a.name, a.alias, a.upToDate, a.date, st.id, st.label, st.color, sc.id, sc.label FROM Artist a LEFT JOIN Status st ON st.id = a.statusId LEFT JOIN Score sc ON sc.id = a.scoreId WHERE a.id = @Id ";
selectCommand.Parameters.AddWithValue("@Id", id);
SqliteDataReader query = selectCommand.ExecuteReader();
query.Read();
artist = new ArtistModel()
{
ArtistId = query.GetInt32(0),
ArtistName = query.GetString(1),
ArtistAlias = query.GetString(2),
ArtistUpToDate = query.GetBoolean(3),
ArtistDate = query.GetDateTime(4),
ArtistStatus = new ArtistStatusModel() { StatusId = query.GetInt32(5), StatusLabel = query.GetString(6), StatusColor = (Brush)new BrushConverter().ConvertFromString(query.GetString(7)) },
ArtistScore = new ArtistScoreModel() { ScoreId = query.GetInt32(8), ScoreLabel = query.GetString(9) }
};
db.Close();
}
return artist;
}
public static void AddRecommandation(int artistId1, int artistId2)
{
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand insertCommand = new SqliteCommand();
insertCommand.Connection = db;
insertCommand.CommandText = "INSERT INTO Recommandation (artistId1, artistId2) VALUES (@Id1, @Id2)";
insertCommand.Parameters.AddWithValue("@Id1", artistId1);
insertCommand.Parameters.AddWithValue("@Id2", artistId2);
insertCommand.ExecuteReader();
db.Close();
}
}
public static ObservableCollection<ArtistModel> GetRelatedArtist(int id)
{
ObservableCollection<ArtistModel> artistList = new ObservableCollection<ArtistModel>();
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand();
selectCommand.Connection = db;
selectCommand.CommandText = @"SELECT * FROM (
SELECT a.id, a.name, a.alias, a.upToDate, a.date, st.id, st.label, st.color, sc.id, sc.label
FROM Recommandation r
INNER JOIN Artist a ON a.id = r.artistId1
LEFT JOIN Status st ON st.id = a.statusId
LEFT JOIN Score sc ON sc.id = a.scoreId
WHERE r.artistId2 = @Id
UNION
SELECT a.id, a.name, a.alias, a.upToDate, a.date, st.id, st.label, st.color, sc.id, sc.label
FROM Recommandation r
INNER JOIN Artist a ON a.id = r.artistId2
LEFT JOIN Status st ON st.id = a.statusId
LEFT JOIN Score sc ON sc.id = a.scoreId
WHERE r.artistId1 = @Id
) t ORDER BY t.name";
selectCommand.Parameters.AddWithValue("@Id", id);
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
artistList.Add(new ArtistModel()
{
ArtistId = query.GetInt32(0),
ArtistName = query.GetString(1),
ArtistAlias = query.GetString(2),
ArtistUpToDate = query.GetBoolean(3),
ArtistDate = query.GetDateTime(4),
ArtistStatus = new ArtistStatusModel() { StatusId = query.GetInt32(5), StatusLabel = query.GetString(6), StatusColor = (Brush)new BrushConverter().ConvertFromString(query.GetString(7)) },
ArtistScore = new ArtistScoreModel() { ScoreId = query.GetInt32(8), ScoreLabel = query.GetString(9) }
});
}
db.Close();
}
return artistList;
}
public static List<ArtistModel> CheckRelatedArtists(List<string> nameList)
{
List<ArtistModel> artistList = new List<ArtistModel>();
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand();
selectCommand.Connection = db;
selectCommand.CommandText = @"SELECT a.id, a.name, a.alias, a.upToDate, a.date, st.id, st.label, st.color, sc.id, sc.label FROM Artist a LEFT JOIN Status st ON st.id = a.statusId LEFT JOIN Score sc ON sc.id = a.scoreId" +
" WHERE a.name IN (\"" + string.Join("\",\"", nameList) + "\") " +
" OR a.alias IN (\"" + string.Join("\",\"", nameList) + "\") " +
"ORDER BY a.name ";
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
artistList.Add(new ArtistModel()
{
ArtistId = query.GetInt32(0),
ArtistName = query.GetString(1),
ArtistAlias = query.GetString(2),
ArtistUpToDate = query.GetBoolean(3),
ArtistDate = query.GetDateTime(4),
ArtistStatus = new ArtistStatusModel() { StatusId = query.GetInt32(5), StatusLabel = query.GetString(6), StatusColor = (Brush)new BrushConverter().ConvertFromString(query.GetString(7)) },
ArtistScore = new ArtistScoreModel() { ScoreId = query.GetInt32(8), ScoreLabel = query.GetString(9) }
});
}
db.Close();
}
return artistList;
}
public static void DeleteArtist(ArtistModel artist)
{
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand deleteCommand = new SqliteCommand();
deleteCommand.Connection = db;
deleteCommand.CommandText = "DELETE FROM Recommandation WHERE artistId1 = @Id OR artistId2 = @Id";
deleteCommand.Parameters.AddWithValue("@Id", artist.ArtistId);
deleteCommand.ExecuteReader();
db.Close();
db.Open();
deleteCommand = new SqliteCommand();
deleteCommand.Connection = db;
deleteCommand.CommandText = "DELETE FROM Artist WHERE id = @Id";
deleteCommand.Parameters.AddWithValue("@Id", artist.ArtistId);
deleteCommand.ExecuteReader();
db.Close();
}
}
public static List<ArtistStatusModel> CountStatusDisco()
{
List<ArtistStatusModel> statusList = new List<ArtistStatusModel>();
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand();
selectCommand.Connection = db;
selectCommand.CommandText = "SELECT s.id, s.label, s.color, COUNT(a.id) FROM Status s LEFT JOIN Artist a ON a.statusId = s.id GROUP BY s.id, s.label, s.color";
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
statusList.Add(new ArtistStatusModel() { StatusId = query.GetInt32(0),
StatusLabel = query.GetString(1),
StatusColor = (Brush)new BrushConverter().ConvertFromString(query.GetString(2)),
NbOfStatus = query.GetInt32(3)
});
}
db.Close();
}
return statusList;
}
}
}
<file_sep>/MyDiscographyList/MyDiscographyList.xaml.cs
using MyDiscographyList.Enum;
using MyDiscographyList.Extention;
using MyDiscographyList.View;
using MyDiscographyList.ViewModel;
using System;
using System.Windows;
using System.Windows.Controls;
namespace MyDiscographyList
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ToggleBtnUnchecked(object sender, RoutedEventArgs e) { Bg.Opacity = 1; }
private void ToggleBtnChecked(object sender, RoutedEventArgs e) { Bg.Opacity = 0.3; }
private void CloseBtnClick(object sender, RoutedEventArgs e) { Close(); }
private void AddBtnClick(object sender, RoutedEventArgs e)
{
AddArtistModalWindowView modalWindow = new AddArtistModalWindowView();
modalWindow.ShowDialog();
}
private void GoToHome(object sender, RoutedEventArgs e)
{
MainView.Items.Clear();
var userControl = new HomeView();
DataContext = new DashboardViewModel();
MainView.Items.Add(new TabItem { Content = userControl });
MainView.Items.Refresh();
}
private void GoToListenedDisco(object sender, RoutedEventArgs e)
{
MainView.Items.Clear();
var userControl = new ListDiscoView();
DataContext = new ArtistListViewModel(TypeListEnum.Listened);
userControl.ArtistSelected += new EventHandler(GoToArtistDetails);
MainView.Items.Add(new TabItem { Content = userControl });
MainView.Items.Refresh();
}
private void GoToUnlistenedDisco(object sender, RoutedEventArgs e)
{
MainView.Items.Clear();
var userControl = new ListDiscoView();
DataContext = new ArtistListViewModel(TypeListEnum.Unlistened);
userControl.ArtistSelected += new EventHandler(GoToArtistDetails);
MainView.Items.Add(new TabItem { Content = userControl });
MainView.Items.Refresh();
}
private void GoToSearchedDisco(object sender, RoutedEventArgs e)
{
MainView.Items.Clear();
var userControl = new ListDiscoView();
DataContext = new ArtistListViewModel(TypeListEnum.Searched, searchTxt.Text);
userControl.ArtistSelected += new EventHandler(GoToArtistDetails);
MainView.Items.Add(new TabItem { Content = userControl });
MainView.Items.Refresh();
}
private void GoToArtistDetails(Object sender, EventArgs e)
{
ArtistRoutedEventArgs artist = (ArtistRoutedEventArgs)e;
MainView.Items.Clear();
var userControl = new ArtistDetailsView();
DataContext = new ArtistDetailsViewModel(artist.ArtistID);
userControl.ArtistSelected += new EventHandler(GoToArtistDetails);
MainView.Items.Add(new TabItem { Content = userControl });
MainView.Items.Refresh();
}
private void GoToGithub(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("https://github.com/Asmodeus96/MyDiscographyList");
}
}
}
<file_sep>/MyDiscographyList/Enum/TypeListEnum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyDiscographyList.Enum
{
public enum TypeListEnum
{
Listened,
Unlistened,
Searched
}
}
<file_sep>/MyDiscographyList/Model/ArtistModel.cs
using System;
using System.ComponentModel;
namespace MyDiscographyList.Model
{
public class ArtistModel : INotifyPropertyChanged
{
private int artistId;
private string artistName;
private string artistAlias;
private ArtistScoreModel artistScore;
private ArtistStatusModel artistStatus;
private bool artisUpToDate;
private DateTime artistDate;
public int ArtistId
{
get { return artistId; }
set { artistId = value; OnPropertyChanged("ArtistId"); }
}
public string ArtistName
{
get { return artistName; }
set { artistName = value; OnPropertyChanged("ArtistName"); }
}
public string ArtistAlias
{
get { return artistAlias; }
set { artistAlias = value; OnPropertyChanged("ArtistAlias"); }
}
public ArtistScoreModel ArtistScore
{
get { return artistScore; }
set { artistScore = value; OnPropertyChanged("ArtistScore"); }
}
public ArtistStatusModel ArtistStatus
{
get { return artistStatus; }
set { artistStatus = value; OnPropertyChanged("ArtistStatus"); }
}
public bool ArtistUpToDate
{
get { return artisUpToDate; }
set { artisUpToDate = value; OnPropertyChanged("ArtistUpToDate"); }
}
public DateTime ArtistDate
{
get { return artistDate; }
set { artistDate = value; OnPropertyChanged("ArtistUpToDate"); }
}
#region INotifyPropertyChanged Artist
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
| 5a14d3357d6c8013600fa14d98d95cfe3244dcd2 | [
"Markdown",
"C#"
]
| 16 | C# | Asmodeus96/MyDiscographyList | 467ea0cc1c21bfe0f79f3a6c9b25fe349054f5e6 | d498c5e596b284e6bec8d42e2825e20a430959b9 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MovieShop.Web.Controllers
{
public class CastController
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MovieShop.Web.Models;
namespace MovieShop.Web.Controllers
{
public class GenreController
{
// List<Genre> GenreList = new List<Genre>();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MovieShop.Core.Entities;
using MovieShop.Core.Models.Request;
using MovieShop.Core.Models.Response;
using MovieShop.Core.ServiceInterfaces;
namespace MovieShop.Web.Controllers
{
public class UserController : ControllerBase
{
private readonly IMovieService _movieService;
private readonly IUserService _userService;
private readonly ICryptoService _encryptionService;
public UserController(IUserService userService, IMovieService movieService)
{
_userService = userService;
_movieService = movieService;
}
public Task<UserLoginResponseModel> ValidateUser(string email, string password)
{
throw new NotImplementedException();
}
public Task<UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
{
throw new NotImplementedException();
}
public Task<UserRegisterResponseModel> GetUserDetails(int id)
{
throw new NotImplementedException();
}
public Task<User> GetUser(string email)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MovieShop.Infrastructure.Repositories;
using MovieShop.Core.ServiceInterfaces;
using MovieShop.Infrastructure.Data;
using MovieShop.Core.RepositoryInterfaces;
using MovieShop.Core.Models.Request;
using MovieShop.Core.Helpers;
using MovieShop.Core.Models.Response;
using MovieShop.Core.Entities;
using MovieShop.Core.Models;
using AutoMapper;
namespace MovieShop.Infrastructure.Services
{
public class MovieService :IMovieService
{
private readonly IMovieRepository _movieRepository;
private readonly IAsyncRepository<MovieGenre> _movieGenresRepository;
private readonly IPurchaseRepository _purchaseRepository;
//constructor injection
public MovieService(IMovieRepository MovieRepository, IAsyncRepository<MovieGenre> MovieGenresRepository, IPurchaseRepository purchaseRepository)
{
//repository = new MovieRepository(new MovieShopDbContext(null));
_movieRepository = MovieRepository;
_movieGenresRepository = MovieGenresRepository;
_purchaseRepository = purchaseRepository;
}
public async Task<IEnumerable<MovieResponseModel>> GetMoviesByGenre(int genreId)
{
var movies = await _movieRepository.GetMoviesByGenre(genreId);
var returnedModel = new List<MovieResponseModel>();
foreach(var movie in movies)
{
var model = new MovieResponseModel
{
Id = movie.Id,
Title = movie.Title,
PosterUrl = movie.PosterUrl,
ReleaseDate = movie.ReleaseDate
};
returnedModel.Add(model);
}
return returnedModel;
}
public async Task<int> GetMoviesCount(string title = "")
{
if (string.IsNullOrEmpty(title)) return await _movieRepository.GetCountAsync();
return await _movieRepository.GetCountAsync(m => m.Title.Contains(title));
}
public async Task<IEnumerable<MovieResponseModel>> GetHighestGrossingMovies()
{
var movies = await _movieRepository.GetHighestGrossingMovies();
// Map our Movie Entity to MovieResponseModel
var movieResponseModel = new List<MovieResponseModel>();
foreach (var movie in movies)
{
movieResponseModel.Add(new MovieResponseModel
{
Id = movie.Id,
PosterUrl = movie.PosterUrl,
//ReleaseDate = movie.ReleaseDate.Value,
Title = movie.Title
});
}
return movieResponseModel;
}
public async Task<PagedResultSet<MovieResponseModel>> GetMoviesByPagination(int pageSize = 20, int page = 0, string title = "")
{
throw new NotImplementedException();
}
public async Task<PagedResultSet<MovieResponseModel>> GetAllMoviePurchasesByPagination(int pageSize = 20, int page = 0)
{
//var totalPurchases = await _purchaseRepository.GetCountAsync();
//var purchases = await _purchaseRepository.GetAllPurchases(pageSize, page);
//var data = _mapper.Map<List<MovieResponseModel>>(purchases);
//var purchasedMovies = new PagedResultSet<MovieResponseModel>(data, page, pageSize, totalPurchases);
//return purchasedMovies;
throw new NotImplementedException();
}
public Task<PaginatedList<MovieResponseModel>> GetAllPurchasesByMovieId(int movieId)
{
throw new NotImplementedException();
}
public async Task<MovieDetailsResponseModel> GetMovieAsync(int id)
{
var movie = await _movieRepository.GetByIdAsync(id);
//if (movie == null) throw new NotFoundException("Movie", id);
//var favoritesCount = await _favoriteRepository.GetCountAsync(f => f.MovieId == id);
var response = new MovieDetailsResponseModel
{
Id = movie.Id,
Title = movie.Title,
Overview = movie.Overview,
Tagline = movie.Tagline,
Revenue = movie.Revenue,
Budget = movie.Budget,
ImdbUrl = movie.ImdbUrl,
TmdbUrl = movie.TmdbUrl,
PosterUrl = movie.PosterUrl,
BackdropUrl = movie.BackdropUrl,
ReleaseDate = movie.ReleaseDate,
RunTime = movie.RunTime,
Price = movie.Price,
Casts = new List<MovieDetailsResponseModel.CastResponseModel>(),
};
foreach(var cast in movie.MovieCasts)
{
response.Casts.Add(new MovieDetailsResponseModel.CastResponseModel
{
Id=cast.CastId,
Gender=cast.Cast.Gender,
Name=cast.Cast.Name,
ProfilePath=cast.Cast.ProfilePath,
TmdbUrl=cast.Cast.TmdbUrl,
Character=cast.Character
});
}
return response;
}
public async Task<IEnumerable<MovieResponseModel>> GetTopRatedMovies()
{
var topMovies = await _movieRepository.GetTopRatedMovies();
List<MovieResponseModel> response = new List<MovieResponseModel>();
foreach(var movie in topMovies)
{
response.Add(new MovieResponseModel
{
Id = movie.Id,
Title = movie.Title,
PosterUrl=movie.PosterUrl,
ReleaseDate=movie.ReleaseDate
});
}
return response;
}
public async Task<MovieDetailsResponseModel> CreateMovie(MovieCreateRequest movieCreateRequest)
{
var movie = new Movie {
Id=movieCreateRequest.Id,
Title= movieCreateRequest.Title,
Overview= movieCreateRequest.Overview,
Tagline= movieCreateRequest.Tagline,
Revenue= movieCreateRequest.Revenue,
Budget= movieCreateRequest.Budget,
ImdbUrl= movieCreateRequest.ImdbUrl,
TmdbUrl= movieCreateRequest.TmdbUrl,
PosterUrl= movieCreateRequest.PosterUrl,
BackdropUrl= movieCreateRequest.BackdropUrl,
OriginalLanguage= movieCreateRequest.OriginalLanguage,
ReleaseDate= movieCreateRequest.ReleaseDate,
RunTime= movieCreateRequest.RunTime,
Price= movieCreateRequest.Price,
};
var CreatedMovie = await _movieRepository.AddAsync(movie);
foreach (var genre in movieCreateRequest.Genres)
{
var MovieGenre = new MovieGenre {MovieId=CreatedMovie.Id,GenreId=genre.Id };
await _movieGenresRepository.AddAsync(MovieGenre);
}
var ReturnedModel = new MovieDetailsResponseModel {
Id = movie.Id,
Title = movie.Title,
Overview = movie.Overview,
Tagline = movie.Tagline,
Revenue = movie.Revenue,
Budget = movie.Budget,
ImdbUrl = movie.ImdbUrl,
TmdbUrl = movie.TmdbUrl,
PosterUrl = movie.PosterUrl,
BackdropUrl = movie.BackdropUrl,
ReleaseDate = movie.ReleaseDate,
RunTime = movie.RunTime,
Price = movie.Price,
};
return ReturnedModel;
}
public async Task<MovieDetailsResponseModel> UpdateMovie(MovieCreateRequest movieCreateRequest)
{
var movie = new Movie
{
Id = movieCreateRequest.Id,
Title = movieCreateRequest.Title,
Overview = movieCreateRequest.Overview,
Tagline = movieCreateRequest.Tagline,
Revenue = movieCreateRequest.Revenue,
Budget = movieCreateRequest.Budget,
ImdbUrl = movieCreateRequest.ImdbUrl,
TmdbUrl = movieCreateRequest.TmdbUrl,
PosterUrl = movieCreateRequest.PosterUrl,
BackdropUrl = movieCreateRequest.BackdropUrl,
OriginalLanguage = movieCreateRequest.OriginalLanguage,
ReleaseDate = movieCreateRequest.ReleaseDate,
RunTime = movieCreateRequest.RunTime,
Price = movieCreateRequest.Price,
}; var UpdatedMovie =await _movieRepository.UpdateAsync(movie);
foreach(var genre in movieCreateRequest.Genres)
{
var MovieGenre = new MovieGenre { MovieId = UpdatedMovie.Id, GenreId = genre.Id };
await _movieGenresRepository.UpdateAsync(MovieGenre);
}
var ReturnedModel = new MovieDetailsResponseModel
{
Id = movie.Id,
Title = movie.Title,
Overview = movie.Overview,
Tagline = movie.Tagline,
Revenue = movie.Revenue,
Budget = movie.Budget,
ImdbUrl = movie.ImdbUrl,
TmdbUrl = movie.TmdbUrl,
PosterUrl = movie.PosterUrl,
BackdropUrl = movie.BackdropUrl,
ReleaseDate = movie.ReleaseDate,
RunTime = movie.RunTime,
Price = movie.Price,
};
return ReturnedModel;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MovieShop.Core.Entities
{
public class Cast
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Gender { get; set; }
public string? TmdbUrl { get; set; }
public string? ProfilePath { get; set; }
public List<MovieCast> MovieCasts { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using MovieShop.Core.Models;
using MovieShop.Core.Models.Response;
using MovieShop.Core.RepositoryInterfaces;
using MovieShop.Core.ServiceInterfaces;
namespace MovieShop.Infrastructure.Services
{
public class CastService : ICastService
{
private readonly ICastRepository _castRepository;
public CastService(ICastRepository castRepository)
{
_castRepository = castRepository;
}
public async Task<IEnumerable<CastResponseModel>> GetCastByMovieId(int id)
{
var casts = await _castRepository.GetCastsByMovieId(id);
var responses = new List<CastResponseModel>();
foreach(var cast in casts)
{
//response.Add(new CastResponseModel {
// CastId=cast.Id,
// ProfileUrl=cast.ProfilePath,
// CastName=cast.Name,
// Character=
//});
var response = new CastResponseModel
{
CastId = cast.Id,
ProfileUrl = cast.ProfilePath,
CastName = cast.Name,
};
responses.Add(response);
}
return responses;
}
public async Task<CastDetailsResponseModel> GetCastDetailsWithMovies(int id)
{
var cast = await _castRepository.GetByIdAsync(id);
var ReturnedCast = new CastDetailsResponseModel {
Id=cast.Id,
Name=cast.Name,
Gender=cast.Gender,
TmdbUrl=cast.TmdbUrl,
ProfilePath=cast.ProfilePath
};
return ReturnedCast;
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using MovieShop.Infrastructure;
using System;
using System.Collections.Generic;
using System.Text;
using MovieShop.Core.Entities;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace MovieShop.Infrastructure.Data
{
public class MovieShopDbContext : DbContext
{
public MovieShopDbContext(DbContextOptions<MovieShopDbContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>(ConfigureMovie);
modelBuilder.Entity<Trailer>(ConfigureTrailer);
modelBuilder.Entity<MovieGenre>(ConfigureMovieGenre);
modelBuilder.Entity<Cast>(ConfigureCast);
modelBuilder.Entity<MovieCast>(ConfigureMovieCast);
modelBuilder.Entity<Review>(ConfigureReview);
modelBuilder.Entity<MovieCrew>(ConfigureMovieCrew);
modelBuilder.Entity<Crew>(ConfigureCrew);
modelBuilder.Entity<User>(ConfigureUser);
modelBuilder.Entity<Purchase>(ConfigurePurchase);
}
public void ConfigurePurchase(EntityTypeBuilder<Purchase> builder)
{
builder.ToTable("Purchase");
builder.HasKey(p => p.Id);
builder.Property(p => p.TotalPrice).HasPrecision(18,2);
}
public void ConfigureCrew(EntityTypeBuilder<Crew> builder)
{
builder.ToTable("Crew");
builder.HasKey(c => c.Id);
builder.Property(c => c.Name).HasMaxLength(128);
builder.Property(c => c.ProfilePath).HasMaxLength(2048);
}
public void ConfigureUser(EntityTypeBuilder<User> builder)
{
builder.ToTable("User");
builder.HasKey(u => u.Id);
builder.Property(u => u.FirstName).HasMaxLength(128);
builder.Property(u => u.LastName).HasMaxLength(128);
builder.Property(u => u.Email).HasMaxLength(256);
builder.Property(u => u.HashedPassword).HasMaxLength(1024);
builder.Property(u => u.Salt).HasMaxLength(1024);
builder.Property(u => u.PhoneNumber).HasMaxLength(16);
}
public void ConfigureMovieCrew(EntityTypeBuilder<MovieCrew> builder)
{
builder.ToTable("MovieCrew");
builder.HasKey(mc => new { mc.MovieId, mc.CrewId });
builder.HasOne(mc => mc.Movie)
.WithMany(m => m.MovieCrews)
.HasForeignKey(mc=>mc.MovieId);
builder.HasOne(mc => mc.Crew)
.WithMany(c => c.MovieCrews)
.HasForeignKey(mc => mc.CrewId);
}
public void ConfigureCast(EntityTypeBuilder<Cast> builder)
{
builder.ToTable("Cast");
builder.HasKey(c => c.Id);
builder.Property(c => c.Name).HasMaxLength(128);
builder.Property(c => c.ProfilePath).HasMaxLength(2048);
}
public void ConfigureMovieCast(EntityTypeBuilder<MovieCast> builder)
{
builder.ToTable("MovieCast");
builder.HasKey(mc => new { mc.MovieId, mc.CastId });
builder.HasOne(mc => mc.Movie)
.WithMany(m => m.MovieCasts)
.HasForeignKey(mc => mc.MovieId);
builder.HasOne(mc => mc.Cast)
.WithMany(c => c.MovieCasts)
.HasForeignKey(mc=>mc.CastId);
}
public void ConfigureReview(EntityTypeBuilder<Review> builder)
{
builder.ToTable("Review");
builder.HasKey(r => new { r.MovieId, r.UserId});
builder.HasOne(r => r.Movie)
.WithMany(m => m.Reviews)
.HasForeignKey(u => u.MovieId);
builder.HasOne(r => r.User)
.WithMany(u => u.Reviews)
.HasForeignKey(r=>r.UserId);
}
public void ConfigureMovieGenre(EntityTypeBuilder<MovieGenre> builder)
{
builder.ToTable("MovieGenre");
builder.HasKey(m=>new { m.MovieId,m.GenreId});
builder.HasOne(mg => mg.Genre)
.WithMany(g => g.MovieGenres)
.HasForeignKey(mg=>mg.GenreId);
builder.HasOne(mg => mg.Movie)
.WithMany(m => m.MovieGenres)
.HasForeignKey(mg => mg.MovieId);
}
public void ConfigureTrailer(EntityTypeBuilder<Trailer> builder)
{
builder.ToTable("Trailer");
builder.HasKey(t => t.Id);
builder.Property(t => t.TrailerUrl).HasMaxLength(2084);
builder.Property(t => t.Name).HasMaxLength(2084);
}
private void ConfigureMovie(EntityTypeBuilder<Movie> builder)
{
builder.ToTable("Movie");
builder.HasKey(m => m.Id);
builder.Property(m => m.Title).IsRequired().HasMaxLength(256);
builder.Property(m => m.Overview).HasMaxLength(4096);
builder.Property(m => m.Tagline).HasMaxLength(512);
builder.Property(m => m.ImdbUrl).HasMaxLength(2084);
builder.Property(m => m.TmdbUrl).HasMaxLength(2084);
builder.Property(m => m.PosterUrl).HasMaxLength(2084);
builder.Property(m => m.BackdropUrl).HasMaxLength(2084);
builder.Property(m => m.OriginalLanguage).HasMaxLength(64);
builder.Property(m => m.Price).HasColumnType("decimal(5, 2)").HasDefaultValue(9.9m);
builder.Property(m => m.CreatedDate).HasDefaultValueSql("getdate()");
builder.Ignore(m => m.Rating);
}
public DbSet<Genre> Genres { get; set; }
public DbSet<Movie> Movies { get; set; }
public DbSet<Trailer> Trailers { get; set; }
public DbSet<MovieCast> MovieCasts { get; set; }
public DbSet<MovieCrew> MovieCrews { get; set; }
public DbSet<MovieGenre> MovieGenres { get; set; }
public DbSet<Crew> Crews { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Review> Reviews { get; set; }
public DbSet<Cast> Casts { get; set; }
public DbSet<Purchase> Purchases { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MovieShop.Core.Models.Response
{
public class CastResponseModel
{
public int CastId { get; set; }
public string ProfileUrl { get; set; }
public string CastName { get; set; }
public string Character { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace MovieShop.Infrastructure.Migrations
{
public partial class ReCreateJoinTable4 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Genre_genreId",
table: "MovieGenre");
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Movie_movieId",
table: "MovieGenre");
migrationBuilder.DropPrimaryKey(
name: "PK_MovieGenre",
table: "MovieGenre");
migrationBuilder.DropIndex(
name: "IX_MovieGenre_movieId",
table: "MovieGenre");
migrationBuilder.RenameColumn(
name: "movieId",
table: "MovieGenre",
newName: "MovieId");
migrationBuilder.RenameColumn(
name: "genreId",
table: "MovieGenre",
newName: "GenreId");
migrationBuilder.AddPrimaryKey(
name: "PK_MovieGenre",
table: "MovieGenre",
columns: new[] { "MovieId", "GenreId" });
migrationBuilder.CreateIndex(
name: "IX_MovieGenre_GenreId",
table: "MovieGenre",
column: "GenreId");
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Genre_GenreId",
table: "MovieGenre",
column: "GenreId",
principalTable: "Genre",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Movie_MovieId",
table: "MovieGenre",
column: "MovieId",
principalTable: "Movie",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Genre_GenreId",
table: "MovieGenre");
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Movie_MovieId",
table: "MovieGenre");
migrationBuilder.DropPrimaryKey(
name: "PK_MovieGenre",
table: "MovieGenre");
migrationBuilder.DropIndex(
name: "IX_MovieGenre_GenreId",
table: "MovieGenre");
migrationBuilder.RenameColumn(
name: "GenreId",
table: "MovieGenre",
newName: "genreId");
migrationBuilder.RenameColumn(
name: "MovieId",
table: "MovieGenre",
newName: "movieId");
migrationBuilder.AddPrimaryKey(
name: "PK_MovieGenre",
table: "MovieGenre",
columns: new[] { "genreId", "movieId" });
migrationBuilder.CreateIndex(
name: "IX_MovieGenre_movieId",
table: "MovieGenre",
column: "movieId");
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Genre_genreId",
table: "MovieGenre",
column: "genreId",
principalTable: "Genre",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Movie_movieId",
table: "MovieGenre",
column: "movieId",
principalTable: "Movie",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
<file_sep>using System;
namespace MovieShop.Core
{
public class Class1
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace MovieShop.Core.Entities
{
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public string? Overview { get; set; }
public string? Tagline { get; set; }
public decimal? Budget { get; set; }
public decimal? Revenue { get; set; }
public string? ImdbUrl { get; set; }
public string? TmdbUrl { get; set; }
public string? PosterUrl { get; set; }
public string? BackdropUrl { get; set; }
public string? OriginalLanguage { get; set; }
public DateTime? ReleaseDate { get; set; }
public int? RunTime { get; set; }
public decimal? Price { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? UpdatedDate { get; set; }
public string? UpdatedBy { get; set; }
public string? CreatedBy { get; set; }
public ICollection<Trailer> Trailers { get; set; }
public List<MovieGenre> MovieGenres { get; set; }
public List<MovieCast> MovieCasts { get; set; }
public List<MovieCrew> MovieCrews { get; set; }
public List<Review> Reviews { get; set; }
public decimal Rating { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace MovieShop.Infrastructure.Migrations
{
public partial class CastTableAndJoinTable2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Charater",
table: "MovieCast",
newName: "Character");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Character",
table: "MovieCast",
newName: "Charater");
}
}
}
<file_sep>using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using MovieShop.Core.Entities;
using MovieShop.Core.Helpers;
using MovieShop.Core.Models.Request;
using MovieShop.Core.Models.Response;
using MovieShop.Core.RepositoryInterfaces;
using MovieShop.Core.ServiceInterfaces;
namespace MovieShop.Infrastructure.Services
{
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
private readonly ICryptoService _cryptoService;
public UserService(IUserRepository userRepository, ICryptoService cryptoService)
{
_userRepository = userRepository;
_cryptoService = cryptoService;
}
public async Task AddFavorite(FavoriteRequestModel favoriteRequest)
{
throw new NotImplementedException();
}
public Task AddMovieReview(ReviewRequestModel reviewRequest)
{
throw new NotImplementedException();
}
public async Task<UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
{
//step1: check whether this user already exists in the db
var dbuser =await _userRepository.GetUserByEmail(requestModel.Email);
if (dbuser != null)
{
//we already have this user(email) in our db
throw new Exception("User already registered, Please try to login");
}
//step 2: create a random unique salt, always use industry hashing algorithm
var salt = _cryptoService.CreateSalt();
//step 3: We hash the password with the salt created by the above step
var hashedPassword = _cryptoService.HashPassword(requestModel.Password,salt);
//step 4: create user object so that we can save it to User Table
var user = new User
{
Email = requestModel.Email,
Salt = salt,
HashedPassword = hashedPassword,
FirstName = requestModel.FirstName,
LastName = requestModel.LastName
};
//Step 5 : Save it to db
var createdUser = await _userRepository.AddAsync(user);
var response = new UserRegisterResponseModel
{
Id = createdUser.Id,
Email = createdUser.Email,
FirstName = createdUser.FirstName,
LastName = createdUser.LastName
};
return response;
}
public async Task DeleteMovieReview(int userId, int movieId)
{
throw new NotImplementedException();
}
public async Task<bool> FavoriteExists(int id, int movieId)
{
throw new NotImplementedException();
}
public Task<FavoriteResponseModel> GetAllFavoritesForUser(int id)
{
throw new NotImplementedException();
}
public Task<PurchaseResponseModel> GetAllPurchasesForUser(int id)
{
throw new NotImplementedException();
}
public async Task<ReviewResponseModel> GetAllReviewsByUser(int id)
{
throw new NotImplementedException();
}
public async Task<PagedResultSet<User>> GetAllUsersByPagination(int pageSize = 20, int page = 0, string lastName = "")
{
throw new NotImplementedException();
}
public async Task<User> GetUser(string email)
{
throw new NotImplementedException();
}
public async Task<UserRegisterResponseModel> GetUserDetails(int id)
{
var user = await _userRepository.GetByIdAsync(id);
var model = new UserRegisterResponseModel {
Id = user.Id,
Email=user.Email,
FirstName=user.FirstName,
LastName=user.LastName
};
return model;
}
public Task<bool> IsMoviePurchased(PurchaseRequestModel purchaseRequest)
{
throw new NotImplementedException();
}
public Task PurchaseMovie(PurchaseRequestModel purchaseRequest)
{
throw new NotImplementedException();
}
public async Task RemoveFavorite(FavoriteRequestModel favoriteRequest)
{
throw new NotImplementedException();
}
public Task UpdateMovieReview(ReviewRequestModel reviewRequest)
{
throw new NotImplementedException();
}
//Execute when user login
public async Task<UserLoginResponseModel> ValidateUser(string email, string password)
{
var user = await _userRepository.GetUserByEmail(email);
if (user == null) return null;
var hashedpassword = _cryptoService.HashPassword(password, user.Salt);
var isSuccess = hashedpassword == user.HashedPassword;
var returnedModel = new UserLoginResponseModel
{
Id = user.Id,
Email=user.Email,
FirstName=user.FirstName,
LastName=user.LastName,
DateOfBirth=user.DateOfBirth,
};
return isSuccess ? returnedModel : null;
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace MovieShop.Infrastructure.Migrations
{
public partial class ReCreateJoinTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Genre_genresId",
table: "MovieGenre");
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Movie_moviesId",
table: "MovieGenre");
migrationBuilder.RenameColumn(
name: "moviesId",
table: "MovieGenre",
newName: "movieId");
migrationBuilder.RenameColumn(
name: "genresId",
table: "MovieGenre",
newName: "genreId");
migrationBuilder.RenameIndex(
name: "IX_MovieGenre_moviesId",
table: "MovieGenre",
newName: "IX_MovieGenre_movieId");
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Genre_genreId",
table: "MovieGenre",
column: "genreId",
principalTable: "Genre",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Movie_movieId",
table: "MovieGenre",
column: "movieId",
principalTable: "Movie",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Genre_genreId",
table: "MovieGenre");
migrationBuilder.DropForeignKey(
name: "FK_MovieGenre_Movie_movieId",
table: "MovieGenre");
migrationBuilder.RenameColumn(
name: "movieId",
table: "MovieGenre",
newName: "moviesId");
migrationBuilder.RenameColumn(
name: "genreId",
table: "MovieGenre",
newName: "genresId");
migrationBuilder.RenameIndex(
name: "IX_MovieGenre_movieId",
table: "MovieGenre",
newName: "IX_MovieGenre_moviesId");
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Genre_genresId",
table: "MovieGenre",
column: "genresId",
principalTable: "Genre",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_MovieGenre_Movie_moviesId",
table: "MovieGenre",
column: "moviesId",
principalTable: "Movie",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
| 74c10e5c0a3eff9e131835ead2d0eb02bd142f77 | [
"C#"
]
| 14 | C# | ZALIJIE/MovieShop | 6744da9512fa55be5b6b5b3eaea96f50735e2012 | ef8bfc3a6015f04cf4a9662bc42b180eb05bd0a7 |
refs/heads/master | <file_sep>function findJava(){
$.ajax({
url : "boke_java.do",
type : "post",
data: JSON.stringify(1),
contentType:"application/json;charset=utf-8",
datatype : "json",
success : function(result) {
var html = "<table class='table'><tr><td>标题</td><td>内容</td><td>备注</td></tr>";
for(var i = 1; i <= result.length; i++){
html+="<tr>"
html+="<td>"+result[i-1].bTitle+"</td>"
html+="<td>"+result[i-1].bContent+"</td>";
html+="<td>"+result[i-1].bDesc+"</td>";
html+="</tr>";
}
html += "</table>";
$("#java_table").html(html);
},
error : function(status) {
alert("错误");
}
});
}<file_sep>package com.lanou.dao;
import java.util.List;
import com.lanou.entity.Boke;
public interface BokeDao {
public List<Boke> findJava();
}
<file_sep>package com.lanou.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lanou.dao.BokeDao;
import com.lanou.entity.Boke;
@Controller
public class BokeController {
@Autowired
BokeDao bokeDao;
@RequestMapping("boke_java.do")
@ResponseBody
public List<Boke> findJava() {
List<Boke> bokes = bokeDao.findJava();
return bokes;
}
}
<file_sep>package com.lanou.entity;
public class Boke {
private int bId;
private String bTitle;
private String bContent;
private String bDesc;
public int getbId() {
return bId;
}
public void setbId(int bId) {
this.bId = bId;
}
public String getbTitle() {
return bTitle;
}
public void setbTitle(String bTitle) {
this.bTitle = bTitle;
}
public String getbContent() {
return bContent;
}
public void setbContent(String bContent) {
this.bContent = bContent;
}
public String getbDesc() {
return bDesc;
}
public void setbDesc(String bDesc) {
this.bDesc = bDesc;
}
}
<file_sep> //首页
$(function(){
$("#java").load("resources/app/java/java.html");
findJava();
})
//其他页面---路由器
function tab(id,url){
$('#'+id).load(url);//ajax加载页面
if(id == "java"){
findJava();//java
}
} | 3be9c93c15a88842f92db505bc9cb7bdb9e40de5 | [
"JavaScript",
"Java"
]
| 5 | JavaScript | xxs-Jay/bk | 4ead47e7362911c943701574a01160a8f4a2150a | fb19d204f00c24c8e906b0e0599715d7718eee18 |
refs/heads/master | <repo_name>rayvaldez/the-bachelor-todo-online-web-prework<file_sep>/lib/bachelor.rb
require 'pry'
def get_first_name_of_season_winner(data, season)
first_name = nil
data.each do |season_no, detail_hash|
if season_no == season
detail_hash.each do |att|
if att["status"] == "Winner"
first_name = att["name"].split(" ")[0]
end
end
end
end
first_name
end
def get_contestant_name(data, occupation)
data.each do |season, contestants|
contestants.each do |att|
if att["occupation"] == occupation
return att["name"]
end
end
end
end
def count_contestants_by_hometown(data, hometown)
count = 0
data.each do |season, contestants|
contestants.each do |att|
if att["hometown"] == hometown
count += 1
end
end
end
count
end
def get_occupation(data, hometown)
data.each do |season, contestants|
contestants.each do |att|
if att["hometown"] == hometown
return att["occupation"]
break
end
end
end
end
def get_average_age_for_season(data, season)
no_of_cont = 0
tot_age = 0
data.each do |season_no, contestants|
if season_no == season
contestants.each do |att|
tot_age += att["age"].to_i
no_of_cont += 1
end
end
end
average = tot_age.to_f / no_of_cont.to_f
average.to_s[3].to_i >= 5 ? average.ceil : average.to_i
end
| 27ca8589f3c00a5d1024d237195f0037bd454e6e | [
"Ruby"
]
| 1 | Ruby | rayvaldez/the-bachelor-todo-online-web-prework | e8308474487ced020ca180c6267dbe37a7506011 | 162238368e87e849d785c363d5e833f20105a772 |
refs/heads/master | <repo_name>ioanaemm/wemakewebsites-task<file_sep>/index.js
var crtSlide = 0;
var slideCount = $('.slide').length;
var MOBILE_BREAKPOINT = 768;
var isMobile = false;
var isMobileNavVisible = false;
var isMobileCartVisible = false;
$(document).ready(function() {
initSlider();
initMobileCart();
enableMobileNav();
distributeShoppingCart();
distributeNav();
$(window).resize(onWindowResize);
onWindowResize();
});
function onWindowResize() {
animateSlider(0);
if(isMobileNavVisible) {
hideMobileNav();
}
}
function distributeShoppingCart() {
var cartCloneDesktop = $('.temp-cart .cart-wrapper').clone();
$('header.desktop .shopping-cart').append(cartCloneDesktop);
var cartCloneMobile = $('.temp-cart .cart-wrapper').clone();
$('header.mobile .shopping-cart').append(cartCloneMobile);
$('.temp-cart .cart-wrapper').remove();
}
function distributeNav() {
var navCloneDesktop = $('.temp-nav .main-nav-list').clone();
$('header.desktop nav').append(navCloneDesktop);
var navCloneMobile = $('.temp-nav .main-nav-list').clone();
$('nav.mobile').append(navCloneMobile);
$('.temp-nav .main-nav-list').remove();
}
function initSlider() {
$('#left-arrow').click(prevSlide);
$('#right-arrow').click(nextSlide);
addSliderMarkers();
refreshMarkers();
}
function addSliderMarkers() {
var marker = '<div class="marker"></div>';
for(var i = 0; i < slideCount; i++) {
$('.carousel .markers').append($(marker));
}
$('.carousel .marker').each(function(index, markerElement) {
$(markerElement).click(function() {
crtSlide = index;
animateSlider(1.5);
});
});
}
function refreshMarkers() {
$('.carousel .marker').removeClass('selected');
$('.carousel .marker').each(function(index, markerElement) {
if(index === crtSlide) {
$(markerElement).addClass('selected');
}
});
}
function nextSlide() {
if(crtSlide < slideCount - 1) {
crtSlide++;
} else {
crtSlide = 0;
}
animateSlider(1.5);
}
function prevSlide() {
if(crtSlide > 0) {
crtSlide--;
} else {
crtSlide = slideCount - 1;
}
animateSlider(1.5);
}
function animateSlider(time) {
var viewportWidth = $('.slide-viewport').width();
if(window.innerWidth < 500) {
time /= 2;
}
TweenMax.to($('.slide-container'), time, {left: -crtSlide * viewportWidth, ease: Power2.easeInOut});
refreshMarkers();
}
function enableMobileNav() {
$('.drawer-container').click(toggleMobileNav);
}
function toggleMobileNav() {
if(isMobileNavVisible) {
hideMobileNav();
} else {
showMobileNav();
}
}
function showMobileNav() {
isMobileNavVisible = true;
TweenMax.to($('main'), 0.5, {left: 250, ease: Power2.easeInOut});
TweenMax.to($('nav.mobile'), 0.5, {left: 0, ease: Power2.easeInOut});
}
function hideMobileNav() {
isMobileNavVisible = false;
TweenMax.to($('main'), 0.5, {left: 0, ease: Power2.easeInOut});
TweenMax.to($('nav.mobile'), 0.5, {left: -250, ease: Power2.easeInOut});
}
function initMobileCart() {
$('header.mobile .shopping-cart .cart-icon').click(toggleMobileCart);
}
function toggleMobileCart() {
if(isMobileCartVisible) {
$('header.mobile .shopping-cart .cart-wrapper').hide();
} else {
$('header.mobile .shopping-cart .cart-wrapper').show();
}
isMobileCartVisible = !isMobileCartVisible;
}
| d04156b10003135403379fc76d81d5ba9bf82bd0 | [
"JavaScript"
]
| 1 | JavaScript | ioanaemm/wemakewebsites-task | a467d71086d9a5a23d9f5fd381d828a4770166e3 | 7a2b4b05b687bee92fb45949d195b9f300549fd8 |
refs/heads/master | <repo_name>JosefButzke/react-native-instagram-zoomable<file_sep>/src/helpers/getDistance.js
// @flow
import type {Touch} from '../types/Touch-type';
export function pow2abs(a: number, b: number) {
return Math.pow(Math.abs(a - b), 2);
}
function getDistance(touches: Array<Touch>) {
const [a, b] = touches;
if (a == null || b == null) {
return 0;
}
return Math.sqrt(pow2abs(a.pageX, b.pageX) + pow2abs(a.pageY, b.pageY));
}
export default getDistance;<file_sep>/src/helpers/getScale.js
// @flow
const SCALE_MULTIPLIER = 1.0;
export default function getScale(
currentDistance: number,
initialDistance: number
) {
return currentDistance / initialDistance * SCALE_MULTIPLIER;
}<file_sep>/src/InstagramProvider.js
// @flow
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import ReactNative, { Animated, StyleSheet, View, Dimensions } from 'react-native';
import type { Measurement } from './types/Measurement-type';
import {SelectedElement} from "./SelectedElement";
const {height} = Dimensions.get('window');
type SelectedElementType = {
element: Object,
measurement: Measurement;
};
type State = {
selected?: SelectedElementType;
isDragging: boolean;
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export class InstagramProvider extends PureComponent {
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.arrayOf(PropTypes.element),
]).isRequired,
renderBackground: PropTypes.func,
};
static defaultProps = {};
static childContextTypes = {
isDragging: PropTypes.bool,
onGestureStart: PropTypes.func,
onGestureRelease: PropTypes.func,
gesturePosition: PropTypes.object,
scaleValue: PropTypes.object,
};
state: State;
_scaleValue: Animated.Value;
_gesturePosition: Animated.ValueXY;
constructor() {
super(...arguments);
this._scaleValue = new Animated.Value(1);
this._gesturePosition = new Animated.ValueXY();
this.state = {
isDragging: false,
};
}
getChildContext() {
const { isDragging } = this.state;
return {
isDragging: isDragging,
onGestureStart: this.onGestureStart,
onGestureRelease: this.onGestureRelease,
gesturePosition: this._gesturePosition,
scaleValue: this._scaleValue,
};
}
onGestureStart = (selected) => {
this.setState({
selected,
isDragging: true,
});
};
onGestureRelease = () => {
this.setState({
isDragging: false
});
};
renderSelectedElement = () => {
const { renderBackground, detail } = this.props;
const { isDragging, selected } = this.state;
if (isDragging) {
return <SelectedElement selected={selected} renderBackground={renderBackground} detail={detail} />;
} else {
return null;
}
};
render() {
const { children } = this.props;
return (
<View style={styles.container}>
{children}
{this.renderSelectedElement()}
</View>
);
}
}
export default InstagramProvider;<file_sep>/src/SelectedElement.js
// @flow
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import ReactNative, { Animated, StyleSheet, View, Platform, Dimensions } from 'react-native';
const styles = StyleSheet.create({
root: {
flex: 1,
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
},
background: {
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
},
});
export class SelectedElement extends PureComponent {
static propTypes = {
selected: PropTypes.object,
renderBackground: PropTypes.func,
};
static defaultProps = {};
static contextTypes = {
gesturePosition: PropTypes.object,
scaleValue: PropTypes.object,
};
constructor() {
super(...arguments);
}
renderBackground = (selected, scaleValue, gesturePosition) => {
let backgroundOpacityValue = scaleValue.interpolate({
inputRange: [1, 3],
outputRange: [0, 1],
});
return (
<Animated.View
style={[
styles.background,
{
opacity: backgroundOpacityValue,
},
]}
/>
);
};
render() {
let { selected, renderBackground = this.renderBackground, detail } = this.props;
let { gesturePosition, scaleValue } = this.context;
let animatedStyle = {
transform: gesturePosition.getTranslateTransform(),
};
animatedStyle.transform.push({
scale: scaleValue,
});
console.log
let elementStyle = [
{
position: 'relative',
top: Platform.OS === 'ios' ? detail ? -35 : -78 : detail ? -25 : -(Dimensions.get('window').height / 10.078740157480315),
alignSelf: 'center',
width: selected.measurement.w,
height: selected.measurement.h,
opacity: parseFloat(JSON.stringify(animatedStyle.transform[1].translateY)) === 0 ? 0 : 1,
},
animatedStyle,
];
parseFloat(JSON.stringify(animatedStyle.transform[1].translateY)) === 0 && setTimeout(() => {
this.forceUpdate()
}, 10);
let children = selected && selected.element && selected.element.props && selected.element.props.children;
return (
<View style={styles.root}>
{ renderBackground(selected, scaleValue, gesturePosition) }
<Animated.View style={elementStyle}>
{ children }
</Animated.View>
</View>
);
}
}<file_sep>/README.md
# react-native-instagram-zoomable
### Description
A component to implement the Instagram Zoom-Draggable-Effect for any component in React-Native.
### Installation
```shell
npm i --save https://github.com/postillonmedia/react-native-instagram-zoomable.git
```
### Usage
#### InstagramProvider
props:
* children
* renderBackground: _(selected: , scaleValue, gesturePosition) => React.Component_
#### ElementContainer
### Thank you
Thank you to [<NAME>](https://medium.com/@audytanudjaja) and his article on Medium: [React Native UI Challenge: Building Instagram Zoom-Draggable Photo](https://medium.com/@audytanudjaja/react-native-ui-challenge-building-instagram-zoom-draggable-photo-9127413b1d29)<file_sep>/index.js
import InstagramProvider from './src/InstagramProvider';
import ElementContainer from './src/ElementContainer';
export {
InstagramProvider,
ElementContainer,
} | fa0ce95c4acfdbacaf51d418186527f467cbf442 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | JosefButzke/react-native-instagram-zoomable | 40cea90935aef8ec5875eaf75e362ee6f162fd7e | b875432e759733a17f756d86d463ddbefac6cf2f |
refs/heads/master | <file_sep>## Happah-Applets
This set of Web-applications provides an interactive way to test geometric algorithms
by visualizing them via [three.js](https://threejs.org/).
## Building Dependencies
* jre as dependency of Google Closure Compiler
* python2
* python-yaml
* node 7.x
* webpack 2.1.0
* node modules:
* babel-loader
* babel-core
* json-loader
* yaml-loader
* i18n-js
* jquery
* three
* mathjax
* three-trackballcontrols
## Building
Run `./util/build/build.sh` for a complete build.
After initial build, you can use `webpack -w` in main directory so Webpack
will compile in the background on any changes made on files.
## Running
In order to test the applets on your local machine, you need to run the simpleWebServer.py from the main directory.
```
cd happah-applets
python ./util/webserver/simpleWebServer.py
```
With the script running, connect to localhost:8000 with your browser to test the applets.
## Applet structure
Every applet has it's own subdirectory in `js/` and `html/`.
The `js/<applet name>` directory contains two mandatory files:
**main.js** and **algorithm.js**.
Where main.js specifies the basic applet layout and algorithm.js the algorithm
to be visualized.
In case there are more files that are only used by one applet, they belong in
this directory too.
Files that are used by more than one applet, belong in the `js/lib` directory.
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// @author: <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as STORYBOARD from "./storyboard";
import * as IMPOSTOR from "./spherical-impostor";
import * as UTIL from "./util";
let s_controlPoints = Symbol('controlPoints');
let s_ratio = Symbol('ratio');
let s_scrollbar = Symbol('scrollbar');
/**
* Encapsulate functionality of De' Casteljau algorithm.
* takes t as division ratio and a callback function
*/
class DeCasteljauAlgorithm {
/** Default constructor. */
constructor(controlPoints, scrollbar) {
this[s_controlPoints] = controlPoints;
this.storyboard = this.storyboard.bind(this);
this[s_scrollbar] = scrollbar;
this[s_ratio] = (scrollbar == null) ? 0.5 : scrollbar.value;
}
evaluate(t = this[s_scrollbar].value, callback = null) {
let segmentLength = this[s_controlPoints].length;
let points = new Array(segmentLength);
points[0] = new Array(segmentLength);
for (let i in this[s_controlPoints]) {
points[0][i] = this[s_controlPoints][i];
}
// until only 1 point remains
for (let i = 0; i < segmentLength - 1; i++) {
points[i + 1] = new Array(segmentLength - i - 1);
// calc next level points
for (let j = 0; j < points[i].length - 1; j++) {
let newPoint = points[i][j].clone();
newPoint.multiplyScalar(1 - t);
let tmpPoint = points[i][j + 1].clone();
tmpPoint.multiplyScalar(t);
newPoint.add(tmpPoint);
points[i + 1][j] = newPoint;
}
callback(points[i + 1]);
}
return points[points.length - 1][0];
}
set scrollbar(scrollbar) {
this[s_scrollbar] = scrollbar;
}
/**
* Calculate a curve segment strip using the subdivision treat of the
* De' Casteljau algorithm.
*
* Additional Memory usage: O(s*s),
* where s is the length of a segment.
*
* @param nSubdivisions times the segmentstrip points are divided
* @param t the factor/weight used in the De' Casteljau algorithm
*
* @return an array of ordered 3D Vectors on the curve
*/
subdivide(nSubdivisions = 4, t = this[s_scrollbar].value) {
// preCalculate necessary array length to avoid later size
// changes
let segmentLength = this[s_controlPoints].length;
if (segmentLength == 0) {
return [];
}
let arrayLength = segmentLength;
for (let i = 0; i < nSubdivisions; i++) {
arrayLength = 2 * arrayLength - 1;
}
// init array
let result = new Array(arrayLength);
for (let i = 0; i < segmentLength - 1; i++) {
result[i] = this[s_controlPoints][i].clone();
}
result[arrayLength - 1] = this[s_controlPoints][this[s_controlPoints].length - 1].clone();
let iterator = arrayLength - 1;
// start iterative calculation here
for (let n = 0; n < nSubdivisions; n++) {
for (let segmentStart = 0; segmentStart < arrayLength - 1; segmentStart += iterator) {
let offset = Math.floor(iterator / 2);
// calc de casteljau subpoints
let localPoints = new Array(segmentLength);
localPoints[0] = new Array(segmentLength);
// copy local control points
for (let i = 0; i < segmentLength - 1; i++) {
localPoints[0][i] = result[segmentStart + i].clone();
}
localPoints[0][segmentLength - 1] = result[segmentStart + iterator].clone();
// calc a de casteljau point and save each step in an
// array
// the first element of each array is part of the left
// curve segment, the last is part of the right
// This part uses O(s*s) memory, where s is the
// defined length of a segment.
for (let i = 0; i < segmentLength - 1; i++) {
localPoints[i + 1] = new Array(segmentLength - i - 1);
for (let j = 0; j < localPoints[i].length - 1; j++) {
let newPoint = localPoints[i][j].clone();
newPoint.multiplyScalar(1 - t);
let tmpPoint = localPoints[i][j + 1].clone();
tmpPoint.multiplyScalar(t);
newPoint.add(tmpPoint);
localPoints[i + 1][j] = newPoint;
}
}
// add left segment to result
for (let i = 1; i < localPoints.length - 1; i++) {
result[segmentStart + i] = localPoints[i][0];
}
// add right segment to result
for (let i = 0; i < localPoints.length - 1; i++) {
result[segmentStart + offset + i] = localPoints[
localPoints.length - 1 - i][localPoints[
localPoints.length - 1 - i].length - 1];
}
}
iterator = Math.floor(iterator / 2);
}
return result;
}
/**
* Returns a storyboard with frames that contain the different steps
* of the algorithm
*/
storyboard() {
let ratio;
if (this[s_scrollbar] == null) {
ratio = 0.5;
} else {
ratio = this[s_scrollbar].value;
}
// Create the first frame by hand
let storyboard = new STORYBOARD.Storyboard(this);
let frame0 = new STORYBOARD.Storyboard.Frame();
frame0.lines[0] = UTIL.Util.insertSegmentStrip(this[s_controlPoints], 0xff0000);
frame0.title = "Controlpolygon";
frame0.points = new THREE.Object3D();
storyboard.append(frame0);
if (this[s_controlPoints].length == 0) {
// Add a dummy mesh
frame0.lines[0] = new THREE.Object3D();
return storyboard;
}
// matrix of points for every iteration
let pointMatrix = new Array();
// First set of points is the control polygon
pointMatrix.push(this[s_controlPoints]);
// fill matrix with points from each iteration
this.evaluate(ratio, function add(points) {
pointMatrix.push(points);
});
// Helper points radius
let radius = 3;
let color = 0x3d3d3d;
// Skip the control polygon
for (let i = 1; i < pointMatrix.length; i++) {
let frame = new STORYBOARD.Storyboard.Frame();
frame.title = "Step " + i;
// Impostor template
let template = new IMPOSTOR.SphericalImpostor(radius);
frame.points = new THREE.Object3D();
//frame.points = pointMatrix[i];
for (let k in pointMatrix[i]) {
let imp = template.clone();
imp.position.copy(pointMatrix[i][k]);
imp.material.uniforms.diffuse.value.set(color);
frame.points.add(imp);
}
let pointStack = new Array();
// The previous iteration has one point more.
for (let k in pointMatrix[i]) {
// Push first one from last iteration
pointStack.push(pointMatrix[i - 1][k]);
// Now add one point from current iteration
pointStack.push(pointMatrix[i][k]);
}
// Add last point from previous iteration
pointStack.push(pointMatrix[i - 1][pointMatrix[i - 1].length - 1]);
// Iterate over stacksize and make a segment from 2 points
for (let k = 2; k <= pointStack.length; k++) {
let segment = new Array();
segment.push(pointStack[k - 1]);
segment.push(pointStack[k - 2]);
// Paint the strips in the interval's color
let strip = (k % 2 == 0) ?
UTIL.Util.insertSegmentStrip(segment, 0x3D3D3D) : UTIL.Util.insertSegmentStrip(segment, 0xFF0000);
frame.lines.push(strip);
}
// Merge with the previous frame's lines
if (i != 1) {
frame.lines = frame.lines.concat(storyboard.frame(storyboard.size() - 1).lines);
// Remove the last mesh from the previous iteration
// to prevent overlapping lines
frame.lines.pop();
}
// Also add the newly generated polygon
frame.lines.push(UTIL.Util.insertSegmentStrip(pointMatrix[i], 0xFF0000));
frame.points.children = frame.points.children.concat(storyboard.frame(storyboard.size() - 1).points);
storyboard.append(frame);
}
// Create the last frame also by hand
let frameLast = new STORYBOARD.Storyboard.Frame();
frameLast.title = "Limes curve";
frameLast.lines[0] = UTIL.Util.insertSegmentStrip(this.subdivide(4, 0.5), 0xff0000);
// Can't create a curve from two points.
if (this[s_controlPoints].length > 2) {
storyboard.append(frameLast);
}
return storyboard;
}
} // class DeCasteljauAlgorithm
export {
DeCasteljauAlgorithm
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// @author <NAME> (<EMAIL>)
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
let s_lines = Symbol('lines');
let s_points = Symbol('points');
let s_algorithm = Symbol('algorithm');
let s_storyboard = Symbol('storyboard');
let s_storyboardNeedsRebuild = Symbol('storyboardneedsrebuild');
let s_needsRebuild = Symbol('needsrebuild');
let s_grid = Symbol('grid');
let s_gridState = Symbol('gridstate');
let s_animationTimer = Symbol('animationtimer');
class Scene extends THREE.Scene {
constructor() {
super();
this[s_points] = new THREE.Object3D();
this[s_lines] = new THREE.Object3D();
this[s_gridState] = false;
this[s_grid] = new THREE.GridHelper(100, 10);
this.requestStoryboardBuild = this.requestStoryboardBuild.bind(this);
this.requestSceneBuild = this.requestSceneBuild.bind(this);
this.nextFrame = this.nextFrame.bind(this);
this.previousFrame = this.previousFrame.bind(this);
this.toggleGrid = this.toggleGrid.bind(this);
this.startAnimation = this.startAnimation.bind(this);
this.stopAnimation = this.stopAnimation.bind(this);
$(document).on("rebuildStoryboard", this.requestStoryboardBuild);
$(document).on("dragging", this.requestStoryboardBuild);
$(document).on("change", this.requestSceneBuild);
$(document).on("hph-forward", this.nextFrame);
$(document).on("hph-backward", this.previousFrame);
$(document).on("hph-play", this.startAnimation);
$(document).on("hph-pause", this.stopAnimation);
$(document).on("grid-toggle", this.toggleGrid);
}
set algorithm(algorithm) {
this[s_algorithm] = algorithm;
this[s_storyboard] = algorithm.storyboard();
this[s_storyboardNeedsRebuild] = true;
}
startAnimation(event) {
this[s_animationTimer] = window.setInterval(this.nextFrame, 1000);
}
stopAnimation(event) {
window.clearInterval(this[s_animationTimer]);
}
toggleGrid(event) {
this[s_gridState] = !this[s_gridState];
if (this[s_gridState])
this.add(this[s_grid]);
else
this.remove(this[s_grid]);
}
nextFrame() {
this[s_storyboard].nextFrame();
$.event.trigger({
type: "change",
message: "switched to next frame!"
});
}
previousFrame() {
this[s_storyboard].previousFrame();
$.event.trigger({
type: "change",
message: "switched to previous frame!"
});
}
/*
* Triggered whenever the storyboard needs to be rebuilt,
* for example a control-point has moved.
*/
requestStoryboardBuild(event) {
this[s_storyboardNeedsRebuild] = true;
}
/*
* Triggered whenever the scene needs to be rebuilt.
*/
requestSceneBuild(event) {
this[s_needsRebuild] = true;
}
/*
* Should be called every frame.
*/
update() {
if (this[s_storyboardNeedsRebuild]) {
let currentIndex = this[s_storyboard].index;
this[s_storyboard] = this[s_algorithm].storyboard();
this[s_storyboard].index = currentIndex;
this[s_needsRebuild] = true;
this[s_storyboardNeedsRebuild] = false;
// TODO: labelmanager update positions here?
}
if (this[s_needsRebuild]) {
let currentFrame = this[s_storyboard].currentFrame();
$('#hph-label').text("Frame: " + currentFrame.title);
let lines = currentFrame.lines;
let points = currentFrame.points;
//this[s_labelmanager].removeLabelsByTag("points");
//for (let i = 0; i < points.children.length; i++) {
//this[s_labelmanager].addLabel(currentFrame.labels[i], points.children[i].position, "points", false);
//}
for (let line of this[s_lines].children) {
if (line.geometry)
line.geometry.dispose();
if (line.material)
line.material.dispose();
}
this.remove(this[s_lines])
for (let point of this[s_points].children) {
if (point.geometry)
point.geometry.dispose();
if (point.material)
point.material.dispose();
}
this.remove(this[s_points]);
this[s_points] = points;
this.add(points);
this[s_lines] = new THREE.Object3D()
for (let i in lines) {
this[s_lines].add(lines[i])
}
this.add(this[s_lines])
this[s_needsRebuild] = false;
}
}
}
export {
Scene
};
<file_sep>#! /usr/bin/env python3
import http.server
import socketserver
class MySimpleHTTPHandler( http.server.SimpleHTTPRequestHandler ):
def send_head(self):
self.send_header("Access-Control-Allow-Origin", "*")
super.send_head(self)
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// @author: <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
/** Unit tests for curve class. */
"use strict";
define(['../js/lib/decasteljaualgorithm.js'], function(DECASTELJAU_ALGORITHM) {
var run = function() {
test('Generated curve points of subdivision using de casteljau should equal precalced ones.', function() {
var expectedResult = [
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(1.9375, 0.0625, 0),
new THREE.Vector3(2.8125, 0.1796875, 0),
new THREE.Vector3(3.6875, 0.296875, 0),
new THREE.Vector3(4.5, 0.46875, 0),
new THREE.Vector3(5.25, 0.6875, 0),
new THREE.Vector3(6, 0.90625, 0),
new THREE.Vector3(6.6875, 1.171875, 0),
new THREE.Vector3(7.3125, 1.4765625, 0),
new THREE.Vector3(7.9375, 1.78125, 0),
new THREE.Vector3(8.5, 2.125, 0),
new THREE.Vector3(9, 2.5, 0),
new THREE.Vector3(9.5, 2.875, 0),
new THREE.Vector3(9.9375, 3.28125, 0),
new THREE.Vector3(10.3125, 3.7109375, 0),
new THREE.Vector3(10.6875, 4.140625, 0),
new THREE.Vector3(11, 4.59375, 0),
new THREE.Vector3(11.25, 5.0625, 0),
new THREE.Vector3(11.5, 5.53125, 0),
new THREE.Vector3(11.6875, 6.015625, 0),
new THREE.Vector3(11.8125, 6.5078125, 0),
new THREE.Vector3(11.9375, 7, 0),
new THREE.Vector3(12, 7.5, 0),
new THREE.Vector3(12, 8, 0),
new THREE.Vector3(12, 8.5, 0),
new THREE.Vector3(11.9375, 9, 0),
new THREE.Vector3(11.8125, 9.4921875, 0),
new THREE.Vector3(11.6875, 9.984375, 0),
new THREE.Vector3(11.5, 10.46875, 0),
new THREE.Vector3(11.25, 10.9375, 0),
new THREE.Vector3(11, 11.40625, 0),
new THREE.Vector3(10.6875, 11.859375, 0),
new THREE.Vector3(10.3125, 12.2890625, 0),
new THREE.Vector3(9.9375, 12.71875, 0),
new THREE.Vector3(9.5, 13.125, 0),
new THREE.Vector3(9, 13.5, 0),
new THREE.Vector3(8.5, 13.875, 0),
new THREE.Vector3(7.9375, 14.21875, 0),
new THREE.Vector3(7.3125, 14.5234375, 0),
new THREE.Vector3(6.6875, 14.828125, 0),
new THREE.Vector3(6, 15.09375, 0),
new THREE.Vector3(5.25, 15.3125, 0),
new THREE.Vector3(4.5, 15.53125, 0),
new THREE.Vector3(3.6875, 15.703125, 0),
new THREE.Vector3(2.8125, 15.8203125, 0),
new THREE.Vector3(1.9375, 15.9375, 0),
new THREE.Vector3(1, 16, 0),
new THREE.Vector3(0, 16, 0),
];
// calc
var controlpoints = [
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(16, 0, 0),
new THREE.Vector3(16, 16, 0),
new THREE.Vector3(0, 16, 0),
];
var mycurve = new DECASTELJAU_ALGORITHM.DeCasteljauAlgorithm(controlpoints);
var curveSegments = mycurve.subdivide();
// check result
for (var i in curveSegments) {
equal(curveSegments[i].x, expectedResult[i].x);
equal(curveSegments[i].y, expectedResult[i].y);
equal(curveSegments[i].z, expectedResult[i].z);
}
});
};
return {
run: run
}
});
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// An applet explaining how two curves defined by an control polygon can be
// joined to achieve c^k continuity. Meaning the created curve can be derived k
// times in each point.
//
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
import * as ALGORITHM from "./algorithm";
// Canvas element
$(document).ready(function() {
let canvas = $('.hph-canvas')[0];
let scene = new HAPPAH.Scene();
scene.add(HAPPAH.Defaults.basicLights());
let origin = new THREE.Vector3(-120, 0, -30);
let viewport = new HAPPAH.Viewport(canvas, scene);
let controlPolygon = new HAPPAH.ControlPolygon(scene, viewport, 4);
// Initialize some points
controlPolygon.addControlPoints([
new THREE.Vector3(-50, 0, 60).add(origin),
new THREE.Vector3(-40, 0, 0).add(origin),
new THREE.Vector3(40, 0, 0).add(origin),
new THREE.Vector3(50, 0, 60).add(origin)
]);
let algorithm = new ALGORITHM.Algorithm(controlPolygon.vectors, viewport);
scene.algorithm = algorithm;
let dragControls = new HAPPAH.DragControls(
controlPolygon.points.children, viewport);
viewport.camera.position.set(0, 1000, 0);
viewport.camera.lookAt(scene.position);
viewport.camera.zoom = 2.5;
viewport.camera.updateProjectionMatrix();
let toolbar = HAPPAH.Defaults.toolbarMenu(
".tool-bar-top");
let menu = HAPPAH.Defaults.playerMenu("#hph-controls");
let guide = new HAPPAH.Guide();
console.log("HAPPAH initialized.");
});
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Two-handle-Scrollbar
// scrollbar with two handles in different colors
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "./happah";
import * as SCROLLBAR from "./scrollbar";
import * as UTIL from "./util";
import * as COLORS from "./colors";
let s_handles = Symbol('handles');
let s_lineMiddle = Symbol('linemiddle');
class IntervalScrollbar extends SCROLLBAR.Scrollbar {
constructor(position, viewport, initialValue) {
super(position, viewport, initialValue);
this[s_handles] = [this.handle];
this.addHandle(0.8, 0x3d3d3d);
this.setIntervalColors([
COLORS.Colors.COLOR1,
COLORS.Colors.COLOR2,
COLORS.Colors.COLOR3
]);
// Re-Setup lines:
// left goes from 0 to first handle
// middle goes from first handle to second handle
// right goes from second handle to 1
let lineGeo = new THREE.Geometry();
lineGeo.vertices.push(this[s_handles][0].position);
lineGeo.vertices.push(this[s_handles][1].position);
let lineMat = new THREE.LineBasicMaterial({
color: this.intervalColors[1],
linewidth: 5
});
this[s_lineMiddle] = new THREE.Line(lineGeo, lineMat);
this.add(this[s_lineMiddle]);
this.lineRight.geometry.vertices[1] = this[s_handles][1].position;
// Colors may have changed
this.lineRight.material.color.set(this.intervalColors[2]);
this.lineLeft.material.color.set(this.intervalColors[0]);
}
addHandle(value = 0.5, color) {
let handle = this.createHandle(value, color);
handle.value = value;
this[s_handles].push(handle);
// Add to scene
this.add(handle);
return handle;
}
removeHandles() {
// Remove them from the scene first
for (let i = 0; i < this[s_handles].length - 1; i++) {
this.remove(this[s_handles][i]);
}
this[s_handles] = [];
}
valueOf(index) {
if (index >= this[s_handles].length)
return -1;
return this[s_handles][index].value;
}
show(handle) {
this.add(handle);
}
hide(handle) {
this.remove(handle);
}
get handles() {
return this[s_handles];
}
updateLines(handle) {
this.lineLeft.geometry.vertices[0] = this[s_handles][0].position;
this.lineRight.geometry.vertices[1] = this[s_handles][1].position;
this[s_lineMiddle].geometry.vertices = [this[s_handles][0].position, this[s_handles][1].position];
this.lineLeft.geometry.verticesNeedUpdate = true;
this.lineRight.geometry.verticesNeedUpdate = true;
this[s_lineMiddle].geometry.verticesNeedUpdate = true;
}
/** Called when a mouse button is pressed */
mouseDown(event) {
event.preventDefault();
if (this.enabled == false) {
return;
}
// TODO: don't calculate the position every time.
// -> only on window resize...
let elementPosition = UTIL.Util.getElementPosition(event.currentTarget);
// Get mouse position
let mouseX = ((event.clientX - elementPosition.x) / event.currentTarget.width) * 2 - 1;
let mouseY = -((event.clientY - elementPosition.y) / event.currentTarget.height) * 2 + 1;
let mouseVector = new THREE.Vector3(mouseX, mouseY, -1);
// Set up ray from mouse position
this.raycaster.setFromCamera(mouseVector, this.camera);
// Find all intersected objects
let intersects = this.raycaster.intersectObjects(this[s_handles]);
if (intersects.length > 0) {
// Enable drag-mode
this.selectedObject = intersects[0].object;
// Disable the controls
//this.controls.enabled = false;
$.event.trigger({
type: "draggingStarted",
message: "scrollbar dragging started!"
});
} else {
this.selectedObject = false;
}
}
/** Called whenever a mouse button is moved */
mouseMove(event) {
event.preventDefault();
if (this.enabled == false) {
return;
}
let elementPosition = UTIL.Util.getElementPosition(event.currentTarget);
// Get mouse position
let mouseX = ((event.clientX - elementPosition.x) / event.currentTarget.width) * 2 - 1;
let mouseY = -((event.clientY - elementPosition.y) / event.currentTarget.height) * 2 + 1;
let mouseVector = new THREE.Vector3(mouseX, mouseY, -1);
// Set up ray from mouse position
this.raycaster.setFromCamera(mouseVector, this.camera);
if (this.selectedObject) {
// Reposition the object based on the intersection point with the plane
let newPos = this.selectionLine.closestPointToPoint(this.raycaster.ray.intersectPlane(this.selectionPlane));
newPos.sub(this.position);
this.selectedObject.position.copy(newPos);
// Update line segments
this.updateLines();
// In case we are beyond the left border
if (this.handle.position.x < -75) {
// hide the black line
this.lineLeft.visible = false;
} else {
this.lineLeft.visible = true;
}
// Same goes for the right line
if (this.handle.position.x > 75) {
this.lineRight.visible = false;
} else {
this.lineRight.visible = true;
}
// Update our line sections
this.lineRight.geometry.verticesNeedUpdate = true;
this.lineLeft.geometry.verticesNeedUpdate = true;
// New value means new storyboard
$.event.trigger({
type: "dragging",
message: "scrollbar dragging!"
});
}
}
} //class IntervalScrollbar
export {
IntervalScrollbar
};
<file_sep>import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
import * as ALGORITHM from "./algorithm";
$(document).ready(function() {
let canvas = $('.hph-canvas')[0];
let scene = new HAPPAH.Scene();
scene.add(HAPPAH.Defaults.basicLights());
let viewport = new HAPPAH.Viewport(canvas, scene);
let controlPolygon = new HAPPAH.ControlPolygon(scene, viewport, 0);
// Enable this if you want to add controlPoints at runtime
//controlPolygon.listenTo(viewport.renderer.domElement);
// Initialize some points
controlPolygon.addControlPoints([
new THREE.Vector3(50, 0, 100),
new THREE.Vector3(50, 0, 50),
new THREE.Vector3(50, 0, 0),
new THREE.Vector3(50, 0, -50),
new THREE.Vector3(50, 0, -100),
]);
let algorithm = new ALGORITHM.Algorithm(controlPolygon.vectors);
// Canvas coordinates relative to middle of canvas element
let pos = new THREE.Vector3(0, -(1 / 1.2), 0);
let scrollbar = new HAPPAH.Scrollbar(pos, viewport);
algorithm.scrollbar = scrollbar;
scene.algorithm = algorithm;
scrollbar.listenTo(viewport.renderer.domElement);
viewport.overlay.add(scrollbar);
viewport.camera.position.set(1000, 1000, 0);
viewport.camera.lookAt(scene.position);
viewport.camera.zoom = 2.5;
viewport.camera.updateProjectionMatrix();
// Menu & toolbar
let toolbar = HAPPAH.Defaults.toolbarMenu(".tool-bar-top");
let menu = HAPPAH.Defaults.playerMenu("#hph-controls");
let guide = new HAPPAH.Guide();
console.log("happah initialized.");
});
<file_sep>import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
import * as ALGORITHM from "./algorithm";
$(document).ready(function() {
// Canvas element
let canvas = $('.hph-canvas')[0];
let scene = new HAPPAH.Scene();
scene.add(HAPPAH.Defaults.basicLights());
let algorithm = new ALGORITHM.Algorithm(new THREE.Vector3(-50, 0, +50));
let viewport = new HAPPAH.Viewport(canvas, scene);
scene.algorithm = algorithm;
viewport.camera.position.set(0, 1000, 0);
viewport.camera.lookAt(scene.position);
viewport.camera.zoom = 4;
viewport.camera.updateMatrixWorld();
viewport.camera.updateProjectionMatrix();
// Create a 1x1 frame
// X-Axis
let geometry = new THREE.CylinderGeometry(0.5, 0.5, 130, 16);
let coneGeo = new THREE.CylinderGeometry(0, 2, 6, 5, 16);
coneGeo.rotateZ(-Math.PI / 2);
coneGeo.translate(68, 0, 0);
geometry.rotateZ(Math.PI / 2);
geometry.merge(coneGeo);
let secondGeometry = new THREE.CylinderGeometry(0.5, 0.5, 101, 16);
secondGeometry.rotateZ(Math.PI / 2);
secondGeometry.rotateY(Math.PI / 2);
secondGeometry.translate(-50, 0, -50);
geometry.merge(secondGeometry);
secondGeometry.translate(100, 0, 0);
geometry.merge(secondGeometry);
let thirdGeometry = new THREE.CylinderGeometry(0.5, 0.5, 101, 16);
thirdGeometry.rotateZ(-Math.PI / 2);
thirdGeometry.translate(0, 0, -100);
geometry.merge(thirdGeometry);
let material = new THREE.MeshBasicMaterial({
color: 0x4d4d4d
});
let frame = new THREE.Mesh(geometry, material);
frame.position.set(0, 0, 50);
scene.add(frame);
// Add labels
viewport.labelManager.addLabel("0", new THREE.Vector3(-52, 0, 50), "axis", false);
viewport.labelManager.addLabel("1", new THREE.Vector3(55, 0, 50), "axis", false);
viewport.labelManager.addLabel("1", new THREE.Vector3(-52, 0, -55), "axis", false);
// Buttons
let menu = HAPPAH.Defaults.playerMenu("#hph-controls");
let toolbar = new HAPPAH.Menu(".tool-bar-top");
toolbar.addButton("Toggle grid", "grid-toggle", "fa-th", "Grid");
toolbar.addButton("Start Tour", "show-help", "fa-info", "Guide");
let guide = new HAPPAH.Guide();
console.log("happah initialized.");
});
<file_sep> import * as $ from "jquery";
import * as THREE from "three";
import * as UTIL from "./util";
var s_camera = Symbol('camera');
var s_oldMouse = Symbol('old');
var s_enabled = Symbol('enabled');
var s_cameraTarget = Symbol('cameratarget');
var s_scene = Symbol('scene');
var s_helper = Symbol('helper');
var s_pq = Symbol('pq');
var s_ppos = Symbol('ppos');
class TrackballControls {
constructor(camera, scene) {
this.mouseDown = this.mouseDown.bind(this);
this.mouseMove = this.mouseMove.bind(this);
this.mouseUp = this.mouseUp.bind(this);
this[s_camera] = camera;
this[s_oldMouse] = camera.position;
this[s_enabled] = false;
this[s_scene] = scene;
this[s_ppos] = new THREE.Vector3();
this[s_pq] = new THREE.Quaternion();
// The target where the camera is looking
this[s_cameraTarget] = new THREE.Vector3(0, 0, 0);
if ((camera && camera.isPerspectiveCamera)) {
//
} else if ((camera && camera.isOrthographicCamera)) {
this[s_oldMouse].setZ((camera.near + camera.far) / (camera.near - camera.far)).unproject(camera);
} else {
console.error('HAPPAH.TrackballControls: Unsupported camera type.');
}
}
listenTo(domElement) {
domElement.addEventListener('mousedown', this.mouseDown, false);
domElement.addEventListener('mousemove', this.mouseMove, false);
domElement.addEventListener('mouseup', this.mouseUp, false);
}
stopListeningTo(domElement) {
domElement.removeEventListener('mousedown', this.mouseDown, false);
domElement.removeEventListener('mousemove', this.mouseMove, false);
domElement.removeEventListener('mouseup', this.mouseUp, false);
}
mouseDown(event) {
// Enable trackball controls
this[s_enabled] = true;
}
mouseMove(event) {
if (!this[s_enabled]) {
return;
}
// Get html position for origin offset
var elementPosition = UTIL.Util.getElementPosition(event.currentTarget);
// Calculate relative mouse position
var newMouse = new THREE.Vector3();
newMouse.x = ((event.clientX - elementPosition.x) / event.currentTarget.width) * 2 - 1;
newMouse.y = -((event.clientY - elementPosition.y) / event.currentTarget.height) * 2 + 1;
// Direction of the camera
var eyeDirection = this[s_camera].position.sub(this[s_cameraTarget]);
// Extracted from THREE.Raycaster
if ((this[s_camera] && this[s_camera].isPerspectiveCamera)) {
//this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
//this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
} else if ((this[s_camera] && this[s_camera].isOrthographicCamera)) {
newMouse.setZ((this[s_camera].near + this[s_camera].far) / (this[s_camera].near - this[s_camera].far)).unproject(this[s_camera]);
} else {
console.error('HAPPAH.TrackballControls: Unsupported camera type.');
}
// Direction in which we moved the cursor
var mouseDirection = new THREE.Vector3(newMouse.x - this[s_oldMouse].x, newMouse.y - this[s_oldMouse].y, newMouse.z - this[s_oldMouse].z);
// TODO: calculate median of previous directions to get smooth
// movement
if (mouseDirection.length() < 2) {
return;
}
var axis = mouseDirection.cross(this[s_camera].getWorldDirection()).normalize()
this[s_scene].remove(this[s_helper]);
this[s_helper] = new THREE.ArrowHelper(axis, new THREE.Vector3(0, 0, 0), 10);
this[s_scene].add(this[s_helper]);
// Calculate distance to previous point
var delta = mouseDirection.length();
// Calculate angle to move TODO parameter for radius
var angle = 0.1; //2 * Math.asin(delta / 2 * 4) * (Math.PI / 180);
// Create the quaternion
//this[s_pq].copy(this[s_camera].quaternion);
//var qm = new THREE.Quaternion();
//qm.setFromAxisAngle(axis, angle);
//var q = new THREE.Quaternion();
//THREE.Quaternion.slerp(this[s_camera].quaternion, q, qm, 0.07);
//this[s_camera].quaternion.copy(qm);
//this[s_camera].quaternion.normalize();
// Apply quaternion
//this[s_camera].setRotationFromAxisAngle(axis, angle);
var previousAngle = this[s_camera].quaternion.w;
//this[s_camera].setRotationFromAxisAngle(axis, previousAngle);
this[s_camera].position.applyAxisAngle(axis, angle);
this[s_camera].lookAt(this[s_scene].position);
//this[s_camera].quaternion.w += 1;
this[s_oldMouse] = newMouse;
$.event.trigger({
type: "change",
message: "trackball controls update"
});
}
mouseUp(event) {
this[s_enabled] = false;
}
} // Class TrackballControls
export {
TrackballControls
}
<file_sep>"use strict";
require.config({
shim: {
'three': {
exports: 'THREE'
},
'QUnit': {
exports: 'QUnit',
init: function() {
QUnit.config.autoload = false;
QUnit.config.autostart = false;
}
},
},
paths: {
jquery: "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min",
three: "http://threejs.org/build/three",
QUnit: 'https://code.jquery.com/qunit/qunit-1.23.0'
},
});
require(
['QUnit', 'three', './decasteljaualgorithmtest'],
function(QUnit, THREE, DECASTELJAU_TEST) {
DECASTELJAU_TEST.run();
QUnit.load();
QUnit.start();
}
);
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// @author: <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as COLORS from "./colors";
const label_font_size = "14pt";
let s_head = Symbol('head');
let s_tail = Symbol('tail');
let s_viewport = Symbol('viewport');
let s_counter = Symbol('counter');
class LabelManager {
constructor(viewport) {
this.addLabel = this.addLabel.bind(this);
this.updatePositions = this.updatePositions.bind(this);
$(document).on("dragging", this.updatePositions);
this[s_counter] = 0;
this.sceneCamera = viewport.camera;
this.overlayCamera = viewport.overlayCam;
this[s_viewport] = viewport;
this[s_head] = null;
this.canvas = viewport.canvas;
}
/**
* Add a new label at the given position.
* If overview = true, the label will be projected by the overlay
* camera
* -> will follow any parent object3D.
*/
addLabel(text, parent, tag = "", overlay = false) {
let label = null;
if (!this[s_head]) {
this[s_head] = new Label(text, parent, tag, overlay, null, this[s_viewport], this[s_counter]);
this[s_tail] = this[s_head];
} else {
label = new Label(text, parent, tag, overlay, null, this[s_viewport], this[s_counter]);
this[s_tail].next = label
this[s_tail] = label;
}
this[s_counter]++;
return label;
}
/**
* Remove all labels with matching tag
*/
removeLabelsByTag(tag) {
let iterator = this[s_head];
let flag = false;
if (!iterator) {
return flag;
}
while (iterator.next) {
// Head has already been checked
if (iterator.tag === tag) {
let previous = iterator;
iterator = iterator.next;
this.removeLabel(previous);
flag = true;
} else {
iterator = iterator.next;
}
}
if (iterator.tag == tag) {
this.removeLabel(iterator);
}
return flag;
}
removeLabel(label) {
if (!label) {
return;
}
// Remove div
label.remove();
if (!this[s_head]) {
return;
}
if (label == this[s_head]) {
this[s_head] = null;
} else {
let iterator = this[s_head];
while (iterator.next) {
if (iterator.next == label) {
// Cut it out
iterator.next = label.next;
// Update tail pointer if necessary
if (label == this[s_tail]) {
this[s_tail] = iterator;
}
return;
}
iterator = iterator.next;
}
}
}
/**
* Recalculates the projection from the position vector
* that was given when added
*/
updatePositions() {
let iterator = this[s_head];
if (!iterator) {
return;
}
while (iterator.next) {
iterator.updatePosition();
iterator = iterator.next;
}
iterator.updatePosition();
}
} // Class LabelManager
let s_next = Symbol('next');
let s_htmlObject = Symbol('htmlobject');
let s_tag = Symbol('tag');
let s_parent = Symbol('s_parent');
let s_sceneCamera = Symbol('scenecamera');
let s_overlayCamera = Symbol('overlaycamera');
let s_text = Symbol('text');
class Label {
constructor(text, parent, tag = "", overlay = false, next, viewport, number) {
this[s_text] = text;
this[s_parent] = parent;
this[s_next] = next;
this[s_tag] = tag;
this[s_overlayCamera] = viewport.overlayCam;
this[s_sceneCamera] = viewport.camera;
this.canvas = viewport.canvas;
this.viewport = viewport;
// Create a new container
//$("#hph-canvas-wrapper").append("<div class=" + tag + tag + "></div>");
$("#hph-canvas-wrapper").append("<div class=" + tag + number + "></div>");
// Get a "pointer" to our new label
this[s_htmlObject] = $("." + tag + number);
// CSS settings
this[s_htmlObject].css("position", "absolute");
this[s_htmlObject].css("z-index", "100");
this[s_htmlObject].css("color", COLORS.Colors.BLACK);
this[s_htmlObject].css("font-size", label_font_size);
// FIXME:
//this[s_htmlObject].css("background-color", COLORS.Colors.GREY);
this[s_htmlObject].css("background-color", "#" + "ffffff");
// Make it non-selectable
this[s_htmlObject].css("-webkit-touch-callout", "none");
this[s_htmlObject].css("-webkit-user-select", "none");
if (overlay) {
this[s_htmlObject].addClass("overlay");
}
this[s_htmlObject].append(text);
this.updatePosition();
}
updatePosition() {
let pos = this[s_parent].isVector3 ? this[s_parent].clone() : this[s_parent].getWorldPosition();
if (this[s_htmlObject].hasClass("overlay")) {
pos.project(this[s_overlayCamera]);
} else {
pos.project(this[s_sceneCamera]);
}
pos.x = Math.round((pos.x + 1) * this.canvas.width / 2);
pos.y = Math.round((-pos.y + 1) * this.canvas.height / 2) + 10;
// Limit to canvas frame
pos.x = (pos.x > this.canvas.width - 20) ? this.canvas.width - 20 : pos.x;
pos.y = (pos.y > this.canvas.height - 20) ? this.canvas.height - 20 : pos.y;
pos.max(new THREE.Vector3(0, 0, 0));
this[s_htmlObject].css("left", pos.x + "px");
this[s_htmlObject].css("top", pos.y + "px");
}
remove() {
this[s_htmlObject].remove();
}
set next(next) {
this[s_next] = next;
}
get next() {
return this[s_next];
}
get tag() {
return this[s_tag];
}
get text() {
return this[s_text];
}
} // class LabelManager
export {
LabelManager
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Storyboard that holds a set of frames to be displayed by the viewport.
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
//import * as Translator from "./translator";
let s_frames = Symbol('frames');
let s_index = Symbol('index');
// This belongs in applet/main.js
//$(".hph-description").append(Translator.t('APPLET_DESCRIPTION'));
class Storyboard {
constructor() {
this[s_frames] = [];
this[s_index] = 0;
this.resetIndex = this.resetIndex.bind(this);
$(document).on("clear-all", this.resetIndex);
}
resetIndex(event) {
this[s_index] = 0;
}
append(frame) {
this[s_frames].push(frame);
}
frame(index) {
return this[s_frames][index];
}
setFrame(index, frame) {
this[s_frames][index] = frame;
}
size() {
return this[s_frames].length;
}
lastFrame() {
return this[s_frames][this.size() - 1];
}
firstFrame() {
return this[s_frames][0];
}
get index() {
return this[s_index];
}
set index(index) {
this[s_index] = index;
}
currentFrame() {
if (this[s_index] < this.size() - 1) {
$('#hph-forward').css("color", "#333");
} else {
$('#hph-forward').css("color", "grey");
}
if (this[s_index] > 0) {
$('#hph-backward').css("color", "#333");
} else {
$('#hph-backward').css("color", "grey");
}
return this.frame(this[s_index]);
}
nextFrame() {
if (this[s_index] < this.size() - 1) {
this[s_index]++;
}
return this.currentFrame()
}
previousFrame() {
if (this[s_index] > 0) {
this[s_index]--;
}
return this.currentFrame()
}
} //class Storyboard
export {
Storyboard
}
Storyboard.Frame = class {
constructor() {
this.lines = [];
this.labels = [];
this.points = new THREE.Object3D();
this.title = "";
this.description = "";
}
clone(orig) {
let myCopy = new Storyboard.Frame();
for (let segment of this.lines) {
myCopy.lines.push(segment.clone());
}
myCopy.labels = this.labels;
myCopy.points = this.points.clone();
myCopy.title = "insert new points";
return myCopy;
}
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Adapter class for hodograph applet.
// The second viewport should receive a different storyboard.
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
let s_algorithm = Symbol('algorithm');
class AlgorithmHodograph {
/** Default constructor. */
constructor(algorithm) {
this[s_algorithm] = algorithm;
}
storyboard() {
return this[s_algorithm].storyboardHodograph();
}
}
export {
AlgorithmHodograph
}
<file_sep>#!/bin/sh
##############################################################################
#
# @author <NAME> (<EMAIL>)
#
# Parse glsl shader files to json.
#
##############################################################################
cd "$(dirname "$0")"
mkdir -p ../../js/build
# join custom shaders in one file
python2 build.py --include shaders
# generate lang files
echo ""
echo " * Generating i18n locales"
for dir in ../../html/*/
do
app_dir=$(basename "$dir")
mkdir -p $dir/build/i18n
echo " * generating i18n locales for app $app_dir"
for file in $dir/i18n/*.yaml
do
filename=$(basename "$file")
filename="${filename%.*}"
out_file=${dir}build/i18n/$filename.json
python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' < $file > $out_file
done
done
echo ""
echo " * Starting Webpack"
webpack --config ../../webpack.config.js
<file_sep>##############################################################################
#
# @author <NAME> (<EMAIL>)
#
# Parse glsl shader files to js/build/shaders.json
#
##############################################################################
import argparse
import json
import os
import re
from io import open
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('--include', action='append', required=True)
parser.add_argument('--output', default='../../js/build/shaders.json')
args = parser.parse_args()
output = args.output
print(' * Building ' + output)
output_file = open(output, 'w', encoding='utf-8')
for include in args.include:
with open('includes/' + include + '.json','r', encoding='utf-8') as f:
files = json.load(f)
output_file.write(u'{')
first_element = True
for filename in files:
output_file.write(u'\n')
filename = '../../' + filename
with open(filename, 'r', encoding='utf-8') as f:
if filename.endswith(".glsl"):
if first_element:
first_element = False
else:
output_file.write(u',\n')
print(" * parsing {}".format(filename))
output_file.write(u'"{}": "'.format(os.path.splitext(
os.path.basename(filename))[0]))
text = f.read()
text = re.sub(r"\t*//.*\n", "", text) # strip comments
text = text.replace('\n','\\n') # line breaks to \n
output_file.write(text)
output_file.write(u'"')
output_file.write(u'\n}')
output_file.close()
if __name__ == "__main__":
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
main()
<file_sep>import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
import * as ALGORITHM from "./algorithm";
import * as LINEDRAG from "./linedragcontrols";
import * as CPLINTERVAL from "./controlpolygoninterval";
$(document).ready(function() {
// Canvas element
let canvas = $('.hph-canvas')[0];
let scene = new HAPPAH.Scene();
scene.add(HAPPAH.Defaults.basicLights());
let viewport = new HAPPAH.Viewport(canvas, scene);
let controlPolygon = new CPLINTERVAL.ControlPolygonInterval(scene, viewport, -80, 160);
// Initialize some points
controlPolygon.addControlPoints([
new THREE.Vector3(-80, 0, 50),
new THREE.Vector3(-40, 0, -30),
new THREE.Vector3(0, 0, -50),
new THREE.Vector3(40, 0, -50),
new THREE.Vector3(80, 0, 0)
]);
let algorithm = new ALGORITHM.Algorithm(controlPolygon.vectors);
let dragControls = new LINEDRAG.LineDragControls(controlPolygon.points.children, viewport);
// Canvas coordinates relative to middle of canvas element
let pos = new THREE.Vector3(0, -(1 / 1.2), 0);
let scrollbar = new HAPPAH.Scrollbar(pos, viewport);
algorithm.scrollbar = scrollbar;
algorithm.camera = viewport.camera;
scrollbar.listenTo(viewport.renderer.domElement);
scene.algorithm = algorithm;
viewport.overlay.add(scrollbar);
viewport.camera.position.set(0, 1000, 0);
viewport.camera.lookAt(scene.position);
viewport.camera.zoom = 3;
viewport.camera.updateProjectionMatrix();
// X-Axis
let geometry = new THREE.CylinderGeometry(1, 1, 190, 32);
let coneGeo = new THREE.CylinderGeometry(0, 3, 8, 5, 1);
coneGeo.rotateZ(-Math.PI / 2);
coneGeo.translate(95, 0, 0);
geometry.rotateZ(Math.PI / 2);
geometry.merge(coneGeo);
let material = new THREE.MeshBasicMaterial({
color: 0x4d4d4d
});
let axis = new THREE.Mesh(geometry, material);
axis.position.set(0, 0, 60);
scene.add(axis);
// Menu & toolbar
let toolbar = HAPPAH.Defaults.toolbarMenu(".tool-bar-top");
let menu = HAPPAH.Defaults.playerMenu("#hph-controls");
let guide = new HAPPAH.Guide();
console.log("happah initialized.");
});
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Creates a storyboard of all Bernstein polynomials from degree 0,0 to 4,4
// outside of 0<x,y<1 they are greyed out.
// @author: <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
const outside_color = 0xE2E2E2;
let s_factorial = Symbol('factorial');
let s_origin = Symbol('origin');
class Algorithm {
constructor(origin) {
//this[s_controlPoints] = controlPoints;
this[s_origin] = origin;
this.storyboard = this.storyboard.bind(this);
this.binomial = this.binomial.bind(this);
}
/**
* Calculates binomial coefficient
* @url: http://www.w3resource.com/javascript-exercises/javascript-math-exercise-20.php
*/
binomial(n, k) {
if ((typeof n !== 'number') || (typeof k !== 'number')) {
return false;
}
let coeff = 1;
for (let x = n - k + 1; x <= n; x++) {
coeff *= x;
}
for (let x = 1; x <= k; x++) {
coeff /= x;
}
return coeff;
}
/**
* Calculate from 0 to 1
*/
evaluate(i, n, min, max) {
let points = [];
let binomial = this.binomial(n, i);
for (let t = min; t <= max; t += 0.02) {
let y = binomial * Math.pow(t, i) * Math.pow(1 - t, n - i);
let point = new THREE.Vector3(t * 100, 0, -y * 100);
points.push(point.add(this[s_origin]));
}
return points;
}
/**
* Returns a storyboard with frames that contain the different steps
* of the algorithm
*/
storyboard() {
// Create the first frame by hand
let storyboard = new HAPPAH.Storyboard(this);
for (let i = 1; i < 5; i++) {
for (let k = 0; k <= i; k++) {
let frame = new HAPPAH.Storyboard.Frame();
// Get a new color from gradient
let color = 0xFF0000 + ((i + k) * 100000);
// Create outer-left line
frame.lines.push(HAPPAH.Util.insertSegmentStrip(this.evaluate(k, i, -10, 0), outside_color));
// Create inner lines in full-color
frame.lines.push(HAPPAH.Util.insertSegmentStrip(this.evaluate(k, i, 0, 1.02), color));
// Create outer-right line
frame.lines.push(HAPPAH.Util.insertSegmentStrip(this.evaluate(k, i, 1, 10), outside_color));
frame.title = "B" + k + "," + i + "(t)";
// Concat with previous iterations -> of same degree
if (k != 0) {
frame.lines = frame.lines.concat(storyboard.frame(storyboard.size() - 1).lines);
}
storyboard.append(frame);
}
}
return storyboard;
}
}
export {
Algorithm
}
<file_sep> /////////////////////////////////////////////////////////////////////////////
//
// @author <NAME> (<EMAIL>)
//
/////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as MENU from "./menu";
class Defaults {
static orthographicCamera(canvas) {
return new THREE.OrthographicCamera(canvas.width() / -2, canvas.width() / 2, canvas.height() / 2, canvas.height() / -2, 1, 10000);
}
static perspectiveCamera(canvas) {
return new THREE.PerspectiveCamera(45,
canvas.width() / canvas.height(), 1, 1000);
}
static basicLights() {
let lights = new THREE.Object3D();
let hemisphereLight = new THREE.HemisphereLight(0xffffff, 0x00ee00, .55);
lights.add(hemisphereLight);
let dirLight = new THREE.DirectionalLight(0xffffff);
dirLight.position.set(0, 200, 100).normalize();
lights.add(dirLight);
return lights;
}
static toolbarMenu(container) {
let menu = new MENU.Menu(container);
menu.addButton("Toggle grid", "grid-toggle", "fa-th", "Grid");
menu.addButton("Toggle controlpolygon", "poly-toggle", "fa-low-vision", "Control polygon");
menu.addButton("Clear scene", "clear-all", "fa-trash", "Clear");
menu.addButton("Start Tour", "show-help", "fa-info", "Guide");
return menu;
}
static playerMenu(container) {
let menu = new MENU.Menu(container);
menu.addButton("Previous Frame", "hph-backward", "fa-chevron-left", "");
menu.addButton("Play", "hph-play", "fa-play", "");
menu.addButton("Pause", "hph-pause", "fa-pause", "");
menu.addButton("Next Frame", "hph-forward", "fa-chevron-right", "");
return menu;
}
} // Class Defaults
export {
Defaults
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Extended deCasteljau algorithm
//
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
import * as IMPOSTOR from "../lib/spherical-impostor";
import * as UTIL from "../lib/util";
let s_controlPoints = Symbol('controlPoints');
let s_ratio = Symbol('ratio');
let s_scrollbar = Symbol('scrollbar');
let s_camera = Symbol('camera');
class Algorithm extends HAPPAH.DeCasteljauAlgorithm {
/** Default constructor. */
constructor(controlPoints, scrollbar, camera) {
super(controlPoints, scrollbar);
this.storyboard = this.storyboard.bind(this);
this[s_controlPoints] = controlPoints;
this[s_ratio] = (scrollbar == null) ? 0.5 : scrollbar.value;
this[s_scrollbar] = scrollbar;
this[s_camera] = camera;
}
set scrollbar(scrollbar) {
this[s_scrollbar] = scrollbar;
// super.scrollbar = scrollbar;
}
/**
* Returns a storyboard with frames that contain the different steps
* of the algorithm
*/
storyboard() {
let ratio;
if (this[s_scrollbar] == null) {
console.log("scrollbar == null");
ratio = 0.5;
} else {
ratio = this[s_scrollbar].value;
}
// Create the first frame by hand
let storyboard = new HAPPAH.Storyboard(this);
if (this[s_controlPoints].length == 0) {
let frame0 = new HAPPAH.Storyboard.Frame();
// Add a dummy mesh
frame0.lines[0] = UTIL.Util.insertSegmentStrip(this[s_controlPoints], 0xff0000);
storyboard.append(frame0);
return storyboard;
}
// each iteration step gets stored in a matrix row
let pointMatrix = new Array();
// First set of points is the control polygon
pointMatrix.push(this[s_controlPoints]);
// TODO: add a box on the axis for each controlpoint
let box_geo = new THREE.BoxGeometry(1.5, 4.1, 5);
let box_mat = new THREE.MeshBasicMaterial({
color: 0x4d4d4d
});
let box_temp = new THREE.Mesh(box_geo, box_mat);
box_temp.position.setZ(60);
// fill matrix with points from each iteration
this.evaluate(ratio, function add(points) {
pointMatrix.push(points);
});
// Helper points settings
let radius = 3;
let color = 0x3d3d3d;
let template = new IMPOSTOR.SphericalImpostor(radius);
for (let i = 1; i < pointMatrix.length; i++) {
let frame = new HAPPAH.Storyboard.Frame();
frame.points = new THREE.Object3D();
for (let point in this[s_controlPoints]) {
let box = box_temp.clone();
box.position.setX(this[s_controlPoints][point].x);
frame.lines.push(box);
}
for (let k in pointMatrix[i]) {
let imp = template.clone();
imp.position.copy(pointMatrix[i][k]);
imp.material.uniforms.diffuse.value.set(color);
frame.points.add(imp);
}
let pointStack = new Array();
// The previous iteration has one point more.
for (let k in pointMatrix[i]) {
// Push first one from last iteration
pointStack.push(pointMatrix[i - 1][k].clone());
// Now add one point from current iteration
pointStack.push(pointMatrix[i][k].clone());
// TODO: this needs to be parameterized
// Get relative point on the axis
let projectPoint = pointMatrix[i][k].clone();
projectPoint.z = 60;
// Add dashed line between point and projection
let line = UTIL.Util.insertDashedLine([pointMatrix[i][k].clone(), projectPoint], 0x000000);
frame.lines.push(line);
}
// Add last point from previous iteration
pointStack.push(pointMatrix[i - 1][pointMatrix[i - 1].length - 1]);
// Iterate over stacksize and make a segment from 2 points
for (let k = 2; k <= pointStack.length; k++) {
let segment = new Array();
segment.push(pointStack[k - 1]);
segment.push(pointStack[k - 2]);
// Paint the strips in the interval's color
let strip = (k % 2 == 0) ?
UTIL.Util.insertSegmentStrip(segment, 0x3D3D3D) : UTIL.Util.insertSegmentStrip(segment, 0xFF0000);
frame.lines.push(strip);
}
//frame.points = frame.points.concat(storyboard.frame(storyboard.size() - 1).points);
if (i > 1) {
frame.lines = frame.lines.concat(storyboard.frame(storyboard.size() - 1).lines);
}
storyboard.append(frame);
}
return storyboard;
}
}
export {
Algorithm
};
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// @author: <NAME> (<EMAIL>)
//
// Algorithm for app 'linear precision'
//
// Let n points be equally distributed on a straight line. After applying the
// de'Casteljau algorithm on this control polygon, the last added point will
// divide the start point s and the end point e in the ratio t:(1-t).
// Let t be 2/3
// p=te+(1-t)s
// *-----------------------*-----------*
// (s) : (e)
// *-------.===*
// : :
// *-------.===*-------.===*
// : : :
// *-------.===*-------.===*-------.===*
// (s) (e)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
let s_controlPoints = Symbol('controlPoints');
let s_ratio = Symbol('ratio');
let s_scrollbar = Symbol('scrollbar');
class Algorithm extends HAPPAH.DeCasteljauAlgorithm {
/** Default constructor. */
constructor(controlPoints, scrollbar) {
super(controlPoints, scrollbar);
this.storyboard = this.storyboard.bind(this);
this[s_controlPoints] = controlPoints;
this[s_ratio] = (scrollbar == null) ? 0.5 : scrollbar.value;
this[s_scrollbar] = scrollbar;
}
// we need this, because scrolbar gets set after the constructor call
set scrollbar(scrollbar) {
this[s_scrollbar] = scrollbar;
super.scrollbar = scrollbar;
}
/**
* Returns a storyboard with frames that contain the different steps
* of the algorithm
*/
storyboard() {
let ratio;
if (this[s_scrollbar] == null) {
ratio = 0.5;
} else {
ratio = this[s_scrollbar].value;
}
// evaluate all de Casteljau steps and store their result in a
// point matrix
let pointMatrix = new Array();
pointMatrix.push(this[s_controlPoints]);
this.evaluate(ratio, function add(points) {
pointMatrix.push(points);
});
// impostor templates only need to created once
let radius = 3;
let imp_template = new HAPPAH.SphericalImpostor(radius);
imp_template.material.uniforms.diffuse.value.set(HAPPAH.Colors.COLOR2);
let imp_template_emph = new HAPPAH.SphericalImpostor(radius);
imp_template_emph.material.uniforms.diffuse.value.set(
HAPPAH.Colors.COLOR4);
let storyboard = new HAPPAH.Storyboard(this);
let frame0 = new HAPPAH.Storyboard.Frame();
frame0.lines[0] = HAPPAH.Util.insertSegmentStrip(this[s_controlPoints], 0xff0000);
frame0.title = "Controlpolygon";
frame0.points = new THREE.Object3D();
storyboard.append(frame0);
if (this[s_controlPoints].length == 0) {
// Add a dummy mesh
frame0.lines[0] = new THREE.Object3D();
return storyboard;
}
let substrips = [];
substrips.push([this[s_controlPoints]]);
for (let i = 0; i < 5; i++) {
let frame = new HAPPAH.Storyboard.Frame();
substrips.push([]);
for (let pointArray of substrips[i]) {
let temp = new HAPPAH.DeCasteljauAlgorithm(pointArray);
let right = temp.subdivide(1, ratio);
let left = right.splice(0, Math.floor(right.length / 2));
left.push(right[0].clone());
substrips[i + 1].push(left);
substrips[i + 1].push(right);
frame.lines.push(HAPPAH.Util.insertSegmentStrip(
left, HAPPAH.Colors.COLOR1));
frame.lines.push(HAPPAH.Util.insertSegmentStrip(
right, HAPPAH.Colors.GREY));
}
storyboard.append(frame);
}
return storyboard;
}
}
export {
Algorithm
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// A controlpolygon subclass, that will place new points withing a fixed
// interval. Former added points will be pushed together to remain equidistant.
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as IMPOSTOR from "../lib/spherical-impostor";
import * as HAPPAH from "../lib/controlpolygon";
import * as UTIL from "../lib/util";
let s_origin = Symbol('origin');
let s_intervalWidth = Symbol('intervalwidth');
class ControlPolygonInterval extends HAPPAH.ControlPolygon {
/** Limit of zero means infinite */
constructor(scene, viewport, origin, width, limit = 0) {
super(scene, viewport, limit);
// Remove superclass event listener first
this.viewport.renderer.domElement.removeEventListener('click', this.onMouseClick);
this.onMouseClick = this.onMouseClick.bind(this);
this[s_origin] = origin;
this[s_intervalWidth] = width;
// Remove eventListeners from superclass
this.viewport.renderer.domElement.addEventListener('click', this.onMouseClick, false);
}
//@Override
onMouseClick(event) {
if (!this.addMode) {
return;
}
console.log("this is subclass call");
// Get current mouse position on screen
let vector = UTIL.Util.getPositionOnCanvas(event);
// Create new raycaster
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(vector, this.camera);
// Intersect with impostors
let intersects = raycaster.intersectObjects(this.impostors.children, true);
// Exit add mode.
if (intersects[0] || (this.impostors.children.length >= this.limit && this.limit != 0)) {
this.addMode = false;
this.viewport.canvas.style.cursor = "default";
return;
}
// Intersect with viewplane to create a new position
this.viewPlane.set(this.camera.getWorldDirection(), 0);
let position = raycaster.ray.intersectPlane(this.viewPlane);
// Add a new point to the specified position
super.addControlPoints([position]);
// Split interval
let distance = this.vectors.length == 0 ? this[s_intervalWidth] :
this[s_intervalWidth] / this.vectors.length;
for (let i = 0; i < this.impostors.children.length; i++) {
let valueX = this[s_origin] + distance * i;
this.impostors.children[i].position.setX(valueX);
this.vectors[i].setX(valueX);
}
}
} //class ControlPolygonInterval
export {
ControlPolygonInterval
};
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Multi-handle-Scrollbar
// scrollbar with multiple handles in different colors
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as UTIL from "./util";
import * as SCROLLBAR from "./scrollbar";
import * as LABEL from "./labelmanager";
let s_handles = Symbol('handles');
class MultiHandleScrollbar extends SCROLLBAR.Scrollbar {
constructor(position, viewport, initialValue) {
super(position, viewport, initialValue);
this[s_handles] = [this.handle];
}
addHandle(value = 0.5, color, text) {
let handle = this.createHandle(value, color);
this[s_handles].push(handle);
// Add to scene
this.add(handle);
if (text) {
handle.label = this.labelManager.addLabel(text, handle, "handle" + handle.id, true);
}
return handle;
}
popHandle() {
let handle = this[s_handles].pop();
this.labelManager.removeLabel(handle.label);
this.remove(handle);
return handle;
}
removeHandles() {
// Remove them from the scene first
for (let i = 0; i < this[s_handles].length - 1; i++) {
this.remove(this[s_handles][i]);
}
this[s_handles] = [];
}
// Deprecated
valueOf(index) {
if (index >= this[s_handles].length)
return -1;
return this[s_handles][index].value;
}
// Deprecated
show(handle) {
this.add(handle);
}
// Deprecated
hide(handle) {
this.remove(handle);
}
// Deprecated
get handles() {
return this[s_handles];
}
// @Override
handle(i) {
return this[s_handles][i];
}
updateLines(handle) {
// Update color of line segments
this.remove(this.lineRight);
this.remove(this.lineLeft);
let geo = new THREE.Geometry();
geo.vertices.push(new THREE.Vector3(-75, 2, 0));
geo.vertices.push(handle.position);
let mat = new THREE.LineBasicMaterial({
color: handle.material.color,
linewidth: 5
});
this.lineLeft = new THREE.Line(geo, mat);
this.add(this.lineLeft);
geo = new THREE.Geometry();
geo.vertices.push(handle.position);
geo.vertices.push(new THREE.Vector3(75, 2, 0));
// TODO: color of previous handle/segment
mat = new THREE.LineBasicMaterial({
color: handle.material.color,
linewidth: 5
});
this.lineRight = new THREE.Line(geo, mat);
this.add(this.lineRight);
}
/** Called when a mouse button is pressed */
mouseDown(event) {
event.preventDefault();
if (this.enabled == false) {
return;
}
// TODO: don't calculate the position every time.
// -> only on window resize...
let elementPosition = UTIL.Util.getElementPosition(event.currentTarget);
// Get mouse position
let mouseX = ((event.clientX - elementPosition.x) / event.currentTarget.width) * 2 - 1;
let mouseY = -((event.clientY - elementPosition.y) / event.currentTarget.height) * 2 + 1;
let mouseVector = new THREE.Vector3(mouseX, mouseY, -1);
// Set up ray from mouse position
this.raycaster.setFromCamera(mouseVector, this.camera);
// Find all intersected objects
let intersects = this.raycaster.intersectObjects(this[s_handles]);
if (intersects.length > 0) {
// Update line colors if different handle
if (this.selectedObject != intersects[0].object) {
this.updateLines(intersects[0].object);
}
// Enable drag-mode
this.selectedObject = intersects[0].object;
$.event.trigger({
type: "draggingStarted",
message: "scrollbar dragging has started!"
});
} else {
this.selectedObject = false;
}
}
/** Called whenever a mouse button is moved */
mouseMove(event) {
event.preventDefault();
if (this.enabled == false) {
return;
}
let elementPosition = UTIL.Util.getElementPosition(event.currentTarget);
// Get mouse position
let mouseX = ((event.clientX - elementPosition.x) / event.currentTarget.width) * 2 - 1;
let mouseY = -((event.clientY - elementPosition.y) / event.currentTarget.height) * 2 + 1;
let mouseVector = new THREE.Vector3(mouseX, mouseY, -1);
// Set up ray from mouse position
this.raycaster.setFromCamera(mouseVector, this.camera);
if (this.selectedObject) {
// Reposition the object based on the intersection point with the plane
let newPos = this.selectionLine.closestPointToPoint(this.raycaster.ray.intersectPlane(this.selectionPlane));
newPos.sub(this.position);
//TODO: selectedobject.object???
this.selectedObject.position.copy(newPos);
// In case we are beyond the left border
if (this.handle.position.x < -75) {
// hide the black line
this.lineLeft.visible = false;
} else {
this.lineLeft.visible = true;
}
// Same goes for the right line
if (this.handle.position.x > 75) {
this.lineRight.visible = false;
} else {
this.lineRight.visible = true;
}
// Update our line sections
this.lineRight.geometry.verticesNeedUpdate = true;
this.lineLeft.geometry.verticesNeedUpdate = true;
// New value means new storyboard
$.event.trigger({
type: "dragging",
message: "scrollbar dragging started!"
});
}
}
} //class MultiHandleScrollbar
export {
MultiHandleScrollbar
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Viewport
// Displays a scene inside a given canvas. Also contains an overlay scene
// for GUI elements.
// @author <NAME> (<EMAIL>)
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as CONTROLS from "three-trackballcontrols";
import * as DEFAULTS from "./defaults";
import * as LABEL from "./labelmanager";
const background_color = 0xFFFFFF;
let s_camera = Symbol('camera');
let s_trackballControls = Symbol('trackballControls');
let s_drawPoly = Symbol('drawpoly');
let s_overlay = Symbol('overlay');
let s_cameraOverlay = Symbol('overlayCam');
let s_renderer = Symbol('renderer');
let s_scene = Symbol('scene');
let s_scrollbar = Symbol('scrollbar');
let s_zoom = Symbol('zoom');
let s_labelmanager = Symbol('labelmanager');
let s_canvas = Symbol('canvas');
class Viewport {
constructor(canvas, scene) {
let context = canvas.getContext('webgl');
this[s_canvas] = canvas;
context.getExtension('EXT_frag_depth');
this.mouseWheel = this.mouseWheel.bind(this);
this.update = this.update.bind(this);
this[s_camera] = DEFAULTS.Defaults.orthographicCamera($(canvas));
this[s_cameraOverlay] = this[s_camera].clone();
this[s_cameraOverlay].position.set(0, 1, 0); // 0 for orthographic camera
this[s_cameraOverlay].lookAt(scene.position);
this[s_cameraOverlay].zoom = 2.2;
this[s_cameraOverlay].updateProjectionMatrix();
this[s_drawPoly] = true;
this[s_overlay] = new THREE.Scene();
this[s_overlay].add(DEFAULTS.Defaults.basicLights());
this[s_renderer] = new THREE.WebGLRenderer({
antialias: true,
canvas: canvas,
context: context
});
this[s_renderer].autoClear = false; // For dual-scene-rendering
this[s_renderer].setClearColor(background_color);
this[s_renderer].setSize($(canvas).width(), $(canvas).height());
this[s_labelmanager] = new LABEL.LabelManager(this);
this[s_scene] = scene;
// TODO: Use own trackballControls that can fire update events
this[s_trackballControls] = new TrackballControls(this[s_camera], this[s_renderer].domElement);
this[s_trackballControls].noZoom = true;
//this[s_trackballControls] = new CONTROLS.TrackballControls(this[s_camera], this[s_scene]);
//this[s_trackballControls] = new TRACK.TrackballControls(this[s_camera], scene);
//this[s_trackballControls].listenTo(this[s_renderer].domElement);
this.enableControls = this.enableControls.bind(this);
this.disableControls = this.disableControls.bind(this);
$(document).on("draggingStarted", this.disableControls);
$(document).on("draggingStopped", this.enableControls);
// add event listeners for user interactions
this[s_renderer].domElement.addEventListener('DOMMouseScroll', this.mouseWheel, false);
this[s_renderer].domElement.addEventListener('wheel', this.mouseWheel, false);
// This is only for trackballcontrols
this.update();
}
disableControls(event) {
this[s_trackballControls].enabled = false;
}
enableControls(event) {
this[s_trackballControls].enabled = true;
}
get canvas() {
return this[s_canvas];
}
get overlay() {
return this[s_overlay];
}
get renderer() {
return this[s_renderer];
}
get controls() {
return this[s_trackballControls];
}
get overlayCam() {
return this[s_cameraOverlay];
}
addLight(lights) {
this[s_scene].add(lights);
this[s_overlay].add(lights);
}
get labelManager() {
return this[s_labelmanager];
}
get camera() {
return this[s_camera];
}
// the mouse wheel controls the camera zoom
// TODO: This belongs trackballcontrols class.
mouseWheel(event) {
event.preventDefault();
let delta;
if (event.wheelDelta) {
delta = event.wheelDeltaY / 35;
} else if (event.detail) {
// This works with Firefox
delta = -event.detail / 2;
} else {
delta = -event.deltaY;
}
// Zoom speed
delta = delta * 0.06;
if (this[s_camera].zoom + delta < 0) {
delta = 0;
}
this[s_camera].zoom += delta;
this[s_camera].updateProjectionMatrix();
// Label positions need to be adjusted
$.event.trigger({
type: "change",
message: "actually zooming"
});
}
/**
* Update function - represents main loop.
* Scene is updated and rendered here.
*/
update() {
requestAnimationFrame(this.update.bind(this));
// Let the scene update if necessary
this[s_scene].update();
// Render scene + scene overlay
this[s_renderer].render(this[s_scene], this[s_camera]);
this[s_renderer].render(this[s_overlay], this[s_cameraOverlay]);
// TODO: trackballControls should fire events so we can update
// on event, instead of every frame.
this[s_trackballControls].update();
}
} //class Viewport
export {
Viewport
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// A polygonal line between a set of controlpoints.
// Can be extended at both ends by double-clicking on an endpoint.
// The maximum amount of controlpoints is defined by the limit variable.
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as IMPOSTOR from "./spherical-impostor";
import * as UTIL from "./util";
let s_isHead = Symbol('ishead');
let s_scene = Symbol('scene');
class ControlPolygon {
/** Limit of zero means infinite */
constructor(scene, viewport, limit = 0) {
this.onMouseDoubleclick = this.onMouseDoubleclick.bind(this);
this.onMouseClick = this.onMouseClick.bind(this);
this.enterAddMode = this.enterAddMode.bind(this);
this.impostors = new THREE.Group();
this[s_scene] = scene;
this[s_scene].add(this.impostors);
this.vectors = [];
this.limit = limit;
this.addMode = false;
this.camera = viewport.camera;
this.viewport = viewport;
this.viewPlane = new THREE.Plane();
this.removeControlPoints = this.removeControlPoints.bind(this);
$(document).on("clear-all", this.removeControlPoints);
//$(document).on("dragging", this.updateVectors);
this.viewport.renderer.domElement.addEventListener('dblclick', this.onMouseDoubleclick, false);
this.viewport.renderer.domElement.addEventListener('click', this.onMouseClick, false);
this.viewport.renderer.domElement.addEventListener('clrscene', this.enterAddMode, false);
}
/** Force add mode */
enterAddMode() {
if (this.impostors.children.length < this.limit || this.limit == 0) {
// Change cursor to crosshair
//$('.hph-canvas')[0].style.cursor = "crosshair";
this.viewport.canvas.style.cursor = "crosshair";
this.addMode = true;
$.event.trigger({
type: "add-mode",
message: "Add-mode enabled!"
});
console.log("event triggered");
} else {
console.warn("Control-point limit reached!");
}
}
/** Adds a control point to the scene */
addControlPoints(points, head = false, color = new THREE.Color(0x888888)) {
for (let i in points) {
let sphere = new IMPOSTOR.SphericalImpostor(3);
sphere.material.uniforms.diffuse.value.set(color);
sphere.position.copy(points[i]);
sphere.updateMatrixWorld();
// Add the point to head/tail of the array
if (head) {
this.impostors.children.unshift(sphere);
this.vectors.unshift(sphere.position);
} else {
this.impostors.children.push(sphere);
this.vectors.push(sphere.position);
}
}
$.event.trigger({
type: "rebuildStoryboard",
message: "points added!"
});
}
/** Remove control points */
removeControlPoints() {
this.impostors.children.length = 0;
this.vectors.length = 0;
$.event.trigger({
type: "rebuildStoryboard",
message: "points removed!"
});
this.enterAddMode();
}
dispose() {
this.viewportrenderer.domElement.removeEventListener('dblclick', this.onMouseDoubleclick, false);
this.viewportrenderer.domElement.removeEventListener('click', this.onMouseClick, false);
this.viewportrenderer.domElement.removeEventListener('clrscene', this.enterAddMode, false);
}
//get vectors() {
//return this.vectors;
//}
get points() {
return this.impostors;
}
onMouseDoubleclick(event) {
// Get current mouse position on screen
let vector = UTIL.Util.getPositionOnCanvas(event);
// Create new raycaster from mouse position
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(vector, this.camera);
// Check if we hit a sphericalImpostor. If so, save the position
// NOTE: only check for first and last impostor (head/tail)
let impostors = this.impostors.children;
let headTail = [impostors[0], impostors[impostors.length - 1]];
let intersects = raycaster.intersectObjects(headTail, true);
if (intersects[0] == headTail[0]) {
// Dblclick on head
this[s_isHead] = true;
} else {
this[s_isHead] = false;
}
// Toggle add mode
if (intersects[0]) {
this.enterAddMode();
}
}
onMouseClick(event) {
if (!this.addMode) {
return;
}
// Get current mouse position on screen
let vector = UTIL.Util.getPositionOnCanvas(event);
// Create new raycaster
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(vector, this.camera);
// Intersect with impostors
let impostors = this.impostors;
let intersects = raycaster.intersectObjects(impostors.children, true);
// Exit add mode.
if (intersects[0] || (this.impostors.children.length >= this.limit && this.limit != 0)) {
this.addMode = false;
this.viewport.canvas.style.cursor = "default";
return;
}
// Intersect with viewplane to create a new position
this.viewPlane.set(this.camera.getWorldDirection(), 0);
let position = raycaster.ray.intersectPlane(this.viewPlane);
// Add a new point to the specified position
this.addControlPoints([position], this[s_isHead]);
}
} //class ControlPolygon
export {
ControlPolygon
};
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// @author <NAME> (<EMAIL>)
//
// De Casteljau's algorithm with polar form labels, showing the ratios for the
// current point.
//
//////////////////////////////////////////////////////////////////////////////
import * as $ from "jquery";
import * as THREE from "three";
import * as HAPPAH from "../lib/happah";
let s_controlPoints = Symbol('controlpoints');
let s_scrollbar = Symbol('scrollbar');
let s_labelmanager = Symbol('labelmanager');
class Algorithm extends HAPPAH.DeCasteljauAlgorithm {
constructor(controlPoints, scrollbar) {
super(controlPoints, scrollbar);
this.storyboard = this.storyboard.bind(this);
this[s_scrollbar] = scrollbar;
this[s_controlPoints] = controlPoints;
}
set labelmanager(labelmanager) {
this[s_labelmanager] = labelmanager;
}
set scrollbar(scrollbar) {
this[s_scrollbar] = scrollbar;
let handle = this[s_scrollbar].getHandle();
handle.geometry.scale(0.75, 1, 1);
this[s_labelmanager].addLabel("c", handle, "interval", true);
}
storyboard() {
var ratio;
if (this[s_scrollbar] == null) {
ratio = 0.5;
} else {
ratio = this[s_scrollbar].value;
}
// Create the first frame by hand
var storyboard = new HAPPAH.Storyboard(this);
var frame0 = new HAPPAH.Storyboard.Frame();
frame0.lines[0] = HAPPAH.Util.insertSegmentStrip(this[s_controlPoints], HAPPAH.Colors.RED);
frame0.title = "Controlpolygon";
frame0.points = new THREE.Object3D();
storyboard.append(frame0);
if (this[s_controlPoints].length == 0) {
// Add a dummy mesh
frame0.lines[0] = new THREE.Object3D();
return storyboard;
}
// matrix of points for every iteration
var pointMatrix = new Array();
//pointMatrix = this.evaluate(function() {});
pointMatrix.push(this[s_controlPoints]);
this.evaluate(ratio, function add(points) {
pointMatrix.push(points);
});
// Helper points radius
var radius = 3;
var color = HAPPAH.Colors.GREY;
frame0.points = new THREE.Object3D();
this[s_labelmanager].removeLabelsByTag("pts");
for (var k = 0; k < this[s_controlPoints].length; k++) {
var str = "";
for (var m = 0; m < this[s_controlPoints].length - k - 1; m++) {
str += "a";
}
// Push previous handle's labels
for (var l = 0; m < this[s_controlPoints].length - 1 && k != 0; m++) {
str += "b";
l++;
}
this[s_labelmanager].addLabel(str, this[s_controlPoints][k], "pts", false);
}
// Impostor template
var template = new HAPPAH.SphericalImpostor(radius);
for (var i = 1; i < pointMatrix.length; i++) {
var frame = new HAPPAH.Storyboard.Frame();
frame.title = "Step " + i;
frame.points = new THREE.Object3D();
for (var k = 0; k < pointMatrix[i].length; k++) {
var str = "";
var j = 0;
// k------->
// i .
// | . |
// | (pointMatrix) |
// | . |
// v .
// Length of finished label
var length = pointMatrix.length - 1;
// Length of current label
var m = 0;
// Push zeros for following iterations
// [000....]
for (; m < pointMatrix[i].length - k - 1; m++) {
str += "a";
}
// Push current intervall handle's label
// [000Z...]
if (i == 0) {
str += "b";
} else {
//str += this[s_scrollbar].handles[i - 1].label.text;
str += "c";
}
m++;
// Push previous handle's labels
// [000ZYX.]
for (var l = 0; m < length; m++) {
if (i - 2 - l >= 0) {
//str += this[s_scrollbar].handles[i - 2 - l].label.text;
str += "c";
} else {
// Fill with ones if no handles left
// [000ZYX1]
str += "b";
}
l++;
}
// TODO: add to own labelmanager?
//frame.labels.push(str);
this[s_labelmanager].addLabel(str, pointMatrix[i][k], "pts", false);
}
var pointStack = new Array();
// The previous iteration has one point more.
for (var k in pointMatrix[i]) {
var imp = template.clone();
imp.position.copy(pointMatrix[i][k]);
imp.material.uniforms.diffuse.value.set(color);
frame.points.add(imp);
// Push first one from last iteration
pointStack.push(pointMatrix[i - 1][k]);
// Now add one point from current iteration
pointStack.push(pointMatrix[i][k]);
}
// Add last point from previous iteration
pointStack.push(pointMatrix[i - 1][pointMatrix[i - 1].length - 1]);
// Iterate over stacksize and make a segment from 2 points
for (var k = 2; k <= pointStack.length; k++) {
var segment = new Array();
segment.push(pointStack[k - 1]);
segment.push(pointStack[k - 2]);
// Paint the strips in the interval's color
var strip = (k % 2 == 0) ?
HAPPAH.Util.insertSegmentStrip(segment, HAPPAH.Colors.BLACK) : HAPPAH.Util.insertSegmentStrip(segment, HAPPAH.Colors.RED);
frame.lines.push(strip);
}
// Merge with the previous frame's lines
if (i != 1) {
frame.lines = frame.lines.concat(storyboard.frame(storyboard.size() - 1).lines);
frame.labels = frame.labels.concat(storyboard.frame(storyboard.size() - 1).labels);
frame.points.children = frame.points.children.concat(storyboard.frame(storyboard.size() - 1).points.children);
// Remove the last mesh from the previous iteration
// to prevent overlapping lines
frame.lines.pop();
}
// Also add the newly generated polygon
frame.lines.push(HAPPAH.Util.insertSegmentStrip(pointMatrix[i], HAPPAH.Colors.RED));
storyboard.append(frame);
}
return storyboard;
}
}
export {
Algorithm
}
<file_sep>//////////////////////////////////////////////////////////////////////////////
//
// Adapter class for hodograph applet.
// The second viewport should receive a different storyboard.
// @author <NAME> (<EMAIL>)
//
//////////////////////////////////////////////////////////////////////////////
let s_algorithm = Symbol('algorithm');
class AlgorithmPoly {
/** Default constructor. */
constructor(algorithm) {
this[s_algorithm] = algorithm;
}
storyboard() {
// Call once to rebuild the storyboards
this[s_algorithm].storyboard();
return this[s_algorithm].storyboardPoly();
}
}
export {
AlgorithmPoly
}
| d6c77f17a71384f3009ba2528f94f7af9de1c57b | [
"Markdown",
"Python",
"JavaScript",
"Shell"
]
| 27 | Markdown | happah-graphics/happah-applets | da6c98635e997c03ea1b6a2413a93ca726c29bd7 | 04b68ebca8452a5dfa66f9811bbe021509aca688 |
refs/heads/master | <file_sep># creating list of files with PR data for 2003, 2008, 2010, 2013, 2015, 2017/2018
# computes use of ITN by anyone in the HH
var_label(NGAfiles[[6]]$hv103)
PR.list <- list(NGAfiles[[6]], NGAfiles[[9]], NGAfiles[[12]], NGAfiles[[15]], NGAfiles[[18]], NGAfiles[[21]])
PR.list <- lapply(PR.list, subset, hv103 == "1")
PR.list <- map(PR.list, recode_itn)
PR.list <- map(PR.list, survey.month.fun)
# key list for ITN (2003, 2008, 2010, 2013, 2015, 2017/2018)
keys.hh.itn <- list(key_list[[2]], key_list[[3]], key_list[[4]], key_list[[5]],key_list[[6]], key_list[[7]])
#changing to a list of keys
# key datasets and dhs/mis datasets are joined
hh.itn.list <- map2(PR.list, keys.hh.itn, left_join) #PR datasets
rep_DS.ls <- list(rep_DS)
hh.itn.list <- map2(hh.itn.list, rep_DS.ls, left_join) #PR datasets
hh.itn.list <- lapply(hh.itn.list, subset, hv105 <= 5)
#
# var_label(hh.itn.list[[6]]$hml12)
#####################################################################################################
#ITN coverage
####################################################################################################
# 2018
hh.itn.list[[6]] <-dataclean.HH(hh.itn.list[[6]], hml12, hv005,'hh_itn', 'hh_itn')
hh.itn.svyd18 <- svydesign.fun(hh.itn.list[[6]])
#LGA_level estimates
DS_hh_itn_18 <- result.fun('hh_itn', 'LGA','num_p', design=hh.itn.svyd18)
head(DS_hh_itn_18)
# DS_hh_itn_18_v2 <- DS_hh_itn_18 %>%
# dplyr::select(State, hv025, hh_itn) %>%
# pivot_wider(names_from = hv025, values_from = hh_itn)
# head(DS_hh_itn_18_v2)
#
# write.csv(DS_hh_itn_18_v2, "results/urbanvsrural/2018_ITNstate.csv")
#next join each LGA to their repDS
DS_hh_itn_18 <- rep_DS %>% left_join(DS_hh_itn_18)
head(DS_hh_itn_18)
summary(DS_hh_itn_18$hh_itn)
#repDS_level estimates and change variable names
rep_DS_hh_itn_18 <- result.fun('hh_itn', 'repDS','num_p', design=hh.itn.svyd18)
head(rep_DS_hh_itn_18)
rep_DS_hh_itn_18 <- rep_DS_hh_itn_18 %>% dplyr::select(repDS, hh_itn_repDS = hh_itn,
se_repDS = se,Num_repDS = `Number of Participants`)
head(rep_DS_hh_itn_18)
#Now combine LGA files with LGA level estimates with repDS estimates
rep_DS_hh_itn_18 <- DS_hh_itn_18 %>% left_join(rep_DS_hh_itn_18) %>%
mutate(hh_itn = ifelse(hh_itn =="0"| hh_itn == "1" |is.na(hh_itn),
hh_itn_repDS, hh_itn),
ci_l = hh_itn - (1.96 * se_repDS), ci_u = hh_itn + (1.96 * se_repDS)) %>%
mutate(ci_l = ifelse(ci_l < 0, 0, ci_l), ci_u =ifelse(ci_u > 1, 1, ci_u))
head(rep_DS_hh_itn_18)
summary(rep_DS_hh_itn_18$hh_itn)
write.csv(rep_DS_hh_itn_18 , "results/archetype_sim_input/Intervention_files_LGA/ITN/over_eighteen2018repDS_LGA.csv")
# 2015
hh.itn.list[[5]] <-dataclean.HH(hh.itn.list[[5]], hml12, hv005,'hh_itn', 'hh_itn')
hh.itn.svyd15 <- svydesign.fun(hh.itn.list[[5]])
DS_hh_itn_15 <- result.fun('hh_itn', 'LGA','num_p', design=hh.itn.svyd15)
head(DS_hh_itn_15)
# DS_hh_itn_15_v2 <- DS_hh_itn_15 %>%
# dplyr::select(State, hv025, hh_itn) %>%
# pivot_wider(names_from = hv025, values_from = hh_itn)
# head(DS_hh_itn_15_v2)
#
# write.csv(DS_hh_itn_15_v2, "results/urbanvsrural/2015_ITNstate.csv")
#next join each LGA to their repDS
DS_hh_itn_15 <- rep_DS %>% left_join(DS_hh_itn_15)
head(DS_hh_itn_15)
summary(DS_hh_itn_15$hh_itn)
#repDS_level estimates and change variable names
rep_DS_hh_itn_15 <- result.fun('hh_itn', 'repDS','num_p', design=hh.itn.svyd15)
head(rep_DS_hh_itn_15)
rep_DS_hh_itn_15 <- rep_DS_hh_itn_15 %>% dplyr::select(repDS, hh_itn_repDS = hh_itn,
se_repDS = se, Num_repDS = `Number of Participants`)
head(rep_DS_hh_itn_15)
#Now combine LGA files with LGA level estimates with repDS estimates
rep_DS_hh_itn_15 <- DS_hh_itn_15 %>% left_join(rep_DS_hh_itn_15) %>%
mutate(hh_itn = ifelse(hh_itn =="0"| hh_itn == "1" |is.na(hh_itn),
hh_itn_repDS, hh_itn),
ci_l = hh_itn - (1.96 * se_repDS), ci_u = hh_itn + (1.96 * se_repDS)) %>%
mutate(ci_l = ifelse(ci_l < 0, 0, ci_l), ci_u =ifelse(ci_u > 1, 1, ci_u))
head(rep_DS_hh_itn_15)
write.csv(rep_DS_hh_itn_15, "results/archetype_sim_input/Intervention_files_LGA/ITN/over_eighteen2015repDS_LGA_v2.csv")
# 2013
hh.itn.list[[4]] <-dataclean.HH(hh.itn.list[[4]], hml12, hv005,'hh_itn', 'hh_itn')
hh.itn.svyd13 <- svydesign.fun(hh.itn.list[[4]])
DS_hh_itn_13 <- result.fun('hh_itn', 'LGA','num_p', design=hh.itn.svyd13)
head(DS_hh_itn_13)
# DS_hh_itn_13_v2 <- DS_hh_itn_13 %>%
# dplyr::select(State, hv025, hh_itn) %>%
# pivot_wider(names_from = hv025, values_from = hh_itn)
# head(DS_hh_itn_13_v2)
#
# write.csv(DS_hh_itn_13_v2, "results/urbanvsrural/2013_ITNstate.csv")
#next join each LGA to their repDS
DS_hh_itn_13 <- rep_DS %>% left_join(DS_hh_itn_13)
head(DS_hh_itn_13)
summary(DS_hh_itn_13$hh_itn)
#repDS_level estimates and change variable names
rep_DS_hh_itn_13 <- result.fun('hh_itn', 'repDS','num_p', design=hh.itn.svyd13)
head(rep_DS_hh_itn_13)
rep_DS_hh_itn_13 <- rep_DS_hh_itn_13 %>% dplyr::select(repDS, hh_itn_repDS = hh_itn,
se_repDS = se, Num_repDS = `Number of Participants`)
head(rep_DS_hh_itn_13)
#Now combine LGA files with LGA level estimates with repDS estimates
rep_DS_hh_itn_13 <- DS_hh_itn_13 %>% left_join(rep_DS_hh_itn_13) %>%
mutate(hh_itn = ifelse(hh_itn =="0"| hh_itn == "1" |is.na(hh_itn),
hh_itn_repDS, hh_itn),
ci_l = hh_itn - (1.96 * se_repDS), ci_u = hh_itn + (1.96 * se_repDS)) %>%
mutate(ci_l = ifelse(ci_l < 0, 0, ci_l))
head(rep_DS_hh_itn_13)
write.csv(rep_DS_hh_itn_13, "results/archetype_sim_input/Intervention_files_LGA/ITN/U52013repDS_LGA_v2.csv")
# 2010
hh.itn.list[[3]] <-dataclean2.HH(hh.itn.list[[3]], hml12, hv005,'hh_itn', 'hh_itn', 'hv023')
hh.itn.svyd10 <- svydesign.fun(hh.itn.list[[3]])
DS_hh_itn_10 <- result.fun('hh_itn', 'LGA','num_p', design=hh.itn.svyd10)
head(DS_hh_itn_10)
# DS_hh_itn_10_v2 <- DS_hh_itn_10 %>%
# dplyr::select(State, hv025, hh_itn) %>%
# pivot_wider(names_from = hv025, values_from = hh_itn)
# head(DS_hh_itn_10_v2)
#
# write.csv(DS_hh_itn_10_v2, "results/urbanvsrural/2010_ITNstate.csv")
#next join each LGA to their repDS
DS_hh_itn_10 <- rep_DS %>% left_join(DS_hh_itn_10)
head(DS_hh_itn_10)
summary(DS_hh_itn_10$hh_itn)
#repDS_level estimates and change variable names
rep_DS_hh_itn_10 <- result.fun('hh_itn', 'repDS','num_p', design=hh.itn.svyd10)
head(rep_DS_hh_itn_10)
rep_DS_LGA_10 <- left_join(rep_DS, rep_DS_hh_itn_10)
head(rep_DS_LGA_10)
rep_DS_hh_itn_10 <- rep_DS_hh_itn_10 %>% dplyr::select(repDS, hh_itn_repDS = hh_itn,
se_repDS = se, Num_repDS = `Number of Participants`)
head(rep_DS_hh_itn_10)
#Now combine LGA files with LGA level estimates with repDS estimates
rep_DS_hh_itn_10 <- DS_hh_itn_10 %>% left_join(rep_DS_hh_itn_10) %>%
mutate(hh_itn = ifelse(hh_itn =="0"| hh_itn == "1" |is.na(hh_itn),
hh_itn_repDS, hh_itn),
ci_l = hh_itn - (1.96 * se_repDS), ci_u = hh_itn + (1.96 * se_repDS)) %>%
mutate(ci_l = ifelse(ci_l < 0, 0, ci_l), ci_u =ifelse(ci_u > 1, 1, ci_u))
#Now combine LGA files with LGA level estimates with repDS estimates
head(rep_DS_hh_itn_10)
write.csv(rep_DS_hh_itn_10, "results/archetype_sim_input/Intervention_files_LGA/ITN/v2/ten_eighteen2010repDS_LGA_v2.csv")
# cluster-level estimates
# 2018
clu_HH_ITN_18 <- result.clu.fun('hh_itn', 'v001', design=hh.itn.svyd18,hh.itn.list[[6]], "hv007")
head(clu_HH_ITN_18)
# write.csv(clu_HH_ITN_18, "results/DHS_HH_ITN/clu_hh_itn_18.csv")
# 2015
clu_HH_ITN_15 <- result.clu.fun('hh_itn', 'v001', design=hh.itn.svyd15,hh.itn.list[[5]], "hv007")
head(clu_HH_ITN_15)
# write.csv(clu_HH_ITN_14, "results/DHS_HH_ITN/clu_hh_itn_14.csv")
# 2013
clu_HH_ITN_13 <- result.clu.fun('hh_itn', 'v001', design=hh.itn.svyd13,hh.itn.list[[4]], "hv007")
head(clu_HH_ITN_13)
# 2010
clu_HH_ITN_10 <- result.clu.fun('hh_itn', 'v001', design=hh.itn.svyd10,hh.itn.list[[3]], "hv007")
head(clu_HH_ITN_10)
# write.csv(clu_HH_ITN_10, "results/DHS_HH_ITN/clu_hh_itn_10.csv")
# # 2003
# clu_HH_ITN_03 <- result.clu.fun('hh.itn', 'v001', design=hh.itn.svyd03,hh.itn.list[[1]])
# head(clu_HH_ITN_03)
#
# write.csv(clu_HH_ITN_03, "results/DHS_HH_ITN/clu_hh_itn_03.csv")
#
#####################################################################################################
## Maps
####################################################################################################
# 2018 transformations
DS_file <- LGAshp_sf %>% left_join(rep_DS_hh_itn_18)
pts_shp_18 <- st_as_sf(NGAshplist[[7]])
pts_file <- pts_shp_18 %>% left_join(clu_HH_ITN_18) #%>% filter(URBAN_RURA =="U")
head(pts_file)
summary(is.na(pts_file$hh_itn))
summary(pts_file$hh_itn)
sd(pts_file$`Number of Participants`)
# 2015 transformations
DS_file_15 <- LGAshp_sf %>% left_join(rep_DS_hh_itn_15)
pts_shp_15 <- st_as_sf(NGAshplist[[6]])
pts_file_15 <- pts_shp_15 %>% left_join(clu_HH_ITN_15) #%>% filter(URBAN_RURA =="U")
head(pts_file_15)
summary(is.na(pts_file_15$hh_itn))
summary(pts_file_15$hh_itn)
summary(pts_file_15$`Number of Participants`)
sd(pts_file_15$`Number of Participants`)
# 2013 transformations
DS_file_13 <- LGAshp_sf %>% left_join(rep_DS_hh_itn_13)
pts_shp_13 <- st_as_sf(NGAshplist[[5]])
pts_file_13 <- pts_shp_13 %>% left_join(clu_HH_ITN_13) #%>%filter(URBAN_RURA =="U")
head(pts_file_13)
summary(is.na(pts_file_13$hh_itn))
summary(pts_file_13$hh_itn)
summary(pts_file_13$`Number of Participants`)
sd(pts_file_13$`Number of Participants`)
# 2010 transformations
DS_file_10 <- LGAshp_sf %>% left_join(rep_DS_LGA_10)
head(DS_file_10)
pts_shp_10 <- st_as_sf(NGAshplist[[4]])
pts_file_10 <- pts_shp_10 %>% left_join() #%>%filter(URBAN_RURA =="U")
head(pts_file_10)
summary(is.na(pts_file_10$hh_itn))
summary(pts_file_10$hh_itn)
summary(pts_file_10$`Number of Participants`)
sd(pts_file_10$`Number of Participants`)
# # 2003 transformations
# DS_file_03 <- DS_shape_sf %>% left_join(DS_hh_itn_03)
#
# pts_file_03 <- BFshplist_sf[[3]] %>% left_join(clu_HH_ITN_03)
# 2018 map
# BF_HH_ITN18 <- tmap.fun5(DS_file, colname="hh.itn", legtitle="% de facto HH population who slept the night before the survey under any mosquito net",
# maintitle="Household (HH) ITN use by District (2018)", ptsfile=pts_file, "Number of Participants",
# "hh.itn")
#u_clu_map <- tmap.clu4(admin1_sf, ptsfile=pts_file, "Number of Participants", "hh_itn", "2018 cluster ITN Nigeria")
HH_ITN_18 <- tmap.fun3(DS_file, "hh_itn", "Prevalence", "HH ITN 2018",
pts_file, "Number of Participants", "hh_itn")
HH_ITN_18 <- tmap.fun4(DS_file, "U5 HH ITN (2018)", "Prevalence", "hh_itn")
# 2015 map
# BF_HH_ITN14 <- tmap.fun5(DS_file_14, colname="hh.itn", legtitle="% de facto HH population who slept the night before the survey under any mosquito net",
# maintitle="Household (HH) ITN use by District (2014)", ptsfile=pts_file_14, "Number of Participants",
# "hh.itn")
u_clu_map_15 <- tmap.clu4(admin1_sf, ptsfile=pts_file_15, "Number of Participants", "hh_itn", "2015 cluster ITN Nigeria")
HH_ITN_15 <- tmap.fun3(DS_file_15, "hh_itn", "Prevalence", "HH ITN 2015",
pts_file_15, "Number of Participants", "hh_itn")
HH_ITN_15 <- tmap.fun4(DS_file_15, "U5 HH ITN (2015)", "Prevalence", "hh_itn")
# 2013 map
u_clu_map_13 <- tmap.clu4(admin1_sf, ptsfile=pts_file_13, "Number of Participants", "hh_itn", "2013 cluster ITN Nigeria")
HH_ITN_13 <- tmap.fun3(DS_file_13, "hh_itn", "Prevalence", "HH ITN 2013",
pts_file_13, "Number of Participants", "hh_itn")
HH_ITN_13 <- tmap.fun4(DS_file_13, "U5 HH ITN (2013)", "Prevalence", "hh_itn")
# 2010 map
# BF_HH_ITN10 <- tmap.fun5(DS_file_10, colname="hh.itn", legtitle="% de facto HH population who slept the night before the survey under any mosquito net",
# maintitle="Household (HH) ITN use by District (2010)", ptsfile=pts_file_10, "Number of Participants",
# "hh.itn")
u_clu_map_10 <- tmap.clu4(admin1_sf, ptsfile=pts_file_15, "Number of Participants", "hh_itn", "2010 cluster ITN Nigeria")
HH_ITN_10 <- tmap.fun3(DS_file_10, "hh_itn", "Prevalence", "HH ITN 2010",
pts_file_10, "Number of Participants", "hh_itn")
HH_ITN_10 <- tmap.fun4(DS_file_10, "U5 HH ITN (2010)", "Prevalence", "hh_itn")
# 2003 map
# BF_HH_ITN03 <- tmap.fun5(DS_file_03, colname="hh.itn", legtitle="% de facto HH population who slept the night before the survey under any mosquito net",
# maintitle="Household (HH) ITN use by District (2003)", ptsfile=pts_file_03, "Number of Participants",
# "hh.itn")
all_hh.itn <- tmap_arrange(HH_ITN_10,HH_ITN_13, HH_ITN_15,HH_ITN_18)
tmap_save(tm = all_hh.itn, filename = "results/archetype_sim_input/Intervention_files_LGA/ITN/hh_itn/hh_itn_repDS_v2.pdf",
width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
cluster.itn <- tmap_arrange(u_clu_map_10,u_clu_map_13,u_clu_map_15,u_clu_map)
## creating a combined prevalence map for all years
#row binding cluster points
pts_merge <- rbind(pts_file,pts_file_15,pts_file_13,pts_file_10)
head(pts_merge)
summary(is.na(pts_merge$hh_itn))
summary(pts_merge$hh_itn)
summary(pts_merge$`Number of Participants`)
sd(pts_merge$`Number of Participants`)
#aggregated plot on state shape file
u_clu_map_bindrows <- tmap.clu4(admin1_sf, ptsfile=pts_merge, "Number of Participants", "hh_itn", "ITN 2010 - 2018 in Nigeria")
#creates aggreagted map of pfpr for all years using mean values
#calculate mean of points to pfpr estimate over time
pts_merge_test <- pts_merge %>% drop_na(hh_itn)
pts100 <- st_is_within_distance(pts_merge_test, dist = 2000)
class(pts100)
res <- data.frame(id=1:length(pts100),x=NA, y=NA,mean_hh_itn=NA)
res$x <- sapply(pts100, function(p){mean(pts_merge_test$LONGNUM[p])})
res$y <- sapply(pts100, function(p){mean(pts_merge_test$LATNUM[p])})
res$mean_hh_itn<- sapply(pts100, function(p) #scaled by the proportion of participants in each nearby cluster
{sum((pts_merge_test$`Number of Participants`[p]/sum(pts_merge_test$`Number of Participants`[p]) * pts_merge_test$hh_itn[p]))})
res$`Number of Participants` <- sapply(pts100, function(p){mean(pts_merge_test$`Number of Participants`[p])})
res_2_itn <- res %>% distinct(x, y, .keep_all = TRUE)
coordinates(res_2) <- c("x","y")
proj4string(res_2) <- CRS('+proj=longlat +datum=WGS84 +no_defs')
res_sf_itn <- st_as_sf(res_2)
head(res_sf_itn)
summary(is.na(res_sf_itn$mean_hh_itn))
summary(res_sf_itn$mean_hh_itn)
summary(res_sf_itn$`Number of Participants`)
sd(res_sf_itn$`Number of Participants`)
u_clu_map_aggregated <- tmap.clu4(admin1_sf, ptsfile=res_sf, "Number of Participants", "mean_hh_itn", "Aggregated ITN 2010 - 2018 in Nigeria")
all_maps <- tmap_arrange(u_clu_map_10,u_clu_map_13,u_clu_map_15,u_clu_map,u_clu_map_bindrows,u_clu_map_aggregated)
tmap_save(tm = all_maps, filename = "results/urban_cluster/ITN/itn_diff.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
<file_sep>rm(list=ls())
itn <- read.csv("C:/Users/ido0493/Box/NU-malaria-team/projects/hbhi_nigeria/simulation_inputs/DHS/LGA_intervention_files/ITN/ITN_by_LGA_v3.csv")
head(itn)
<file_sep>library(splitstackshape)
# For scenario 3, we first get an estimate of the averagechange in coverage per year
cm_3 <- read.csv('bin/projection/s3_v3/cm_trend.csv')
head(cm_3)
plot(cm_3$year, cm_3$comboACT)
cm_split <- split(cm_3, cm_3$repDS)
#models
# summary(ahoda)$coef
# summary(list.mod[[2]])$coef
model.fun <- function(x){g <- lm(comboACT ~ year, data = x)}
ex.fun <- function(x){y <- summary(x)$coef
y[2]}
list.mod <- map(cm_split, model.fun)
summary(list.mod[1]$`Ahoada West`)
# png("Ahoda_West.png")
# plot(comboACT ~ year, data = cm_split$`Ahoada West`, xlab = "Year", ylab = "Coverage Percent")
# abline(coef(list.mod[1]$`Ahoada West`)[1:2], col = "red")
# cf <- round(coef(list.mod[1]$`Ahoada West`), 3)
#
# eq <- paste0(" CM coverage = ", cf[1]," + ", abs(cf[2]), " year ")
#
# mtext(eq, 3, line=-2)
# dev.off()
scale.factors <- map(list.mod, ex.fun)
values <- do.call(rbind.data.frame, scale.factors)
lst.names <- tibble(names(scale.factors))
df <- cbind (lst.names,values)
colnames(df)<- c("Rep_DS", "scale_values")
write.csv(df, 'bin/projection/s3_v3/scale_values.csv')
# now we use the df values
cm_2 <- read.csv('bin/projection/s2_v2/HS_placeholder_v2.csv')
head(cm_2)
summary(cm_2$U5_coverage)
summary(cm_2$adult_coverage)
cm_3 <- expandRows(cm_2, count = 6,count.is.col=FALSE,
drop = FALSE)
head(cm_3)
lookup_key <- c(1, 2, 3, 4, 5, 6) # 3, 4, 5, 6
cm_3 <- cm_3 %>% mutate(round =
rep(lookup_key, times=774), severe_cases =0.49)
head(cm_3)
sim_day <- c(71, 436)#801, 1166, 1532, 1898
year_sim <- c(2020, 2021, 2022, 2023, 2024, 2025)
duration <- c(365, 365, 365, 365, 365, 294)
df_sim <- tibble(lookup_key, sim_day, year_sim, duration)
cm_3$simday[cm_3$round %in% df_sim$lookup_key == TRUE]<-
sim_day[df_sim$lookup_key %in% cm_3$round == TRUE]
cm_3$duration[cm_3$round %in% df_sim$lookup_key == TRUE] <-
duration[df_sim$lookup_key %in% cm_3$round == TRUE]
cm_3$year[cm_3$round %in% df_sim$lookup_key == TRUE] <-
year_sim[df_sim$lookup_key %in% cm_3$round == TRUE]
head(cm_3)
cm_3 <- cm_3 %>% left_join(df)
head(cm_3)
max_v <- 1
cm_3 <- cm_3 %>% mutate(scale_values = ifelse(round == 2, scale_values*2, ifelse(round == 3,
scale_values*3,ifelse(round ==4, scale_values *4,
ifelse(round ==5, scale_values *5,
ifelse(round ==6, scale_values*6, scale_values))) )),
U5_coverage = pmin(U5_coverage + scale_values,max_v),
adult_coverage = U5_coverage, severe_cases = pmin(severe_cases + scale_values, max_v))
head(cm_3, 15)
write.csv(cm_3, 'results/archetype_sim_input/Intervention_files_LGA/case_management/cm_scen3_v3.csv')
<file_sep>library(data.table)
library(splitstackshape)
cc_smc <- read.csv("bin/projection/s1/smc_LGA.csv")
table(cc_smc$State)
cc_smc_repDS <- cc_smc %>% left_join(rep_DS)
table(cc_smc_repDS$repDS)
summary(rep_DS$LGA)
cc_smc_repDS <- cc_smc_repDS %>%
mutate(peak = if_else(repDS == 'Akinyele', 'may',
if_else(repDS == 'Alkaleri', 'july',
if_else(repDS == 'Babura','may',
if_else(repDS =='Birnin Kebbi','august',
if_else(repDS =='Darazo','july',
if_else(repDS == 'Gawabawa', 'august',
if_else(repDS =='Giwa', 'august',
if_else(repDS =='Gwarzo', 'august',
if_else(repDS == 'Isoko South', 'june',
if_else(repDS =='Keana', 'august',
if_else(repDS =='Ngor-Okpala', 'june',
if_else(repDS =='Nsit Ubium', 'june',
if_else(repDS=='Obubra','june',
if_else(repDS == 'Oke-Ero','july',
if_else(repDS =='Oru West', 'june',
if_else(repDS =='Owan East','march',
if_else(repDS == 'Rimi','march',
if_else(repDS == 'Soba', 'july',
if_else(repDS == 'Takali','september',
if_else(repDS =='Taura', 'july',
if_else(repDS =='Uzo-Uwani', 'june', ''))))))))))))))))))))))
table(cc_smc_repDS$peak)
cc_smc_2020 <- cc_smc_repDS %>%
mutate(simday = if_else(peak == 'july',186,
if_else(peak == 'may',131,
if_else(peak == 'august', 223,
if_else(peak == 'june', 162,
if_else(peak =='march', 70,
if_else(peak =='september',250, NA_real_)))))),
year = 2020)
tail(cc_smc_2020)
cc_smc_2020_v2 <- expandRows(cc_smc_2020, count = 4,count.is.col=FALSE,
drop = FALSE)
cc_smc_2020_v3<- data.frame(row.names(cc_smc_2020_v2),
cc_smc_2020_v2, row.names = NULL)
cc_smc_2020_v3 <- cc_smc_2020_v3 %>%
group_by(LGA) %>% mutate(round =
rleid(row.names.cc_smc_2020_v2.))
cc_smc_2020_v4 <- cc_smc_2020_v3 %>%
mutate(simday = if_else(round == 2, simday + 30,
if_else(round == 3, simday + 60,
if_else(round ==4, simday + 90, simday))))
head(cc_smc_2020_v4)
#2021
cc_smc_2021 <- cc_smc_2020_v4 %>% mutate(simday =
if_else(peak == 'july',550,if_else(peak == 'may',488,
if_else(peak == 'august', 579, if_else(peak == 'june',
518, if_else(peak =='march', 426, if_else(peak =='september',
610, NA_real_)))))), year = 2021)
head(cc_smc_2021)
cc_smc_2021 <- cc_smc_2021 %>%
mutate(simday = if_else(round == 2, simday + 30,
if_else(round == 3, simday + 60,
if_else(round ==4, simday +90, simday))))
head(cc_smc_2021)
#2022
cc_smc_2022 <- cc_smc_2020_v4 %>% mutate(simday =
if_else(peak == 'july',915,if_else(peak == 'may',852,
if_else(peak == 'august', 950, if_else(peak == 'june',
887, if_else(peak =='march', 796, if_else(peak =='september',
978, NA_real_)))))), year = 2022)
head(cc_smc_2022)
cc_smc_2022 <- cc_smc_2022 %>%
mutate(simday = if_else(round == 2, simday + 30,
if_else(round == 3, simday + 60,
if_else(round ==4, simday + 90, simday))))
head(cc_smc_2022)
#2023
cc_smc_2023 <- cc_smc_2020_v4 %>% mutate(simday =
if_else(peak == 'july',1286,if_else(peak == 'may',1223,
if_else(peak == 'august', 1314, if_else(peak == 'june',
1251, if_else(peak =='march', 1160, if_else(peak =='september',
1342, NA_real_)))))), year = 2023)
head(cc_smc_2023)
cc_smc_2023 <- cc_smc_2023 %>%
mutate(simday = if_else(round == 2, simday + 30,
if_else(round == 3, simday + 60,
if_else(round ==4, simday + 90, simday))))
head(cc_smc_2023)
#2024
cc_smc_2024 <- cc_smc_2020_v4 %>% mutate(simday =
if_else(peak == 'july',1646,if_else(peak == 'may',1587,
if_else(peak == 'august', 1678, if_else(peak == 'june',
1622, if_else(peak =='march', 1531, if_else(peak =='september',
1713, NA_real_)))))), year = 2024)
head(cc_smc_2024)
cc_smc_2024 <- cc_smc_2024 %>%
mutate(simday = if_else(round == 2, simday +30,
if_else(round == 3, simday + 60,
if_else(round ==4, simday + 90, simday))))
head(cc_smc_2024)
#2025
cc_smc_2025 <- cc_smc_2020_v4 %>% mutate(simday =
if_else(peak == 'july',2014,if_else(peak == 'may',1951,
if_else(peak == 'august', 2049, if_else(peak == 'june',
1988, if_else(peak =='march', 1895, if_else(peak =='september',
2079, NA_real_)))))), year = 2025)
head(cc_smc_2025)
cc_smc_2025 <- cc_smc_2025 %>%
mutate(simday = if_else(round == 2, simday + 30,
if_else(round == 3, simday + 60,
if_else(round ==4, simday + 90, simday))))
head(cc_smc_2025)
all_smc_cc <-do.call("rbind", list(cc_smc_2020_v4, cc_smc_2021,
cc_smc_2022, cc_smc_2023, cc_smc_2024,
cc_smc_2025))
summary(all_smc_cc$year)
head(all_smc_cc)
all_smc_cc$LGA <- gsub("\\/", "-", all_smc_cc$LGA)
all_smc_cc <- all_smc_cc %>% mutate(duration = -1, coverage_high_access = 0.8,
coverage_low_access = 0.2, max_age = 5 )
write.csv(all_smc_cc, 'results/archetype_sim_input/Intervention_files_LGA/smc_cc_v3.csv')
<file_sep>#######################################################################################################################
# --- Data preparation --- #
#######################################################################################################################
#run seperately for RDT and micrscopy
# creating list of files with Pfpr data for 2010, 2015 & 2018
pfpr.list <- list(NGAfiles[[12]], NGAfiles[[18]], NGAfiles[[21]])
# recoding pfpr (microscopy data)
# 2018
table(pfpr.list[[3]][,"hml32"])
table(pfpr.list[[3]][,"hml35"])
# 2015
pfpr.list[[2]][,"hml32"] <-recoder.pfpr(pfpr.list[[2]][,"hml32"])
table(pfpr.list[[2]][,"hml32"])
table(pfpr.list[[2]][,"hml35"])
# 2010
pfpr.list[[1]][,"hml32"] <-recoder.pfpr(pfpr.list[[1]][,"hml32"])
table(pfpr.list[[1]][,"hml32"])
# pfpr.list[[1]][,"hml35"] <-recoder(pfpr.list[[1]][,"hml35"])
# table(pfpr.list[[1]][,"hml32"])
# dim(pfpr.list[[1]])
# val_labels(pfpr.list[[3]]$hml32)
#subsetting for microscopy (denominator -hh selected for hemoglobin, child slept there last night and have result for test)
pfpr.list <- lapply(pfpr.list, subset, hv042 == "1" & hv103 == "1" & hml32 %in% c(0, 1) )
# key list for pfpr
keyspfpr <- list(key_list[[4]], key_list[[6]], key_list[[7]]) #changing to a list of keys
# applying function to create month and year of survey. Note this function only works for person and household recode file
pfpr.list <- map(pfpr.list, survey.month.fun)
# key datasets and dhs/mis datasets are joined
pfpr.list <- map2(pfpr.list, keyspfpr, left_join) #PR datasets
rep_DS.ls <- list(rep_DS)
pfpr.list <- map2(pfpr.list, rep_DS.ls, left_join) #PR datasets
####################################################################################################
## Pfpr analysis
####################################################################################################
# DS-level estimates
# recoding and renaming pfpr datasets
# 2018 PR NGA DHS
pfpr.list[[3]] <- dataclean.para(pfpr.list[[3]], hv005, hc1, hml32, 'hml32', 'p_test')
pfpr.list[[3]] <- dataclean.para(pfpr.list[[3]], hv005, hc1, hml35, 'hml35', 'p_testRDT')
table(pfpr.list[[3]]$time2)
hml32.svyd18 <- svydesign.fun(pfpr.list[[3]])
#write.csv(pfpr.list[[3]], "bin/pfpr/pfpr2018.csv")
#write.csv(pfpr.list[[3]], "bin/pfpr/pfpr2018RDT.csv")
# 2018 estimation of pfpr by LGA replaced with state value
#estimate state value
S_merge_ym_18 <- result.fun('p_test', 'State + hv025', 'num_p', design=hml32.svyd18) #microscopy
head(S_merge_ym_18)
S_merge_ym_18_v2 <- S_merge_ym_18 %>%
dplyr::select(State, hv025, p_test) %>%
pivot_wider(names_from = hv025, values_from = p_test)
head(S_merge_ym_18_v2)
write.csv(S_merge_ym_18_v2, "results/urbanvsrural/2018_micropfpr_LGA.csv")
S_merge_ym_18 <- S_merge_ym_18 %>% dplyr::select(State, time2, PfPr_microscopy = PfPr, ci_l_micro = ci_l,
ci_u_micro = ci_u, num_state_micro = `Number of Kids`)
head(S_merge_ym_18)
S_merge_ym_18$LGA <- gsub("\\/", "-", S_merge_ym_18$LGA)
write.csv(S_merge_ym_18, "results/pfpr_LGA/2018_micropfpr_LGA.csv")
#estimate LGA value
DS_merge_ym_18 <- result.fun.para('p_test', 'LGA + time2', 'num_p', 'LGA', design=hml32.svyd18) #microscopy
head(DS_merge_ym_18)
DS_merge_ym_18_RDT$LGA <- gsub("\\/", "-", DS_merge_ym_18_RDT$LGA)
write.csv(DS_merge_ym_18_RDT, "results/pfpr_LGA/2018_RDTpfpr_LGA.csv")
#join LGA estimates to LGA admin and state estimates
pfpr_LGA_state_val <- DS_merge_ym_18 %>% left_join(LGAshp_sf) %>% left_join(S_merge_ym_18) %>%
dplyr::select(LGA, time2, PfPrRDT_state, ci_l_state, ci_u_state)
head(pfpr_LGA_state_val)
write.csv(pfpr_LGA_state_val, "results/pfpr_state/pfpr_RDT2018_LGA_state_val.csv")
# recoding and renaming pfpr datasets
# 2015 NGA BF DHS
pfpr.list[[2]] <- dataclean.para(pfpr.list[[2]], hv005, hc1, hml32, 'hml32', 'p_test')
pfpr.list[[2]] <- dataclean.para(pfpr.list[[2]], hv005, hc1, hml35, 'hml35', 'p_testRDT')
hml32.svyd15 <- svydesign.fun(pfpr.list[[2]])
table(pfpr.list[[2]]$time2)
# 2015
# 2015 estimation of pfpr by LGA replaced with state value
# estimate state value
S_merge_ym_15 <- result.fun('p_test', 'State + hv025', 'num_p', design=hml32.svyd15) #microscopy
head(S_merge_ym_15)
S_merge_ym_15_v2 <- S_merge_ym_15 %>%
dplyr::select(State, hv025, p_test) %>%
pivot_wider(names_from = hv025, values_from = p_test)
head(S_merge_ym_15_v2)
write.csv(S_merge_ym_15_v2, "results/urbanvsrural/2015_micropfpr_LGA.csv")
S_merge_ym_15 <- S_merge_ym_15 %>% dplyr::select(State, time2, PfPr_RDT = PfPr, ci_l_RDT = ci_l,
ci_u_RDT = ci_u, num_state_RDT = `Number of Kids`)
head(S_merge_ym_15)
write.csv(S_merge_ym_15, "results/pfpr_state/pfpr_state_v3/2015_RDTpfpr_state_time.csv")
# estimate LGA value
DS_merge_ym_15 <- result.fun.para('p_testRDT', 'LGA + time2', 'num_p', 'LGA', design=hml32.svyd15) #microscopy
head(DS_merge_ym_15)
DS_merge_ym_15$LGA <- gsub("\\/", "-", DS_merge_ym_15$LGA)
write.csv(DS_merge_ym_15, "results/pfpr_LGA/2015_RDTpfpr_LGA.csv")
#join LGA estimates to LGA admin and state estimates
pfpr_LGA_state_val_15 <- DS_merge_ym_15 %>% left_join(LGAshp_sf) %>% left_join(S_merge_ym_15) %>%
dplyr::select(LGA, time2, PfPrRDT_state, ci_l_state, ci_u_state)
head(pfpr_LGA_state_val_15)
write.csv(pfpr_LGA_state_val_15, "results/pfpr_state/pfprRDT_2015_LGA_state_val.csv")
# recoding and renaming pfpr datasets
# 2010 PR BF DHS
pfpr.list[[1]] <- dataclean.para(pfpr.list[[1]], hv005, hc1, hml32, 'hml32', 'p_test')
write.csv(pfpr.list[[1]], "bin/pfpr/pfpr2010.csv")
table(pfpr.list[[1]]$time2)
pfpr.list[[1]] <- dataclean.para(pfpr.list[[1]], hv005, hc1, hml35,'hml35', 'p_testRDT')
write.csv(pfpr.list[[1]], "bin/pfpr/pfpr2010RDT.csv")
hml32.svydesign <- svydesign.fun(pfpr.list[[1]])
# 2010 PR BF DHS
# 2010 estimation of pfpr by LGA replaced with state value
# estimate state value
S_merge_ym_15 <- result.fun('p_test', 'State + hv025', 'num_p', design=hml32.svyd15) #microscopy
head(S_merge_ym_15)
S_merge_ym_15_v2 <- S_merge_ym_15 %>%
dplyr::select(State, hv025, p_test) %>%
pivot_wider(names_from = hv025, values_from = p_test)
head(S_merge_ym_15_v2)
write.csv(S_merge_ym_15_v2, "results/urbanvsrural/2015_micropfpr_LGA.csv")
S_merge_ym_10 <- result.fun('p_test', 'State + hv025', 'num_p', design=hml32.svydesign) #microscopy
head(S_merge_ym_10)
S_merge_ym_10_v2 <- S_merge_ym_10 %>%
dplyr::select(State, hv025, p_test) %>%
pivot_wider(names_from = hv025, values_from = p_test)
head(S_merge_ym_10_v2)
write.csv(S_merge_ym_10_v2, "results/urbanvsrural/2010_micropfpr_LGA.csv")
S_merge_ym_10 <- S_merge_ym_10 %>% dplyr::select(State, time2, PfPr_RDT = PfPr, ci_l_RDT = ci_l,
ci_u_RDT = ci_u, num_state_RDT = `Number of Kids`)
head(S_merge_ym_10)
write.csv(S_merge_ym_10, "results/pfpr_state/pfpr_state_v3/2010_RDTpfpr_state_val_time.csv")
# estimate LGA value
DS_merge_ym_10 <- result.fun.para('p_testRDT', 'LGA + time2', 'num_p', 'LGA', design=hml32.svydesign) #microscopy
head(DS_merge_ym_10)
DS_merge_ym_10$LGA <- gsub("\\/", "-", DS_merge_ym_10$LGA)
write.csv(DS_merge_ym_10, "results/pfpr_LGA/2010_RDTpfpr_LGA.csv")
#join LGA estimates to LGA admin and state estimates
pfpr_LGA_state_val_10 <- DS_merge_ym_10 %>% left_join(LGAshp_sf) %>% left_join(S_merge_ym_10) %>%
dplyr::select(LGA, time2, PfPr_state, ci_l_state, ci_u_state)
head(pfpr_LGA_state_val_10)
write.csv(pfpr_LGA_state_val_10, "results/pfpr_state/pfprRDT_2010_LGA_state_val.csv")
#creating a csv file with both the PfPr and number of surveyed kids by timepoint (ymd)
write.csv(DS_merge_ym_18,file="results/DS18_pfpr_ym_micro.csv") # 2018 PfPr micro BF DHS
write.csv(DS_merge_ym_RDT18, file="results/DS18_pfpr_ym_RDT.csv") # 2018 PfPr PR RDT BF DHS
#creating a csv file with both the PfPr and number of surveyed kids by timepoint (ymd)
write.csv(DS_merge_ym_15,file="DS15_pfpr_ym_micro.csv") # 2015 PfPr micro BF DHS
write.csv(DS_merge_ym_RDT15, file="DS15_pfpr_ym_RDT.csv") # 2015 PfPr PR RDT BF DHS
#creating a csv file with both the PfPr and number of surveyed kids by timepoint (ymd) for the DSs
write.csv(DS_merge_ym, file="results/pfpr_repDS/DS10_pfpr_ym_micro.csv") # 2010 PfPr PR micro BF DHS
write.csv(DS_merge_ym_RDT, file="results/pfpr_repDS/DS10_pfpr_ym_RDT.csv") # 2010 PfPr PR RDT BF DHS
# cluster-level estimates
# 2018 PR BF DHS
clu_ptest_num_18 <- result.clu.fun.para('p_test', 'v001+time2', 'num_p', 'v001',design=hml32.svyd18, pfpr.list[[3]]) #microscopy
head(clu_ptest_num_18)
clu_ptest_num_18 <- result.clu.fun('p_test', 'v001', design=hml32.svyd18,pfpr.list[[3]], 'hv007')
head(clu_ptest_num_18)
clu_ptest_num_RDT18 <- result.clu.fun.para('p_testRDT', 'v001 + time2','num_p', 'v001', design=hml32.svyd18, pfpr.list[[3]]) #RDT
head(clu_ptest_num_RDT18)
# 2015 PR BF DHS
clu_ptest_num_15 <- result.clu.fun.para('p_test', 'v001+time2', 'num_p', 'v001', design=hml32.svyd15, pfpr.list[[2]]) #microscopy
head(clu_ptest_num_15)
clu_ptest_num_15 <- result.clu.fun('p_test', 'v001', design=hml32.svyd15,pfpr.list[[2]], 'hv007')
head(clu_ptest_num_15)
clu_ptest_num_RDT15 <- result.clu.fun.para('p_testRDT', 'v001 + time2','num_p', 'v001', design=hml32.svyd15, pfpr.list[[2]]) #RDT
head(clu_ptest_num_RDT15)
# 2010 PR BF DHS
clu_ptest_num <- result.clu.fun('p_test', 'v001',design=hml32.svydesign, pfpr.list[[1]]) #microscopy
head(clu_ptest_num)
clu_ptest_num_10 <- result.clu.fun('p_test', 'v001', design=hml32.svydesign,pfpr.list[[1]], 'hv007')
head(clu_ptest_num_10)
clu_ptest_num_RDT <- result.clu.fun.para('p_testRDT', 'v001 + time2','num_p', 'v001', design=hml32.svydesign, pfpr.list[[1]]) #RDT
head(clu_ptest_num_RDT)
#creating a csv file with both the PfPr and number of surveyed kids by timepoint (ymd)
write.csv(clu_ptest_num, file="clu10_pfpr_ym_micro.csv") # 2010 PfPr PR micro BF DHS
write.csv(clu_ptest_num_RDT, file="clu10_pfpr_ym_RDT.csv") # 2010 PfPr PR RDT BF DHS
write.csv(clu_ptest_num_15,file="clu15_pfpr_ym_micro.csv") # 2015 PfPr micro BF DHS
write.csv(clu_ptest_num_RDT15, file="clu15_pfpr_ym_RDT15.csv") # 2015 PfPr PR RDT BF DHS
write.csv(clu_ptest_num_18,file="results/clu15_pfpr_ym_micro.csv") # 2018 PfPr micro BF DHS
write.csv(clu_ptest_num_RDT18, file="results/clu15_pfpr_ym_RDT15.csv") # 2018 PfPr PR RDT BF DHS
#######################################################################################################
# merging to identify DSs with no estimates
#######################################################################################################
# set up an empty dataframe with the LGA names so LGA with no estimates can be identified
DS_merge<-data.frame(LGA=LGAshp@data[,"LGA"])
# read in the MAP shapefiles and convert to sf object to merge
MAPshp <- readOGR("bin/nigeria_MAP/District_Summary_Shapefiles", layer ="NGA_pfpr_maps_2-4", use_iconv=TRUE, encoding= "UTF-8")
MAPshp<-st_as_sf(MAPshp)
# 2018 PR BF DHS
DS_merge_noest18<-DS_merge%>%left_join(DS_merge_ym_18)%>%filter(is.na(p_test))
head(DS_merge_noest18)
colnames(DS_merge_noest18)[1] <- "District"
DS_merge_noest18 <- DS_merge_noest18%>%left_join(MAPshp)%>%dplyr::select(District, Region, map3_2018, map4_2018, map4_LCI18, map4_UCI18)
write.csv(DS_merge_noest18, file="results/DS18_noest.csv") # 2018 PfPr PR micro BF DHS
#
# # 2015 PR BF DHS
# DS_merge_noest15<-DS_merge%>%left_join(ptest_15_no_time)%>%filter(is.na(p_test))
# head(DS_merge_noest15)
# colnames(DS_merge_noest15)[1] <- "District"
#
# DS_merge_noest15 <- DS_merge_noest15%>%left_join(MAPshp)%>%dplyr::select(District, Region, map3_2015, map4_2015, map4_LCI15, map4_UCI15)
#
#
# write.csv(DS_merge_noest15, file="DS15_noest.csv") # 2015 PfPr PR micro BF DHS
#
#
#
# # 2010 PR BF DHS
# DS_merge_noest<-DS_merge%>%left_join(ptest_10_no_time)%>%filter(is.na(p_test))
# head(DS_merge_noest)
# colnames(DS_merge_noest)[1] <- "District"
#
# DS_merge_noest <- DS_merge_noest%>%left_join(MAPshp)%>%dplyr::select(District, Region, map3_2010, map4_2010, map4_LCI10, map4_UCI10)
########################################################################################################
# Treating the DHS as a random sample to estimate Pfpr for Banfora (substitute 2010 and 2015 data)
########################################################################################################
dhs <- pfpr.list[[3]]%>% dplyr:: select(LGA, p_test, time2) %>% filter(!is.na(p_test))
dhs2<-na.omit(dhs)%>%
group_by(LGA, time2)%>%
summarise_each(funs(mean, sd, std.error, n()))
write.csv(dhs2, "results/SRS18_ptest_micro.csv")
#####################################################################################################
#####################################################################################################
## Maps
####################################################################################################
# 2018 transformations
# DS_file <- LGAshp_sf %>% left_join(DS_merge_ym_18)
pts_shp_18 <- st_as_sf(NGAshplist[[7]])
pts_file <- pts_shp_18 %>% left_join(clu_ptest_num_18) %>% filter(URBAN_RURA =="U")
head(pts_file)
# num_part <- pts_file$`Number of Participants`
# num_part <- na.omit(num_part)
# sd(num_part)
# 2015 transformations
# DS_file15 <- LGAshp_sf %>% left_join(DS_merge_ym_15)
pts_shp_15 <- st_as_sf(NGAshplist[[6]])
pts_file_15 <- pts_shp_15 %>% left_join(clu_ptest_num_15)%>%filter(URBAN_RURA =="U")
head(pts_file_15)
sd(pts_file_15$`Number of Participants`)
# 2010 transformations
# DS_file10 <- LGAshp_sf %>% left_join(DS_merge_ym)
# DS_file10 <- LGAshp_sf %>% left_join(plot.file)
pts_shp_10 <- st_as_sf(NGAshplist[[4]])
pts_file_10 <- pts_shp_10 %>% left_join(clu_ptest_num_10)%>%filter(URBAN_RURA =="U")
head(pts_file_10)
sd(pts_file_10$`Number of Participants`)
# 2018 map
nga_pfpr18 <- tmap.fun1(DS_file, DSmapvalue="p_test", adminlegtitle="Malaria prevalence",
main_title="U5 Malaria prevalence by LGA (2018)", text_title = "LGA",
ptsfile=pts_file, "Number of Participants", "p_test")
u_clu_map <- tmap.clu3(admin1_sf, ptsfile=pts_file, "Number of Participants", "p_test", "2018 cluster PfPR Nigeria")
summary(pts_file$`Number of Participants`)
sum(!is.na(pts_file$p_test))
summary(pts_file$`Number of Participants`)
summary(pts_file$p_test)
#2015 map
nga_pfpr15 <- tmap.fun1(DS_file15, DSmapvalue="p_test", adminlegtitle="Malaria prevalence",
main_title="U5 Malaria prevalence by LGA (2015)", text_title = "LGA",
ptsfile=pts_file_15, "Number of Participants", "p_test")
u_clu_map_15 <- tmap.clu2(admin1_sf, ptsfile=pts_file_15, "Number of Participants", "p_test", "2015 cluster PfPR Nigeria")
sum(!is.na(pts_file_15$p_test))
summary(pts_file_15$`Number of Participants`)
summary(pts_file_15$p_test)
#2010 map
nga_pfpr10 <- tmap.fun1(DS_file10, DSmapvalue="p_test", adminlegtitle="Malaria prevalence",
main_title="U5 Malaria prevalence by LGA (2010)", text_title = "LGA",
ptsfile=pts_file_10, "Number of Participants", "p_test")
u_clu_map_10 <- tmap.clu2(admin1_sf, ptsfile=pts_file_10, "Number of Participants", "p_test", "2010 cluster PfPR Nigeria")
sum(!is.na(pts_file_10$p_test))
summary(pts_file_10$`Number of Participants`)
summary(pts_file_10$p_test)
# nga_PfPR10_rep <- tmap.fun2(DS_file10, "p_test", "PfPR", "U5 PfPR by LGA (2010)")
tmap_save(tm = nga_PfPR10_rep, filename = "results/para_2010_repDS.micro.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
## creating a combined prevalence map for all years
#row binding cluster points
pts_merge <- rbind(pts_file,pts_file_15, pts_file_10)
summary(!is.na(pts_merge_test$p_test))
summary(pts_merge$`Number of Participants`)
vec <- na.omit(pts_merge$`Number of Participants`)
sd(vec)
#now plot on state shape file
u_clu_map_bindrows <- tmap.clu3(admin1_sf, ptsfile=pts_merge, "Number of Participants", "p_test", "PfPR 2010 - 2018 in Nigeria")
head(pts_merge)
#creates aggreagted map of pfpr for all years using mean values
#calculate mean of points to pfpr estimate over time
pts_merge_test <- pts_merge %>% drop_na(p_test)
pts100 <- st_is_within_distance(pts_merge_test, dist = 2000)
class(pts100)
res <- data.frame(id=1:length(pts100),x=NA, y=NA,mean_pfpr=NA)
res$x <- sapply(pts100, function(p){mean(pts_merge_test$LONGNUM[p])})
res$y <- sapply(pts100, function(p){mean(pts_merge_test$LATNUM[p])})
res$mean_pfpr<- sapply(pts100, function(p) #scaled by the proportion of participants in each nearby cluster
{sum((pts_merge_test$`Number of Participants`[p]/sum(pts_merge_test$`Number of Participants`[p]) * pts_merge_test$p_test[p]))})
res$`Number of Participants` <- sapply(pts100, function(p){mean(pts_merge_test$`Number of Participants`[p])})
res_2_pfpr<- res %>% distinct(x, y, .keep_all = TRUE) %>% rename(num_pfpr = `Number of Participants`)
coordinates(res_2) <- c("x","y")
proj4string(res_2) <- CRS('+proj=longlat +datum=WGS84 +no_defs')
res_sf_pfpr <- st_as_sf(res_2)
head(res_sf_pfpr)
summary(res_sf_pfpr$`Number of Participants`)
sum(!is.na(res_sf$mean_pfpr))
u_clu_map_aggregated <- tmap.clu2(admin1_sf, ptsfile=res_sf, "Number of Participants", "mean_pfpr", "Aggregated PfPR 2010 - 2018 in Nigeria")
all_maps <- tmap_arrange(u_clu_map_10,u_clu_map_15,u_clu_map,u_clu_map_bindrows,u_clu_map_aggregated)
tmap_save(tm = all_maps, filename = "results/urban_cluster/pfpr_diff.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
res_2_ACT <- res_2_ACT %>% rename(num_ACT = `Number of Participants`)
res_2_itn <- res_2_itn %>% rename(num_itn = `Number of Participants`)
res_2_wealth <- res_2_wealth %>% rename(num_wealth = `Number of Participants`)
res_ <- left_join(res_2_itn, res_2_wealth, by=c("x", "y"))
res_n <- left_join(res_, res_2_ACT, by=c("x", "y"))
res_fin <- left_join(res_n, res_2_pfpr, by=c("x", "y"))
write.csv(res_fin, "results/urban_cluster/ranking_df.csv")
summary(res_$mean_rich)
<file_sep>CM <- read.csv("bin/LGA_map_input/HS_by_LGA_v2_mid.csv")
head(CM)
CM$LGA <- gsub("\\/", "-", CM$LGA)
cm_split <- split(CM, CM$year)
LGAshp <- readOGR("data/Nigeria_LGAs_shapefile_191016", layer ="NGA_LGAs", use_iconv=TRUE, encoding= "UTF-8")
LGAshp_sf <- st_as_sf(LGAshp)
LGAshp_sf$LGA <- gsub("\\/", "-", LGAshp_sf$LGA)
LGA_cov <- LGAshp_sf %>% mutate(LGA = ifelse(LGA == "kaita","Kaita", ifelse(LGA == "kiyawa", "Kiyawa", as.character(LGA))))
LGA_cov_2 <- left_join(LGA_cov, cm_split$`2018`, by = "LGA")
head(LGA_cov_2)
summary(LGA_cov_2$U5_coverage)
#map
eighteen <- tm_shape(LGA_cov_2) + #this is the health district shapfile with LLIn info
tm_polygons(col = "U5_coverage", textNA = "No data",
title = "", palette = "seq", breaks=c(0,0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))+
tm_layout(title = "2018 LGA CM", aes.palette = list(seq="RdYlBu"))
CM_maps <-tmap_arrange(ten, thirteen, fifteen, eighteen)
tmap_save(tm = CM_maps, filename = "results/LGA_maps/CM/CM_2010_2018.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
# ITN
ITN <- read.csv('bin/LGA_map_input/projection/ITN_scen2_80.csv')
head(ITN)
ITN_split <- split(ITN, ITN$year)
LGA_cov_2 <- left_join(LGA_cov, ITN_split$`2023`, by = "LGA")
head(LGA_cov_2)
summary(LGA_cov_2$U5_ITN_use)
#map
ten <- tm_shape(LGA_cov_2) + #this is the health district shapfile with LLIn info
tm_polygons(col = "ten_eighteen_ITN_use", textNA = "No data",
title = "", palette = "seq", breaks=c(0,0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))+
tm_layout(title = "2023 ten to eighteen", aes.palette = list(seq="RdYlBu"))
ITN_maps <-tmap_arrange(u5, six, ten, over_eight)
tmap_save(tm = ITN_maps, filename = "results/LGA_maps/ITN/ITN_scen2_2022.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
# SMC
smc <- read.csv('bin/LGA_map_input/projection/smc_scen3_no_PAAR_v3.csv')
head(smc)
summary(smc$year)
smc_split <- split(smc, smc$year)
smc_2020 <- smc_split$`2020`[smc_split$`2020`$round == 4,]
head(smc_2020)
smc_pop <- smc_2020 %>% dplyr::select(LGA)
# population by LGA
ng_pop <- read.csv("bin/nigeria_LGA_pop.csv") %>% dplyr::select(LGA, geopode.pop.0.4)
head(ng_pop)
smc_pop_2 <- anti_join(ng_pop,smc_pop, by="LGA") %>% summarise(sum(geopode.pop.0.4))
summary(is.na(smc_pop_2$geopode.pop.0.4))
LGA_cov_2 <- left_join(LGA_cov, smc_2020, by = "LGA")
head(LGA_cov_2)
summary(LGA_cov_2$coverage_high_access)
#map
twenty_20_high <- tm_shape(LGA_cov_2) + #this is the health district shapfile with LLIn info
tm_polygons(col = "coverage_high_access", textNA = "No data",
title = "", palette = "seq", breaks=c(0,0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))+
tm_layout(title = "2020 SMC high LGA ITN", aes.palette = list(seq="RdYlBu"))
SMC_maps <- tmap_arrange(twenty_20_low,twenty_20_high)
# (twenty_15_low,
# twenty_15_high,twenty_16_low,twenty_16_high)
tmap_save(tm = twenty_20_high, filename = "results/LGA_maps/SMC/SMC_core.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
# scenario 2
scen2 <- read.csv('bin/LGA_map_input/projection/cm_scen3_v3.csv')
head(scen2)
cm_scen2 <- split(scen2, scen2$year)
#data_20 <- cm_scen2$`2020`[cm_scen2$`2025`$round == 12, ]
LGA_cov_2 <- left_join(LGA_cov, cm_scen2$`2022`, by = "LGA")
head(LGA_cov_2)
summary(LGA_cov_2$U5_coverage)
#map
twenty_22<- tm_shape(LGA_cov_2) + #this is the health district shapfile with LLIn info
tm_polygons(col = "severe_cases", textNA = "No data",
title = "", palette = "seq", breaks=c(0,0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))+
tm_layout(title = "scenario 6 2022 severe", aes.palette = list(seq="RdYlBu"))
scne2_maps <- tmap_arrange(twenty_20, twenty_21, twenty_22, twenty_23, twenty_24, twenty_25)
tmap_save(tm = scne2_maps , filename = "results/LGA_maps/CM/severe_CM_scen6-7.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
# scenario 3
scen3 <- read.csv('bin/LGA_map_input/projection/cm_scen2_10_v2.csv')
head(scen3)
scen4 <- read.csv('bin/LGA_map_input/projection/cm_scen2_20_v2.csv')
scen4
scen5 <- read.csv('bin/LGA_map_input/projection/cm_scen2_30_v2.csv')
scen5
scen3$year <- 2020
scen4$year <- 2020
scen5$year <- 2020
LGA_cov_2 <- left_join(LGA_cov, scen5, by = "LGA")
head(LGA_cov_2)
summary(LGA_cov_2$U5_coverage)
#map
cm_scen5 <- tm_shape(LGA_cov_2) + #this is the health district shapfile with LLIn info
tm_polygons(col = "U5_coverage", textNA = "No data",
title = "", palette = "seq", breaks=c(0,0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))+
tm_layout(title = "scenario 5 LGA CM", aes.palette = list(seq="RdYlBu"))
cm_maps <- tmap_arrange(cm_scen3, cm_scen4, cm_scen5)
tmap_save(tm = cm_maps , filename = "results/LGA_maps/CM/CM_scen3-5.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
#scenario 6
scen6 <- read.csv('bin/LGA_map_input/projection/cm_scen3_v3.csv')
head(scen6)
cm_split <- split(scen6, scen6$year)
LGA_cov_2 <- left_join(LGA_cov, cm_split$`2025`, by = "LGA")
head(LGA_cov_2)
#map
scen6_2025 <- tm_shape(LGA_cov_2) + #this is the health district shapfile with LLIn info
tm_polygons(col = "U5_coverage", textNA = "No data",
title = "", palette = "seq", breaks=c(0,0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))+
tm_layout(title = "scenario 6 2025 LGA CM", aes.palette = list(seq="RdYlBu"))
cm_maps <- tmap_arrange(scen6_2020, scen6_2021, scen6_2022,scen6_2023,scen6_2024, scen6_2025)
tmap_save(tm = cm_maps , filename = "results/LGA_maps/CM/CM_scen6_7.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
# parasite prevalence
para_18 <- read.csv("bin/ds_para_prevalence_2018.csv")
head(para_18)
para_18$LGA <- gsub("\\/", "-", para_18$LGA)
LGA_cov_2 <- left_join(LGAshp_sf, para_18, by = "LGA")
head(LGA_cov_2)
summary(LGA_cov_2$p_test)
#map
para_18 <- tm_shape(LGA_cov_2) + #this is the health district shapfile with LLIn info
tm_polygons(col = "p_test", textNA = "No data",
title = "", palette = "seq", breaks=c(0,0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))+
tm_layout(title = "2018", aes.palette = list(seq="-RdYlBu"))
tmap_save(tm = para_18 , filename = "results/LGA_maps/para_prev/2018_pfpr.pdf", width=13, height=13, units ="in", asp=0,
paper ="A4r", useDingbats=FALSE)
<file_sep>itn.scen3<- read.csv('bin/projection/s3_v3/itn.csv')%>% dplyr::rename(LGA = adm2)
head(itn.scen3)
itn.scen3$LGA <- gsub("\\/", "-", itn.scen3$LGA)
in_80_fun <- function(x){ifelse(x < 0.80, 0.80,x)} #function to increase by up to 80%
s1_itn_80 <- read.csv('results/archetype_sim_input/Intervention_files_LGA/ITN/itn_scenario1_v3.csv') %>%
mutate_at(vars(matches("use")), in_80_fun)
head(s1_itn_80)
#final join
kill_block_3 <- read.csv('bin/projection/s3_v3/itn_block_kill.csv') %>%
dplyr::select(-c(X,adm1)) %>%
mutate(adm2 = ifelse(adm2 == "<NAME>oda","Kaura-Namoda", as.character(adm2)))
head(kill_block_3)
colnames(kill_block_3)[1]<- "LGA"
kill_block_3$LGA <- gsub("\\/", "-", kill_block_3$LGA)
colnames(kill_block_3)[4] <- "kill_rate_new"
colnames(kill_block_3)[5] <- "block_initial_new"
s3_itn_80 <- inner_join(s1_itn_80, kill_block_3, by = "LGA")
head(s3_itn_80)
write.csv(s3_itn_80, 'results/archetype_sim_input/Intervention_files_LGA/ITN/v2/ITN_scen3_80.csv')
| 8417fbe562f530abf21a7d96bfef53eaba08784d | [
"R"
]
| 7 | R | MAmbrose-IDM/hbhi-dhs | b75cf10f89f5a204fd5b83e1d4617544fcd1fa3d | 977e54bccf6d55821d0cb67dd89893e577fefd42 |
refs/heads/master | <repo_name>tcrurav/AccederAWebServiceDesdeReact<file_sep>/ProyectoReact/Alumnado/src/Componentes/ListaDeCiclos/ListaDeCiclos.js
import React, { Component } from 'react';
import MostrarCiclos from '../MostrarCiclos/MostrarCiclos';
class ListaDeCiclos extends Component {
constructor(props){
super(props);
this.state = {
ciclos: []
}
}
componentWillMount(){
fetch("http://192.168.1.178:8080/Alumnado/webresources/ciclo")
.then((response) => {
return response.json();
})
.then((ciclos) => {
this.setState({
ciclos: ciclos
});
});
}
render() {
return (
<MostrarCiclos ciclos={this.state.ciclos}/>
);
}
}
export default ListaDeCiclos;
<file_sep>/ProyectoNetbeans/Alumnado/nbproject/private/private.properties
deploy.ant.properties.file=C:\\Users\\Tiburcio\\AppData\\Roaming\\NetBeans\\8.2\\tomcat70.properties
j2ee.server.home=C:/xampp/tomcat
j2ee.server.instance=tomcat70:home=C:\\xampp\\tomcat
javac.debug=true
javadoc.preview=true
selected.browser=default
test.client.project=C:\\Casa\\2-DAM-T-PGV\\RestFul\\PGL-SincronizacionSQLiteMySQL-master\\ProyectoNetbeans\\Alumnado\\Alumnado
user.properties.file=C:\\Users\\Tiburcio\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>/ProyectoReact/Alumnado/src/App.js
import React, { Component } from 'react';
import ListaDeCiclos from './Componentes/ListaDeCiclos/ListaDeCiclos';
class App extends Component {
render() {
return (
<ListaDeCiclos />
);
}
}
export default App;
<file_sep>/ProyectoNetbeans/Alumnado/src/java/org/ieselrincon/convalidaciones/rest/ApplicationConfig.java
/*
* 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 org.ieselrincon.convalidaciones.rest;
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.ResourceConfig;
/**
*
* @author Tiburcio
*/
@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
// final ResourceConfig resourceConfig = new ResourceConfig();
// resourceConfig.register(new CORSFilter());
// final final URI uri = "http://localhost:8080/Alumnado/webresources/ciclo";
// final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(uri, resourceConfig);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(org.ieselrincon.convalidaciones.rest.CicloResource.class);
}
}
<file_sep>/ProyectoNetbeans/Alumnado/src/java/org/ieselrincon/convalidaciones/bd/CicloBD.java
/**
* @author Tiburcio
*
*/
package org.ieselrincon.convalidaciones.bd;
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 org.ieselrincon.convalidaciones.pojos.Ciclo;
public class CicloBD {
static public List<Ciclo> getAllCiclo() throws Exception {
List<Ciclo> registros = new ArrayList<>();
Connection conexion = ConexionBD.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conexion.prepareStatement("SELECT * FROM ciclo ORDER BY nombre ASC, abreviatura ASC");
rs = ps.executeQuery();
while (rs.next()) {
Ciclo registro = new Ciclo();
registro.setPK_ID(rs.getInt("PK_ID"));
registro.setNombre(rs.getString("Nombre"));
registro.setAbreviatura(rs.getString("Abreviatura"));
registros.add(registro);
}
return registros;
} catch (Exception e) {
throw e;
} finally {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(conexion != null) conexion.close();
}
}
static public Ciclo getCiclo(int id) throws SQLException {
Connection conexion = ConexionBD.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conexion.prepareStatement("SELECT * FROM Ciclo WHERE PK_ID = " + id);
rs = ps.executeQuery();
while (rs.next()) {
Ciclo registro = new Ciclo();
registro.setPK_ID(rs.getInt("PK_ID"));
registro.setNombre(rs.getString("Nombre"));
registro.setAbreviatura(rs.getString("Abreviatura"));
return registro;
}
} catch (SQLException e) {
throw e;
} finally {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(conexion != null) conexion.close();
}
return null;
}
static public void addCiclo(Ciclo registro) throws SQLException {
Connection conexion = ConexionBD.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String str;
if (registro.getPK_ID() != -1) {
str = "INSERT INTO Ciclo (PK_ID, Nombre, Abreviatura) VALUES ("
+ registro.getPK_ID() + ",'" + registro.getNombre() + "','" + registro.getAbreviatura()+ "')";
} else {
str = "INSERT INTO Ciclo (Nombre, Abreviatura) VALUES ("
+ "'" + registro.getNombre() + "','" + registro.getAbreviatura()+ "')";
}
ps = conexion.prepareStatement(str);
ps.executeUpdate();
} catch (SQLException e) {
throw e;
} finally {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(conexion != null) conexion.close();
}
}
static public void delCiclo(int id) throws SQLException {
Connection conexion = ConexionBD.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conexion.prepareStatement("DELETE FROM Ciclo WHERE PK_ID = " + id + "");
ps.executeUpdate();
} catch (SQLException e) {
throw e;
} finally {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(conexion != null) conexion.close();
}
}
static public void updateCiclo(Ciclo registro) throws SQLException {
Connection conexion = ConexionBD.getConexion();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String str = "UPDATE Ciclo SET Nombre = '" + registro.getNombre() + "'"
+ ", Abreviatura = '" + registro.getAbreviatura()+ "'"
+ " WHERE PK_ID = " + registro.getPK_ID();
ps = conexion.prepareStatement(str);
ps.executeUpdate();
} catch (SQLException e) {
throw e;
} finally {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(conexion != null) conexion.close();
}
}
}
| 0e9165ea677b7539e101282f1e0d6bfbe2f7b955 | [
"JavaScript",
"Java",
"INI"
]
| 5 | JavaScript | tcrurav/AccederAWebServiceDesdeReact | 7512420c754a839d92e9036ef6d4537aef067eb2 | a3023a29c0c249888c902bdf3394ae15ce7f71c1 |
refs/heads/main | <file_sep>name = input('請輸入名字: ')
print('hi,', name)
height = input('請問你多高: ')
weight = input('請問你多重: ')
print('你的身高', height,' 體重', weight) | 801fa25319f32edc5da9177ff5465e66c308cf97 | [
"Python"
]
| 1 | Python | WayneWNS/hi | 27b0d67fb9850faec19a87a0b31ee82f73778cec | 29c278b63a3ba666b3a5f2de0f4e26f9c627e94c |
refs/heads/master | <file_sep>
package com.example.login.firebase_chat_app.UI;
import android.animation.ValueAnimator;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.support.annotation.DrawableRes;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.example.login.firebase_chat_app.R;
import com.example.login.firebase_chat_app.Utils.POJO.Adapters.FirendsListAdapter;
import com.example.login.firebase_chat_app.Utils.POJO.ApiEndPoint.Users;
import com.example.login.firebase_chat_app.Utils.POJO.MockUser;
import com.example.login.firebase_chat_app.Utils.POJO.RetroUser;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ConversationListActivity extends AppCompatActivity {
private static String USERNAME = "Linda";
private static final String BASEURL = "https://jsonplaceholder.typicode.com/";
private LottieAnimationView animationView;
@BindView(R.id.friends_list_viewer)
RecyclerView recyclerView;
private LinearLayoutManager mLayoutManager;
FirendsListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation_list);
Toolbar toolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
ButterKnife.bind(this);
getSupportActionBar().setTitle(USERNAME);
animationView = findViewById(R.id.loader);
//Display the users
displayUsers();
}
private void displayUsers(){
//get the data from jons server
getJsonDataAndUpdateUI();
}
private void getJsonDataAndUpdateUI() {
//lets get the data
startLoader();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Users service = retrofit.create(Users.class);
//making the call async to the api
Call<List<RetroUser>> repos = service.listUsers();
repos.enqueue(new Callback<List<RetroUser>>() {
@Override
public void onResponse(Call<List<RetroUser>> call, Response<List<RetroUser>> response) {
//Toast.makeText(ConversationListActivity.this, "got the data", Toast.LENGTH_LONG).show();
List<RetroUser> users = response.body();
loadList(users);
hideLoader();
}
@Override
public void onFailure(Call<List<RetroUser>> call, Throwable t) {
Toast.makeText(ConversationListActivity.this, "did not get the data : "+t, Toast.LENGTH_LONG).show();
hideLoader();
}
});
}
private void loadList(List<RetroUser>users) {
//initialize recycler view
recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
adapter=new FirendsListAdapter(this,users);
recyclerView.setAdapter(adapter);
recyclerView.setVisibility(View.VISIBLE);
}
private void hideLoader() {
//hide the loader
if(animationView.isAnimating()){
//stop animation
animationView.cancelAnimation();
}
animationView.setVisibility(View.GONE);
}
private void startLoader() {
//show the loader
animationView.playAnimation();
}
private void liveUsersDisplay(){
}
}
<file_sep>package com.example.login.firebase_chat_app.Utils.POJO.Adapters;
public class MessagesAdapter {
}
<file_sep>package com.example.login.firebase_chat_app.Utils.POJO;
import android.support.annotation.DrawableRes;
import com.example.login.firebase_chat_app.R;
import java.util.List;
public class MockUser {
private String userName;
@DrawableRes
private int userImage;
private List<MockUser> users;
public MockUser(){
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserImage() {
return userImage;
}
public void setUserImage(int userImage) {
this.userImage = userImage;
}
public List<MockUser> getMockUsers(){
//prepaire the 10 mock users
for (int i =0;i<10;i++){
users.add(getUser());
}
return users;
}
private MockUser getUser (){
MockUser user = new MockUser();
user.setUserName("Linda");
user.setUserImage(R.drawable.male_user);
return user;
}
}
| 52c138bdded1a73344e5e3efe2de99b36c1e07c3 | [
"Java"
]
| 3 | Java | sarvinder/Firebase_chat_app | d6d9c3993500545dc82bec45ebd36dd147318400 | 25abf6e77993d90750c80eff66e9085134a4e5f2 |
refs/heads/master | <repo_name>Livenga/p2paint<file_sep>/src/graphic/g_c2csv.c
#include <stdio.h>
#include "../../include/graphic.h"
int save_csv(const char *path,
img _img) {
int i, j;
FILE *csv_fp;
if((csv_fp = fopen(path, "w")) == NULL) {
perror(path);
return EOF;
}
for(i = 0; i < _img.height; i++) {
for(j = 0; j < _img.width; j++) {
fprintf(csv_fp, "%d\t%d\t%d\n",
_img.data[i][j * 3 + 0],
_img.data[i][j * 3 + 1],
_img.data[i][j * 3 + 2]);
}
}
fclose(csv_fp);
return 0;
}
<file_sep>/src/cluster/c_init.c
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
#include "../../include/graphic.h"
#include "../../include/cluster.h"
ushort *dist_alloc(const int width,
const int height) {
ushort *dist;
dist = (ushort *)calloc(width * height, sizeof(ushort));
return dist;
}
/* 分類値の初期化 */
void init_dist(const int k,
const int width,
const int height,
ushort *dist) {
int i, j, position;
for(i = 0; i < height; i++) {
for(j = 0; j < width; j++) {
position = i * width + j;
dist[position] = rand() % k;
}
}
}
/* 分類値の解放 */
void release_dist(const int width,
const int height,
ushort *dist) {
int i, j;
for(i = 0; i < height; i++)
for(j = 0; j < width; j++)
dist[i * width + j] = '\0';
free(dist);
dist = NULL;
}
<file_sep>/src/genetic/gn_crossover.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../../include/cluster.h"
#include "../../include/canvas.h"
#include "../../include/genetic.h"
void
copy_canvas(int label,
const ushort *segment,
canvas cv_in01,
canvas cv_in02,
canvas cv_child01,
canvas cv_child02);
void
gn_crossover(const ushort **segment_data,
int population,
canvas cv_target,
canvas cv_paint,
canvas cv_in01,
canvas cv_in02,
canvas *cv_child) {
const int img_size = cv_in01.width * cv_in01.height * cv_in01.colors;
int i;
int k, label;
int R;
double cross_rate;
for(i = 0; i < population; i += 2) {
k = rand() % 9;
// 交叉
cross_rate = (double)(rand() % 100) / 100.0;
if(cross_rate < CROSSOVER_RAGE) {
label = (k == 0) ? 0 : rand() % k;
copy_canvas(label, (const ushort *)segment_data[k],
cv_in01, cv_in02, cv_child[i], cv_child[i + 1]);
}
else {
memmove((void *)cv_child[i].data, (const void *)cv_in01.data,
sizeof(uchar) * img_size);
memmove((void *)cv_child[i + 1].data, (const void *)cv_in02.data,
sizeof(uchar) * img_size);
}
// 突然変異
R = (rand() % 21) + 20;
//R = (rand() % 11) + 5;
draw_circuit(R / 2, &cv_child[i], cv_paint);
draw_circuit(R / 2, &cv_child[i + 1], cv_paint);
}
}
void
copy_canvas(int label,
const ushort *segment,
canvas cv_in01,
canvas cv_in02,
canvas cv_child01,
canvas cv_child02) {
int i, j;
int position;
for(i = 0; i < cv_in01.height; i++) {
for(j = 0; j < cv_in01.width; j++) {
position = i * cv_in01.width + j;
//printf("%dx%d\n", j, i);
if(segment[position] == label) {
cv_child01.data[position * 3 + 0] = cv_in02.data[position * 3 + 0];
cv_child01.data[position * 3 + 1] = cv_in02.data[position * 3 + 1];
cv_child01.data[position * 3 + 2] = cv_in02.data[position * 3 + 2];
cv_child02.data[position * 3 + 0] = cv_in01.data[position * 3 + 0];
cv_child02.data[position * 3 + 1] = cv_in01.data[position * 3 + 1];
cv_child02.data[position * 3 + 2] = cv_in01.data[position * 3 + 2];
}
else {
cv_child01.data[position * 3 + 0] = cv_in01.data[position * 3 + 0];
cv_child01.data[position * 3 + 1] = cv_in01.data[position * 3 + 1];
cv_child01.data[position * 3 + 2] = cv_in01.data[position * 3 + 2];
cv_child02.data[position * 3 + 0] = cv_in02.data[position * 3 + 0];
cv_child02.data[position * 3 + 1] = cv_in02.data[position * 3 + 1];
cv_child02.data[position * 3 + 2] = cv_in02.data[position * 3 + 2];
}
}
}
}
<file_sep>/src/cl/cl_kernel.c
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
#include "../../include/common.h"
#include "../../include/opencl.h"
cl_int set_kernels(const int did,
cl_prop *prop) {
cl_int status;
prop->context = clCreateContext(0,
prop->num_devices,
(const cl_device_id *)prop->devices,
NULL, NULL, &status);
prop->queue = clCreateCommandQueueWithProperties(
prop->context, prop->devices[did], 0, &status);
prop->program = clCreateProgramWithSource(
prop->context, prop->code.count,
(const char **)prop->code.codes,
NULL, &status);
const char *options = "-I ./include/";
status = clBuildProgram(prop->program, prop->num_devices,
(const cl_device_id *)prop->devices,
options, NULL, NULL);
if(status != CL_SUCCESS)
printf("%s[Build Error Log]%s\n",
ERR_STR, CLR_STR);
else
printf("%s[Build Log]%s\n",
WHT_STR, CLR_STR);
size_t value_size;
char *value;
clGetProgramBuildInfo(prop->program, prop->devices[did],
CL_PROGRAM_BUILD_LOG, 0, NULL, &value_size);
value = (char *)calloc(value_size, sizeof(char));
clGetProgramBuildInfo(prop->program, prop->devices[did],
CL_PROGRAM_BUILD_LOG, value_size, (void *)value, NULL);
printf("%s\n", value);
free(value);
if(status != CL_SUCCESS) getchar();
prop->kernel = clCreateKernel(prop->program,
(const char *)"cluster", &status);
return status;
}
<file_sep>/src/cl/cl_util.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
#include "../../include/opencl.h"
void release_kernel_code(kcode *code) {
int i;
for(i = 0; i < code->count; i++) {
free(code->paths[i]); code->paths[i] = NULL;
free(code->codes[i]); code->codes[i] = NULL;
}
free(code->paths); code->paths = NULL;
free(code->codes); code->codes = NULL;
}
void release_cl_properties(cl_prop *prop) {
clReleaseKernel(prop->kernel);
clReleaseProgram(prop->program);
clReleaseCommandQueue(prop->queue);
clReleaseContext(prop->context);
free(prop->platforms); prop->platforms = NULL;
free(prop->devices); prop->devices = NULL;
release_kernel_code(&prop->code);
}
<file_sep>/src/canvas/cv_draw.c
#include <stdlib.h>
#include "../../include/canvas.h"
void
draw_circuit(int r,
canvas *cv_paint,
canvas cv_target) {
int i, j;
int circ_area, paint_pos, target_pos;
int pt_x0, pt_y0;
int tr_x0, tr_y0;
int paint_x0, paint_y0;
int target_x0, target_y0;
/* Paint Canvas の描画中心点 */
pt_x0 = rand() % cv_paint->width;
pt_y0 = rand() % cv_paint->height;
/* Target Canvas の描画中心点 */
tr_x0 = rand() % cv_target.width;
tr_y0 = rand() % cv_target.height;
for(i = -r; i < r; i++) {
target_y0 = tr_y0 + i;
paint_y0 = pt_y0 + i;
for(j = -r; j < r; j++) {
target_x0 = tr_x0 + j;
paint_x0 = pt_x0 + j;
circ_area = i * i + j * j; // 円領域
paint_pos = paint_y0 * cv_paint->width + paint_x0;
target_pos = target_y0 * cv_target.width + target_x0;
/* Paint, Target Canvas
* 画像内のみ描画 */
if(circ_area <= (r * r) &&
target_x0 > -1 && target_y0 > -1 &&
target_x0 < cv_target.width && target_y0 < cv_target.height &&
paint_x0 > -1 && paint_y0 > -1 &&
paint_x0 < cv_paint->width && paint_y0 < cv_paint->height
) {
cv_paint->data[paint_pos * 3 + 0] =
cv_target.data[target_pos * 3 + 0];
cv_paint->data[paint_pos* 3 + 1] =
cv_target.data[target_pos * 3 + 1];
cv_paint->data[paint_pos * 3 + 2] =
cv_target.data[target_pos * 3 + 2];
}
}
}
}
<file_sep>/src/graphic/g_png.c
#include <stdio.h>
#include <stdlib.h>
#include <png.h>
#include "../../include/graphic.h"
#if defined(GDEBUG)
const char *color_type_str(const size_t type);
#endif
int pnread(const char *path,
img *_img) {
FILE *png_fp;
png_structp png_ptr;
png_infop info_ptr;
if((png_fp = fopen(path, "rb")) == NULL) {
perror(path);
return EOF;
}
png_ptr = png_create_read_struct(
PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
png_init_io(png_ptr, png_fp);
png_read_info(png_ptr, info_ptr);
// 画像情報取得
png_uint_32 width, height;
png_byte color_type, bit_depth;
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
switch(color_type) {
case PNG_COLOR_TYPE_GRAY: _img->colors = 1; break;
case PNG_COLOR_TYPE_GA: _img->colors = 2; break;
case PNG_COLOR_TYPE_RGB: _img->colors = 3; break;
case PNG_COLOR_TYPE_RGBA: _img->colors = 4; break;
}
_img->bit_size = _img->colors * (bit_depth / 8);
_img->width = width;
_img->height = height;
_img->color_type = color_type;
_img->bit_depth = bit_depth;
#if defined(GDEBUG)
printf("PNG Size\t%lux%lu\n", width, height);
printf("PNG Color Type\t%s\n", color_type_str(color_type));
printf("PNG Bit depth\t%d\n", bit_depth);
#endif
int i, j, k;
_img->ldata = (uchar *)calloc(
height * width * _img->bit_size, sizeof(uchar));
_img->data = (uchar **)calloc(
height, sizeof(uchar *));
for(i = 0; i < height; i++)
_img->data[i] = (uchar *)calloc(
width * _img->bit_size, sizeof(uchar));
png_read_image(png_ptr, (png_bytepp)_img->data);
png_read_end(png_ptr, info_ptr);
png_destroy_info_struct(png_ptr, &info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
int img_pos;
for(i = 0; i < height; i++) {
for(j = 0; j < width; j++) {
img_pos = i * width + j;
for(k = 0; k < _img->colors; k++)
_img->ldata[img_pos * 3 + k] = _img->data[i][j * 3 + k];
}
}
fclose(png_fp);
return 0;
}
<file_sep>/src/genetic/gn_main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../../include/opencl.h"
#include "../../include/graphic.h"
#include "../../include/genetic.h"
#include "../../include/canvas.h"
extern void
img2canvas(img _img,
canvas *cv);
/* src/genetic/gn_calc.c */
/* 適応度計算 */
extern double
calc_fitness(canvas input, /* 個体仮想Canvas */
canvas teach /* 目標画像Canvas */);
/* src/genetic/gn_crossover.c */
extern void
gn_crossover(const ushort **segment_data,
int population,
canvas cv_target,
canvas cv_paint,
canvas cv_in01,
canvas cv_in02,
canvas *cv_child);
void
run_genetic(cl_prop prop,
const ushort **segment_data,
img target,
img paint) {
const size_t img_size = target.width * target.height * target.colors;
size_t cnt_generation;
int i, R;
double pr_fitness[POPULATION_SIZE],
ch_fitness[CHILDREN_SIZE];
canvas cv_target, cv_paint;
canvas pr_canvas[POPULATION_SIZE],
ch_canvas[CHILDREN_SIZE];
/* img -> canvas */
img2canvas(target, &cv_target);
img2canvas(paint, &cv_paint);
/* 個体集合の初期化 */
for(i = 0; i < POPULATION_SIZE; i++)
pr_canvas[i] = cvalloc(
target.width,
target.height,
target.colors);
/* 子個体集合領域の確保 */
for(i = 0; i < CHILDREN_SIZE; i++)
ch_canvas[i] = cvalloc(
target.width,
target.height,
target.colors);
char output[1024];
for(i = 0; i < POPULATION_SIZE; i++) {
while(cv_finish_init(pr_canvas[i]) < 0.8) {
R = (rand() % 41) + 40;
//R = (rand() % 21) + 10;
/* 2015/11/05 12:55
* cv_target のサイズを考慮していない
* !!! 修正完了 !!! */
draw_circuit(R / 2, &pr_canvas[i], cv_paint);
}
#if 0
sprintf(output, "imgs/canvas/canvas%03d.png", i);
pnwrite_from_canvas(output, pr_canvas[i]);
#endif
pr_fitness[i] = calc_fitness(
cv_target, pr_canvas[i]);
printf("\033[1m[個体適応度 No.%3d] %f\033[0m\n",
i, pr_fitness[i]);
}
int slt_rand[2];
int slt_best, slt_roul;
char gen_path[1024];
cnt_generation = 0;
do {
// 個体から2つ選択
slt_rand[0] = rand() % POPULATION_SIZE;
slt_rand[1] = rand() % POPULATION_SIZE;
while(slt_rand[0] == slt_rand[1])
slt_rand[1] = rand() % POPULATION_SIZE;
// 交叉
gn_crossover(segment_data, CHILDREN_SIZE,
cv_target, cv_paint,
pr_canvas[slt_rand[0]], pr_canvas[slt_rand[1]], ch_canvas);
// 子個体集合評価
for(i = 0; i < CHILDREN_SIZE; i++) {
ch_fitness[i] =
calc_fitness(cv_target, ch_canvas[i]);
//printf("%f\n", ch_fitness[i]);
}
slt_best =
minof_fitness(CHILDREN_SIZE, ch_fitness);
//slt_roul = rand() % CHILDREN_SIZE;
slt_roul = slt_best;
memmove((void *)pr_canvas[slt_rand[0]].data,
(const void *)ch_canvas[slt_best].data, sizeof(uchar) * img_size);
memmove((void *)pr_canvas[slt_rand[1]].data,
(const void *)ch_canvas[slt_roul].data, sizeof(uchar) * img_size);
if((cnt_generation % 100) == 0) {
printf("No.%5d: %f\n", cnt_generation, ch_fitness[slt_best]);
sprintf(gen_path,"gen/gen%05d.png", cnt_generation);
pnwrite_from_canvas(gen_path, pr_canvas[slt_rand[0]]);
}
} while(++cnt_generation != NUMBER_OF_GENERATION);
printf("[終了世代] %d\n", cnt_generation);
/* Canvas領域の解放(後処理) */
free_canvas(&cv_target);
free_canvas(&cv_paint);
}
<file_sep>/include/genetic.h
#ifndef GENETIC_H
#define GENETIC_H
/* 終了世代 */
#define NUMBER_OF_GENERATION (100000)
/* 個体, 子個体数 */
#define POPULATION_SIZE (20)
#define CHILDREN_SIZE (10)
/* 突然変異, 交叉率 */
#define MUTATION_RATE (1.0)
#define CROSSOVER_RAGE (0.7)
/* パッチ半径 */
#define INIT_PATCH_SIZE (80) /* 初期個体生成 */
#define PATCH_SIZE (40) /* GAパラメータ */
/* src/genetic/gn_calc.c */
extern int
minof_fitness(int population,
double *fitness);
#endif
<file_sep>/src/cl/cl_code.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include "../../include/opencl.h"
int get_kernel_paths(const char *path,
kcode *code) {
int count;
char *p;
DIR *kernel_dir;
struct dirent *kernel_stat;
/* Cファイル数カウント */
kernel_dir = opendir(path);
if(kernel_dir == NULL) {
perror(path);
return EOF;
}
count = 0;
while((kernel_stat = readdir(kernel_dir)) != NULL) {
p = strstr(kernel_stat->d_name, ".c"); // 拡張子が ".c " のみを認識
if(p != NULL)
++count;
}
closedir(kernel_dir);
kernel_dir = NULL;
if(count == 0) return EOF;
/* パスの取得 */
long kernel_len, full_len;
code->count = count;
kernel_dir = opendir(path);
if(kernel_dir == NULL) {
perror(path);
return EOF;
}
count = 0;
code->paths = (unsigned char **)calloc(
count, sizeof(unsigned char *));
kernel_len = strlen(path);
while((kernel_stat = readdir(kernel_dir)) != NULL) {
p = strstr(kernel_stat->d_name, ".c");
if(p != NULL) {
full_len = kernel_len + 1 +
strlen(kernel_stat->d_name);
code->paths[count] = (unsigned char *)calloc(
full_len, sizeof(unsigned char));
sprintf((char *)code->paths[count], "%s/%s",
path, kernel_stat->d_name);
++count;
}
}
closedir(kernel_dir);
kernel_dir = NULL;
return 0;
}
int read_kernel_code(kcode *code) {
int i;
FILE *kernel_fp;
long kernel_len;
code->codes = (unsigned char **)calloc(
code->count, sizeof(unsigned char *));
for(i = 0; i < code->count; i++) {
kernel_fp = fopen((char *)code->paths[i], "r");
if(kernel_fp == NULL) {
perror((char *)code->paths[i]);
return EOF;
}
fseek(kernel_fp, 0L, SEEK_END);
kernel_len = ftell(kernel_fp);
fseek(kernel_fp, 0L, SEEK_SET);
code->codes[i] = (unsigned char *)calloc(
kernel_len, sizeof(unsigned char));
fread((void *)code->codes[i], sizeof(unsigned char),
kernel_len, kernel_fp);
fclose(kernel_fp);
}
return 0;
}
<file_sep>/src/main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "../include/graphic.h"
#include "../include/opencl.h"
#include "../include/cluster.h"
/* src/cluster/c_main.c */
extern ushort *
run_k_means(const int K,
cl_prop prop,
img read_img);
/* src/genetic/gn_main.c */
extern void
run_genetic(cl_prop prop,
const ushort **segment_data,
img target,
img paint);
int main(int argc, char *argv[])
{
const int pid = 1, did = 0;
cl_prop prop;
img read_img, paint_img;
/* 画像分割データ */
ushort **segment_data;
srand((unsigned)time(NULL));
/* 画像ファイル(PNG)の読み込み */
pnread("imgs/img00.png", &read_img);
pnread("imgs/shout.png", &paint_img);
//save_csv("img00.csv", read_img);
/* Kernelコードの読み込み */
get_kernel_paths("src/kernel", &prop.code);
read_kernel_code(&prop.code);
/* OpenCLプロパティ設定 */
numof_platforms(&prop);
get_platforms(&prop);
numof_devices(pid, &prop);
get_devices(pid, &prop);
set_kernels(did, &prop);
/* 画像分割データの取得 */
int i;
segment_data =
(ushort **)calloc(10, sizeof(ushort *));
for(i = 2; i < 11; i++)
segment_data[i - 2] =
run_k_means(i, prop, read_img);
run_genetic(prop, (const ushort **)segment_data,
read_img, paint_img);
/* OpenCLプロパティの解放 */
release_cl_properties(&prop);
release_img(&read_img);
release_img(&paint_img);
/* 分割データ解放 */
for(i = 2; i < 11; i++)
release_dist(
read_img.width,
read_img.height,
segment_data[i - 2]);
return 0;
}
<file_sep>/src/canvas/cv_util.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../../include/graphic.h"
#include "../../include/canvas.h"
void
img2canvas(img _img,
canvas *cv) {
int i;
int img_size = _img.width * _img.height * _img.colors;
cv->width = _img.width;
cv->height = _img.height;
cv->colors = _img.colors;
cv->data = (uchar *)calloc(
img_size,
sizeof(uchar));
memmove((void *)cv->data, (const void *)_img.ldata,
img_size);
}
double cv_finish_init(canvas cv) {
int i, j, k, position;
int sum, count = 0;
for(i = 0; i < cv.height; i++) {
for(j = 0; j < cv.width; j++) {
position = i * cv.width + j;
sum = 0;
for(k = 0; k < cv.colors; k++)
sum += cv.data[position * 3 + k];
if(sum != (0xFF * 3)) ++count;
}
}
return (double)count / (cv.width * cv.height);
}
/* Canvas領域の解放 */
void release_canvas(int population,
canvas *cv) {
int cnt_p;
int i, j, k;
//printf("%p\n", cv);
for(cnt_p = 0; cnt_p < population; cnt_p++) {
for(i = 0; i < cv[cnt_p].height; i++)
for(j = 0; j < cv[cnt_p].width; j++)
for(k = 0; k < cv[cnt_p].colors; k++)
cv[cnt_p].data[(i * cv->width + j) * 3 + k] = '\0';
free(cv[cnt_p].data);
cv[cnt_p].data = NULL;
}
free(cv);
cv = NULL;
}
void free_canvas(canvas *cv) {
int i, j;
for(i = 0; i < cv->height; i++)
for(j = 0; j < cv->width; j++) {
cv->data[(i * cv->width + j) * 3 + 0] = '\0';
cv->data[(i * cv->width + j) * 3 + 1] = '\0';
cv->data[(i * cv->width + j) * 3 + 2] = '\0';
}
free(cv->data);
cv->data = NULL;
}
<file_sep>/src/graphic/g_uitl.c
#include <stdio.h>
#include <stdlib.h>
#include <png.h>
#include "../../include/graphic.h"
void release_img(img *_img) {
int i, j, k;
int img_pos;
for(i = 0; i < _img->height; i++) {
for(j = 0; j < _img->width; j++) {
img_pos = i * _img->width + j;
for(k = 0; k < _img->colors; k++) {
_img->data[i][j * 3 + k] = '\0';
_img->ldata[img_pos * 3 + k] = '\0';
}
}
free(_img->data[i]);
_img->data[i] = NULL;
}
free(_img->data);
_img->data = NULL;
free(_img->ldata);
_img->ldata = NULL;
}
<file_sep>/src/cluster/c_calc.c
#include <stdio.h>
#include <stdlib.h>
#include "../../include/graphic.h"
#include "../../include/opencl.h"
#include "../../include/cluster.h"
/* 所属クラスタの中心地計算 */
void calc_cluster_center(const int k,
const img read_img,
const ushort *dist,
p_cluster *_cluster) {
int i, j, position;
size_t sum_r, sum_g, sum_b, cnt;
sum_r = 0;
sum_g = 0;
sum_b = 0;
cnt = 0;
for(i = 0; i < read_img.height; i++) {
for(j = 0; j < read_img.width; j++) {
position = i * read_img.width + j;
if(k == dist[position]) {
#if 1
sum_r += read_img.data[i][j * 3 + 0];
sum_g += read_img.data[i][j * 3 + 1];
sum_b += read_img.data[i][j * 3 + 2];
#else
sum_r += read_img.ldata[position * 3 + 0];
sum_g += read_img.ldata[position * 3 + 1];
sum_b += read_img.ldata[position * 3 + 2];
#endif
++cnt;
}
}
}
if(cnt != 0) {
_cluster->r = sum_r / cnt;
_cluster->g = sum_g / cnt;
_cluster->b = sum_b / cnt;
}
else {
#if 0
_cluster->r = _cluster->r;
_cluster->g = _cluster->g;
_cluster->b = _cluster->b;
#else
_cluster->r = 0;
_cluster->g = 0;
_cluster->b = 0;
#endif
}
}
int conf_cluster_center(const int k,
p_cluster *_cluster) {
int i, conf = 0;
for(i = 0; i < k - 1; i++) {
conf += _cluster[i].r == _cluster[i + 1].r;
conf += _cluster[i].g == _cluster[i + 1].g;
conf += _cluster[i].b == _cluster[i + 1].b;
}
return ((conf == 0) ? 0 : 1);
}
<file_sep>/src/cluster/c_main.c
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
#include "../../include/graphic.h"
#include "../../include/opencl.h"
#include "../../include/cluster.h"
//#define K 11
#define MAX_RANGE 200
/* src/graphic/g_write.c */
extern int
pnwrite_from_cluster(const char *path,
int width,
int height,
p_cluster *_cluster,
unsigned short *dist);
void set_image_info(img _img, img_info *info);
ushort *run_k_means(const int K,
cl_prop prop,
img read_img) {
const size_t img_size = read_img.width * read_img.height;
int num_k = K, k;
cl_int status; // エラー状態
size_t global_size[2]; // 並列次元数
img_info info; // 画像情報
cluster_args cl_cls_arg; // Kernel引数
ushort *k2; // 分類
p_cluster cls_k2[K]; // クラスタ
set_image_info(read_img, &info);
k2 = dist_alloc(read_img.width, read_img.height);
do {
init_dist(K, read_img.width, read_img.height, k2);
for(k = 0; k < K; k++)
calc_cluster_center(k, read_img, (const ushort *)k2, &cls_k2[k]);
} while(conf_cluster_center(K, cls_k2) == 0);
/* ++++ OpenCL Kernel関数の引数設定 ++++ */
cl_cls_arg.k = clCreateBuffer(prop.context,
CL_READ_COPY, sizeof(int), (void *)&num_k, &status);
cl_cls_arg.img_info = clCreateBuffer(prop.context,
CL_READ_COPY, sizeof(img_info), (void *)&info, NULL);
cl_cls_arg.cls_center = clCreateBuffer(prop.context,
CL_MEM_READ_ONLY, sizeof(p_cluster) * K, (void *)NULL, NULL);
cl_cls_arg.dist = clCreateBuffer(prop.context,
CL_MEM_READ_WRITE, sizeof(ushort) * img_size, (void *)NULL, &status);
cl_cls_arg.data = clCreateBuffer(prop.context,
CL_READ_COPY, sizeof(uchar) * img_size * 3, (void *)read_img.ldata, NULL);
clSetKernelArg(prop.kernel, 0, sizeof(cl_mem), &cl_cls_arg.k);
clSetKernelArg(prop.kernel, 1, sizeof(cl_mem), &cl_cls_arg.img_info);
clSetKernelArg(prop.kernel, 2, sizeof(cl_mem), &cl_cls_arg.cls_center);
clSetKernelArg(prop.kernel, 3, sizeof(cl_mem), &cl_cls_arg.dist);
clSetKernelArg(prop.kernel, 4, sizeof(cl_mem), &cl_cls_arg.data);
/* 次元数指定 */
global_size[0] = read_img.width;
global_size[1] = read_img.height;
/* ++++ OpenCL ++++ */
/* 終了条件を回数でなく, クラスタの更新停止も追加(ゆくゆくは) */
int count = 0;
do {
status = clEnqueueWriteBuffer(prop.queue, cl_cls_arg.cls_center,
CL_TRUE, 0, sizeof(p_cluster) * K, (const void *)cls_k2, 0, NULL, NULL);
status = clEnqueueWriteBuffer(prop.queue, cl_cls_arg.dist, CL_TRUE,
0, sizeof(ushort) * img_size, (const void *)k2, 0, NULL, NULL);
clEnqueueNDRangeKernel(prop.queue, prop.kernel, 2,
NULL, global_size, NULL, 0, NULL, NULL);
status = clEnqueueReadBuffer(prop.queue,
cl_cls_arg.dist, CL_TRUE, 0, sizeof(ushort) * img_size,
(void *)k2, 0, NULL, NULL);
for(k = 0; k < K; k++) // 中心値の再計算
calc_cluster_center(k, read_img, (const ushort *)k2, &cls_k2[k]);
} while(++count != MAX_RANGE);
printf("\033[1mSegmentation data No.%2d\033[0m\n", K);
cluster_print(K, cls_k2);
putchar('\n');
#ifdef SAVE_CLUSTER_IMAGE
char image_path[1024];
for(k = 0; k < K; k++) {
sprintf(image_path, "imgs/k_out/k%02d_%03d.png", K, k);
pnwrite_from_dist(image_path, read_img.width, read_img.height, k,
k2, read_img.data);
}
sprintf(image_path, "imgs/cluster/cluster_k_%02d.png", K);
pnwrite_from_cluster(image_path, read_img.width, read_img.height,
cls_k2, k2);
#endif
clReleaseMemObject(cl_cls_arg.k);
clReleaseMemObject(cl_cls_arg.img_info);
clReleaseMemObject(cl_cls_arg.cls_center);
clReleaseMemObject(cl_cls_arg.dist);
clReleaseMemObject(cl_cls_arg.data);
//release_dist(read_img.width, read_img.height, k2);
return k2;
}
void set_image_info(img _img, img_info *info) {
info->width = _img.width;
info->height = _img.height;
info->colors = _img.colors;
}
<file_sep>/include/cluster.h
#ifndef CLUSTER_H
#define CLUSTER_H
typedef struct _image_info {
size_t width, height, colors;
} img_info;
typedef struct _cluster {
size_t r, g, b;
} p_cluster;
#ifndef F_KERNEL
/* ..Common Function.. */
#ifndef GRAPHIC_H
#include "graphic.h"
#endif
// クラスタリング後の画像保存
//#define SAVE_CLUSTER_IMAGE
typedef unsigned short ushort;
/* src/cluster/c_init.c */
extern ushort // 分類領域の確保
*dist_alloc(const int width,
const int height);
extern void // 分類の初期化
init_dist(const int k,
const int width,
const int height,
ushort *dist);
extern void // 分類の解放
release_dist(const int width,
const int height,
ushort *dist);
/* src/cluster/c_calc.c */
extern void // 中心値の計算
calc_cluster_center(const int k,
const img read_img,
const ushort *dist,
p_cluster *_cluster);
extern int // 中心位置の確認
conf_cluster_center(const int k,
p_cluster *_cluster);
/* src/cluster/c_print.c */
extern void // クラスタ値の表示
cluster_print(const int k,
const p_cluster *_cluster);
extern void
class_print(int width,
int height,
ushort *dist);
#else // Kernel Function
/* ..OpenCL用.. */
typedef unsigned char unchar;
double
minof_arg(int count,
double *euclid_distance);
double
calc_euclid_distance(int position,
p_cluster cls_center,
unchar *data);
#endif // F_KERNEL
#endif
<file_sep>/include/common.h
#ifndef COMMON_H
#define COMMON_H
#define WHT_STR "\033[1m\033[39m"
#define ERR_STR "\033[1m\033[5m\033[32m"
#define CLR_STR "\033[0m\033[39m"
#endif
<file_sep>/include/opencl.h
#ifndef CL_PROPERTIES
#define CL_PROPERTIES
#ifndef __OPENCL_CL_H
#include <CL/cl.h>
#endif
#define CL_READ_COPY (CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR)
#define CL_RW_COPY (CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR)
typedef struct _kerenl_code {
size_t count;
unsigned char **paths;
unsigned char **codes;
} kcode;
typedef struct _cl_prop {
/* Kernel Code */
kcode code;
/* Platform */
cl_uint num_platforms;
cl_platform_id *platforms;
/* Device */
cl_uint num_devices;
cl_device_id *devices;
cl_context context;
cl_command_queue queue;
cl_program program;
cl_kernel kernel;
} cl_prop;
/* k-means法 算出に使用 */
typedef struct _cluster_args {
cl_mem k;
cl_mem img_info;
cl_mem cls_center;
cl_mem dist;
cl_mem data;
} cluster_args;
/* src/cl/cl_plat_dev.c */
extern cl_int numof_platforms(cl_prop *prop);
extern cl_int get_platforms(cl_prop *prop);
extern cl_int
numof_devices(const int pid,
cl_prop *prop);
extern cl_int
get_devices(const int pid,
cl_prop *prop);
/* src/cl/cl_kernel.c */
extern cl_int
set_kernels(const int did,
cl_prop *prop);
/* src/cl/cl_code.c */
extern int // カーネルコードのパス取得
get_kernel_paths(const char *path,
kcode *code);
extern int // カーネルコードの読み込み
read_kernel_code(kcode *code);
/* src/cl/cl_util.c */
extern void release_cl_properties(cl_prop *prop);
#endif
<file_sep>/src/graphic/g_write.c
#include <stdio.h>
#include <stdlib.h>
#include <png.h>
#include "../../include/graphic.h"
#include "../../include/cluster.h"
#include "../../include/canvas.h"
int pnwrite_from_dist(const char *path,
int width,
int height,
int k,
unsigned short *dist,
uchar **data) {
int i, j;
int position; // distance position
FILE *png_fp;
png_structp png_ptr;
png_infop info_ptr;
uchar **img_data;
if((png_fp = fopen(path, "wb")) == NULL) {
perror(path);
return EOF;
}
png_ptr = png_create_write_struct(
PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
png_init_io(png_ptr, png_fp);
png_set_IHDR(png_ptr, info_ptr,
width, height, 8, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
PNG_FILTER_TYPE_BASE);
img_data = (uchar **)calloc(height, sizeof(uchar *));
for(i = 0; i < height; i++) {
img_data[i] = (uchar *)calloc(width * 3, sizeof(uchar));
for(j = 0; j < width; j++) {
position = i * width + j;
if(dist[position] == k) {
img_data[i][j * 3 + 0] = data[i][j * 3 + 0];
img_data[i][j * 3 + 1] = data[i][j * 3 + 1];
img_data[i][j * 3 + 2] = data[i][j * 3 + 2];
}
else {
img_data[i][j * 3 + 0] = 0x0;
img_data[i][j * 3 + 1] = 0x0;
img_data[i][j * 3 + 2] = 0x0;
}
}
}
png_write_info(png_ptr, info_ptr);
png_write_image(png_ptr, (png_bytepp)img_data);
png_write_end(png_ptr, info_ptr);
png_destroy_info_struct(png_ptr, &info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(png_fp);
for(i = 0; i < height; i++) {
for(j = 0; j < width; j++) {
img_data[i][j * 3 + 0] = '\0';
img_data[i][j * 3 + 1] = '\0';
img_data[i][j * 3 + 2] = '\0';
}
free(img_data[i]);
img_data[i] = NULL;
}
free(img_data);
img_data = NULL;
return 0;
}
int pnwrite_from_cluster(const char *path,
int width,
int height,
p_cluster *_cluster,
unsigned short *dist) {
int i, j;
int position; // distance position
FILE *png_fp;
png_structp png_ptr;
png_infop info_ptr;
uchar **img_data;
if((png_fp = fopen(path, "wb")) == NULL) {
perror(path);
return EOF;
}
png_ptr = png_create_write_struct(
PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
png_init_io(png_ptr, png_fp);
png_set_IHDR(png_ptr, info_ptr,
width, height, 8, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
PNG_FILTER_TYPE_BASE);
img_data = (uchar **)calloc(height, sizeof(uchar *));
for(i = 0; i < height; i++) {
img_data[i] = (uchar *)calloc(width * 3, sizeof(uchar));
for(j = 0; j < width; j++) {
position = i * width + j;
img_data[i][j * 3 + 0] = _cluster[dist[position]].r;
img_data[i][j * 3 + 1] = _cluster[dist[position]].g;
img_data[i][j * 3 + 2] = _cluster[dist[position]].b;
}
}
png_write_info(png_ptr, info_ptr);
png_write_image(png_ptr, (png_bytepp)img_data);
png_write_end(png_ptr, info_ptr);
png_destroy_info_struct(png_ptr, &info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(png_fp);
for(i = 0; i < height; i++) {
for(j = 0; j < width; j++) {
img_data[i][j * 3 + 0] = '\0';
img_data[i][j * 3 + 1] = '\0';
img_data[i][j * 3 + 2] = '\0';
}
free(img_data[i]);
img_data[i] = NULL;
}
free(img_data);
img_data = NULL;
return 0;
}
int pnwrite_from_canvas(const char *path,
canvas cv) {
int i, j;
int position; // distance position
FILE *png_fp;
png_structp png_ptr;
png_infop info_ptr;
uchar **img_data;
if((png_fp = fopen(path, "wb")) == NULL) {
perror(path);
return EOF;
}
png_ptr = png_create_write_struct(
PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
png_init_io(png_ptr, png_fp);
png_set_IHDR(png_ptr, info_ptr,
cv.width, cv.height, 8, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
PNG_FILTER_TYPE_BASE);
img_data = (uchar **)calloc(cv.height, sizeof(uchar *));
for(i = 0; i < cv.height; i++) {
img_data[i] = (uchar *)calloc(cv.width * 3, sizeof(uchar));
for(j = 0; j < cv.width; j++) {
position = i * cv.width + j;
img_data[i][j * 3 + 0] = cv.data[position * 3 + 0];
img_data[i][j * 3 + 1] = cv.data[position * 3 + 1];
img_data[i][j * 3 + 2] = cv.data[position * 3 + 2];
}
}
png_write_info(png_ptr, info_ptr);
png_write_image(png_ptr, (png_bytepp)img_data);
png_write_end(png_ptr, info_ptr);
png_destroy_info_struct(png_ptr, &info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(png_fp);
for(i = 0; i < cv.height; i++) {
for(j = 0; j < cv.width; j++) {
img_data[i][j * 3 + 0] = '\0';
img_data[i][j * 3 + 1] = '\0';
img_data[i][j * 3 + 2] = '\0';
}
free(img_data[i]);
img_data[i] = NULL;
}
free(img_data);
img_data = NULL;
return 0;
}
<file_sep>/include/graphic.h
#ifndef GRAPHIC_H
#define GRAPHIC_H
#define GDEBUG
#ifndef CANVAS_H
typedef unsigned char uchar;
#endif
typedef struct _img {
size_t color_type;
size_t colors;
size_t bit_depth;
size_t bit_size;
size_t width, height;
uchar *ldata;
uchar **data;
} img;
/* src/graphic/g_png.c */
extern int // PNG読み込み
pnread(const char *path,
img *_img);
/* src/graphic/g_write.c */
extern int
pnwrite_from_dist(const char *path,
int width,
int height,
int k,
unsigned short *dist,
uchar **data);
/* src/graphic/g_util.c */
extern void // 構造体img の解放
release_img(img *_img);
/* src/graphic/g_c2csv.c */
extern int // 画像データをcsvに変換
save_csv(const char *path,
img _img);
#endif
<file_sep>/src/graphic/g_debug.c
#include <stdio.h>
#include <stdlib.h>
#include <png.h>
#include "../../include/graphic.h"
#if defined(GDEBUG)
const char *color_type_str(const size_t type) {
const char *msg;
switch(type) {
case PNG_COLOR_TYPE_GRAY: msg = "Grayscale"; break;
case PNG_COLOR_TYPE_GA: msg = "Grayscale(Alpha)"; break;
case PNG_COLOR_TYPE_RGB: msg = "Color(RGB)"; break;
case PNG_COLOR_TYPE_RGBA: msg = "Color(RGBA)"; break;
default: msg = "Otherwise"; break;
}
return msg;
}
#endif
<file_sep>/src/canvas/cv_init.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../../include/opencl.h"
#include "../../include/graphic.h"
#include "../../include/genetic.h"
#include "../../include/canvas.h"
/* Canvas領域の割当 */
canvas cvalloc(int width,
int height,
int colors) {
int i;
canvas cv;
cv.width = width;
cv.height = height;
cv.colors = colors;
cv.data = (uchar *)calloc(
width * height * colors,
sizeof(uchar));
memset((void *)cv.data, 0xFF,
width * height * colors * sizeof(uchar));
return cv;
}
<file_sep>/include/canvas.h
#ifndef CANVAS_H
#define CANVAS_H
#ifndef GRAPHIC_H
typedef unsigned char uchar;
#endif
typedef struct _canvas {
size_t width, height, colors;
uchar *data;
} canvas;
/* src/canvas/cv_init.c */
extern canvas
cvalloc(int width, /* 横幅 */
int height, /* 縦幅 */
int colors /* 色サイズ */);
/* src/canvas/cv_draw.c */
// *cv_paintにcv_targetより円を描画
extern void
draw_circuit(int r, /* 円半径 */
canvas *cv_paint, /* Paint Canvas */
canvas cv_target /* Target Canvas */);
/* src/canvas/cv_util.c */
extern double
cv_finish_init(canvas cv);
extern void
release_canvas(int population,
canvas *cv);
extern void
free_canvas(canvas *cv);
extern int
pnwrite_from_canvas(const char *path,
canvas cv);
#endif
<file_sep>/src/cluster/c_print.c
#include <stdio.h>
#include <stdlib.h>
#include "../../include/cluster.h"
void cluster_print(const int k,
const p_cluster *_cluster) {
int i;
for(i = 0; i < k; i++) {
printf("Cluster No.%2d\n", i);
printf("[R:G:B]\t[%3lu:%3lu:%3lu]\n",
_cluster[i].r, _cluster[i].g, _cluster[i].b);
}
}
void class_print(int width,
int height,
ushort *dist) {
int i, j;
for(i = 0; i < height; i++)
for(j = 0; j < width; j++)
printf("%d ", dist[i * width + j]);
}
<file_sep>/src/kernel/cluster.c
#define F_KERNEL
#include <cluster.h>
__kernel void cluster(
__global int *k,
__global img_info *info,
__global p_cluster *cls_center,
__global ushort *dist,
__global unsigned char *data
) {
const int num_k = *k;
const int x = get_global_id(0), y = get_global_id(1);
const int img_position = y * info->width + x;
const unsigned char *img_data = (unsigned char *)data;
int i, min_arg;
double euclid_distance[256];
for(i = 0; i < num_k; i++) {
euclid_distance[i] = calc_euclid_distance(
img_position, cls_center[i], (unsigned char *)data
);
}
min_arg = minof_arg(num_k, euclid_distance);
dist[img_position] = min_arg;
}
<file_sep>/src/genetic/gn_calc.c
#include <stdio.h>
#include <math.h>
#include "../../include/canvas.h"
double
calc_fitness(canvas input, /* 個体仮想Canvas */
canvas teach /* 目標画像Canvas */) {
int i, j, k;
int position;
double diff, sum_diff, sumof;
sumof = 0.0;
for(i = 0; i < input.height; i++) {
for(j = 0; j < input.width; j++) {
position = i * input.width + j;
sum_diff = 0.0;
for(k = 0; k < input.colors; k++) {
diff = (double)input.data[position * 3 + k] - teach.data[position * 3 + k];
sum_diff += diff * diff;
}
sumof += sqrt(sum_diff);
}
}
return sumof;
}
int
minof_fitness(int population,
double *fitness) {
int i, arg = 0;
double minof = fitness[0];
for(i = 1; i < population; i++) {
if(minof > fitness[i]) {
minof = fitness[i];
arg = i;
}
}
return arg;
}
<file_sep>/src/cl/cl_plat_dev.c
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
#include "../../include/opencl.h"
cl_int numof_platforms(cl_prop *prop) {
return clGetPlatformIDs(0, NULL, &prop->num_platforms);
}
cl_int get_platforms(cl_prop *prop) {
prop->platforms = (cl_platform_id *)calloc(
prop->num_platforms, sizeof(cl_platform_id));
return clGetPlatformIDs(prop->num_platforms, prop->platforms, NULL);
}
cl_int numof_devices(const int pid,
cl_prop *prop) {
return clGetDeviceIDs(prop->platforms[pid],
CL_DEVICE_TYPE_ALL,
0,
NULL,
&prop->num_devices);
}
cl_int get_devices(const int pid,
cl_prop *prop) {
prop->devices = (cl_device_id *)calloc(
prop->num_devices, sizeof(cl_device_id));
return clGetDeviceIDs(prop->platforms[pid],
CL_DEVICE_TYPE_ALL,
prop->num_devices,
prop->devices,
NULL);
}
<file_sep>/src/kernel/euclid.c
#define F_KERNEL
#include <cluster.h>
double
calc_euclid_distance(int position,
p_cluster cls_center,
unchar *data) {
int i;
double diff[3] = {0.0}, euclid = 0.0;
diff[0] = (double)data[position * 3 + 0] - cls_center.r;
diff[1] = (double)data[position * 3 + 1] - cls_center.g;
diff[2] = (double)data[position * 3 + 2] - cls_center.b;
for(i = 0; i < 3; i++)
euclid += (diff[i] * diff[i]);
return euclid;
}
double
minof_arg(int count,
double *euclid_distance) {
int i, arg = 0;
double minof = euclid_distance[0];
for(i = 1; i < count; i++) {
if(minof > euclid_distance[i]) {
minof = euclid_distance[i];
arg = i;
}
}
return arg;
}
| e80fa04f53e4a7b320f42d4258b71a0f2324657e | [
"C"
]
| 28 | C | Livenga/p2paint | cf2aa0b4e0f847e093be26a66eb709a0c4af9c53 | 42398cafcdb45094932d1cff1f6fa54070172286 |
refs/heads/master | <repo_name>alexander-schranz/dotfiles<file_sep>/README.md
# Alex's dotfiles
These are my personal dotfiles for my development machine, which I keep here maily as a backup.
<file_sep>/php/php.ini
error_reporting = E_ALL
memory_limit = -1
upload_max_filesize = 510M
post_max_size = 512M
realpath_cache_size=4096K
realpath_cache_ttl=600
;error_reporting = E_ALL
;display_errors = on
;display_startup_errors = on
session.gc_divisor = 1000
session.gc_maxlifetime = 3600 ; in seconds (increased to 1h (3600s))
[Date]
date.timezone = Europe/Vienna
;date.default_latitude = 47.41427
;date.default_longitude = 9.74195
;date.sunset_zenit = 90.583333
[opcache]
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=32000
[xdebug]
xdebug.default_enable=off
xdebug.remote_enable=on
xdebug.remote_autostart=off
xdebug.file_link_format = "phpstorm://open?file=%f&line=%l"
xdebug.remote_port=9000
xdebug.remote_host=localhost
xdebug.max_nesting_level = 4096
xdebug.var_display_max_depth = 128
xdebug.var_display_max_data = 2048
xdebug.profiler_enable_trigger=1
xdebug.profiler_output_name=xdebug-profile-cachegrind.out-%H-%R
<file_sep>/php/php8.ini
memory_limit = -1
upload_max_filesize = 510M
post_max_size = 512M
realpath_cache_size=4096K
realpath_cache_ttl=600
;error_reporting = E_ALL
;display_errors = on
;display_startup_errors = on
[Date]
date.timezone = Europe/Vienna
;date.default_latitude = 47.41427
;date.default_longitude = 9.74195
;date.sunset_zenit = 90.583333
[opcache]
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
[xdebug]
xdebug.mode=debug
xdebug.file_link_format = "phpstorm://open?file=%f&line=%l"
xdebug.client_port=9000
xdebug.client_host=localhost
xdebug.max_nesting_level = 4096
xdebug.var_display_max_depth = 128
xdebug.var_display_max_data = 2048
<file_sep>/fish/conf.d/git_recent_branches.sh
#!/usr/local/bin/bash
# from https://stackoverflow.com/questions/2514172/listing-each-branch-and-its-last-revisions-date-in-git
for k in `git branch | sed s/^..//`; do echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k --`\\t"$k";done | sort -r | head -n 10
| 1a381a22ab140b5b49a406c7ed75a25ac9a2f0b7 | [
"Markdown",
"Shell",
"INI"
]
| 4 | Markdown | alexander-schranz/dotfiles | 41493950ea581a3a3e1c4110f9d022805c3e3404 | 735e6a405a5bc6c5a07037cc94dd4a14e41fffd3 |
refs/heads/master | <file_sep>#include<stdio.h>
#include<string.h>
char* encryption(char message[],int n)
{
//printf("FUNCTION IS WORKING\n");
char result[1000];
int i,length;
length = strlen(message);
for(i=0; i<length; i++)
{
if(message[i]>=32 && message[i]<=96 && message[i]>=123 && message[i]<=127){
result[i] = (message[i]+n -65) % 26 + 65;
}else if(message[i]>=97 && message[i]<=122)
{
result[i] = (message[i]+n -97)%26 + 97;
}else{
result[i] = message[i];
}
}
return result;
}
char* decryption(char message[],int n)
{
//printf("FUNCTION IS WORKING\n");
char result[1000];
int i,length;
length = strlen(message);
for(i=0; i<length; i++)
{
if(message[i]>=65 && message[i]<=90){
result[i] = (message[i]-n - 90)%26 + 90;
}else if(message[i]>=97 && message[i]<=122)
{
result[i] = (message[i]-n - 122)%26 + 122;
}else{
result[i] = message[i];
}
}
return result;
}
int main()
{
char message[1000];
int n,d;
printf("SELECT FROM THE FOLLOWING OPERATIONS:\n1.ENCRYPTION \n2.DECRYPTION\n");
scanf("%d",&d);
if(d == 1)
{
printf("ENTER THE MESSAGE YOU WANT TO ENCRYPT\n");
scanf(" %[^\n]",message);
printf("ENTER THE KEY:\n");
scanf("%d", &n);
printf("ENCRYPTED MESSAGE:\n");
printf("%s\n",encryption(message,n));
}
else if(d == 2)
{
printf("ENTER THE MESSAGE YOU WANT TO DECRYPT\n");
scanf(" %[^\n]",message);
printf("ENTER THE KEY:\n");
scanf("%d", &n);
printf("\nDECRYPTED MESSAEGE:\n");
printf("%s\n",decryption(message,n));
}
return 0;
}
| abeea358e21c1bc07aa6f1e2e612dc61baab8209 | [
"C"
]
| 1 | C | University-Of-Rajshahi/Cryptographi-Lab-2014-15 | 45f62f5b6af748799ddebafc9c016ae97617e04d | c15f60d96a084340d2a036714e3cfd6d22005794 |
refs/heads/master | <repo_name>kylecrawshaw/ImagrAdmin<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/BaseComponent.swift
//
// BaseComponent.swift
// ImagrManager
//
// Created by <NAME> on 7/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
public class BaseComponent {
var type: String!
var id: Int!
var workflowName: String!
var workflowId: Int!
var componentViewController: NSViewController?
var componentWindowController: NSWindowController?
var componentWindow: NSWindow?
init(id: Int!, type: String!, workflowName: String!, workflowId: Int!) {
self.id = id
self.type = type
self.workflowName = workflowName
self.workflowId = workflowId
}
func asDict() -> NSDictionary? {return nil}
func displayComponentPanel(window: NSWindow!) {
if componentWindowController == nil {
componentWindow = NSWindow(contentViewController: componentViewController!)
componentWindow!.title = "Edit component"
componentWindowController = NSWindowController(window: componentWindow)
buildComponentPanel()
}
componentViewController!.identifier = "\(workflowId)-\(id)"
window.beginSheet(componentWindow!, completionHandler: nil)
componentWindow!.makeKeyAndOrderFront(self)
componentWindowController!.showWindow(self)
}
func closeComponentPanel() {
let workflow = ImagrConfigManager.sharedManager.getWorkflow(workflowName)
if workflow != nil {
NSLog("Closing component panel for \(type)-\(id) in \(workflowName)")
if workflow!.workflowWindow!.sheets.count > 0 {
workflow!.workflowWindow!.endSheet(workflow!.workflowWindow!.sheets[0])
}
} else {
NSLog("Missing workflow object for \(workflowName). Unable to close panel")
}
}
func buildComponentPanel() {}
func notifyUpdateTable() {
NSLog("Notifying window for workflow with ID:\(workflowId!).")
NSNotificationCenter.defaultCenter().postNotificationName("UpdateTableView-\(workflowId!)", object: nil)
}
}<file_sep>/ImagrAdmin/MainViewController.swift
//
// MainViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/9/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
import Carbon
let tempDir = NSTemporaryDirectory() as String
class MainViewController: NSViewController, NSWindowDelegate {
// Main view objects
@IBOutlet weak var mainWindow: NSWindow!
@IBOutlet weak var mainView: NSView!
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var backgroundImageField: NSTextField!
@IBOutlet weak var passwordField: NSTextField!
@IBOutlet weak var changePasswordButton: NSButton!
@IBOutlet weak var autorunDropdown: NSPopUpButton!
@IBOutlet weak var defaultDropdown: NSPopUpButton!
// Validation view objects
@IBOutlet weak var validateView: NSView!
@IBOutlet var validateTextField: NSTextView!
@IBOutlet weak var validateSpinner: NSProgressIndicator!
@IBOutlet weak var validateOkButton: NSButton!
@IBOutlet weak var skipValidateButton: NSButton!
// Welcome view objects
@IBOutlet weak var welcomeView: NSView!
let openPanel: NSOpenPanel = NSOpenPanel()
let savePanel: NSSavePanel = NSSavePanel()
private var task: NSTask?
private var selectedConfigPath: String!
override func viewDidAppear() {
super.viewDidAppear()
// Setup observer to get notified to update the tableView.
// This will occur when content from a workflow window is updated
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateView(_:)), name:"UpdateWorkflowTableView", object: nil)
// Display the welcomeView the the ImagrConfigManager singleton
// has not been configured
if !ImagrConfigManager.sharedManager.hasLoaded {
mainWindow.contentView = welcomeView
}
}
// remove observers when the view isn't visible
override func viewDidDisappear() {
super.viewDidDisappear()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
mainWindow.delegate = self
tableView.setDelegate(self)
tableView.setDataSource(self)
tableView.target = self
let registeredTypes: [String] = [NSStringPboardType]
tableView.registerForDraggedTypes(registeredTypes)
}
@IBAction func quitApp(sender: AnyObject) {
NSApplication.sharedApplication().terminate(self)
}
@IBAction func createNewConfig(sender: AnyObject) {
ImagrConfigManager.sharedManager.loadConfig()
updateView(self)
mainWindow.contentView = mainView
}
@IBAction func displayOpenPanel(sender: AnyObject) {
openPanel.message = "Locate Imagr Config. Must be a .plist"
openPanel.allowsMultipleSelection = false
openPanel.allowedFileTypes = ["plist"]
openPanel.beginSheetModalForWindow(mainWindow, completionHandler: openPanelDidClose)
}
func openPanelDidClose(response: NSModalResponse) {
if response == 1 {
selectedConfigPath = openPanel.URL!.path!
NSLog("User selected path \(selectedConfigPath)")
// Check if the path selected is a directory or
var isDir: ObjCBool = false
NSFileManager.defaultManager().fileExistsAtPath(openPanel.URL!.path!, isDirectory: &isDir)
if NSFileManager.defaultManager().fileExistsAtPath(selectedConfigPath) {
NSLog("Need to validate \(selectedConfigPath)")
displayValidateView(selectedConfigPath)
}
ImagrConfigManager.sharedManager.loadConfig(selectedConfigPath)
setupView()
}
}
@IBAction func saveAll(sender: AnyObject) {
var visibleWindows: Bool = false
for workflow in ImagrConfigManager.sharedManager.workflows {
if workflow.workflowWindow?.visible == true {
visibleWindows = true
break
}
}
if visibleWindows {
let a = NSAlert()
a.messageText = "All workflow windows must be closed before saving"
mainWindow.makeKeyAndOrderFront(self)
a.beginSheetModalForWindow(mainWindow, completionHandler: nil)
} else {
saveConfig()
}
}
@IBAction func removeWorkflow(sender: AnyObject) {
if tableView.selectedRow >= 0 {
ImagrConfigManager.sharedManager.workflows.removeAtIndex(tableView.selectedRow)
updateView(self)
}
}
func setupView() {
if ImagrConfigManager.sharedManager.hasLoaded == false {
NSLog("Unable to load config view. ImagrConfigManager.sharedManager has not been initialized")
return
}
if ImagrConfigManager.sharedManager.password == nil {
passwordField.placeholderString = nil
passwordField.enabled = true
changePasswordButton.hidden = true
} else {
passwordField.placeholderString = "Hashed password is already set"
passwordField.enabled = false
changePasswordButton.hidden = false
}
let bgImage = ImagrConfigManager.sharedManager.backgroundImage
if bgImage != nil {
backgroundImageField.stringValue = bgImage!
} else {
backgroundImageField.stringValue = ""
}
updateView(nil)
}
func updateView(sender: AnyObject?) {
NSLog("Updating config view")
if ImagrConfigManager.sharedManager.hasLoaded == false {
NSLog("Unable to load config view. ImagrConfigManager.sharedManager has not been initialized")
return
}
let workflowTitles = ImagrConfigManager.sharedManager.workflowTitles()
let autorunWorkflow = ImagrConfigManager.sharedManager.autorunWorkflow
let selectedAutorun = autorunDropdown.selectedItem
autorunDropdown.removeAllItems()
autorunDropdown.addItemWithTitle("")
autorunDropdown.addItemsWithTitles(workflowTitles)
if selectedAutorun == nil && autorunWorkflow != nil {
autorunDropdown.selectItemWithTitle(autorunWorkflow!)
} else if selectedAutorun != nil {
autorunDropdown.selectItemWithTitle(selectedAutorun!.title)
}
let defaultWorkflow = ImagrConfigManager.sharedManager.defaultWorkflow
let selectedDefault = defaultDropdown.selectedItem
defaultDropdown.removeAllItems()
defaultDropdown.addItemWithTitle("")
defaultDropdown.addItemsWithTitles(workflowTitles)
if selectedDefault == nil && defaultWorkflow != nil {
defaultDropdown.selectItemWithTitle(defaultWorkflow!)
} else if selectedDefault != nil {
defaultDropdown.selectItemWithTitle(selectedDefault!.title)
}
tableView.reloadData()
}
@IBAction func terminateValidationTask(sender: AnyObject) {
task!.terminate()
}
@IBAction func addWorkflow(sender: AnyObject) {
let workflow = ImagrWorkflowManager(name: "", description: "", components: [])
ImagrConfigManager.sharedManager.workflows.append(workflow)
workflow.displayWorkflowWindow()
}
@IBAction func changePasswordClicked(sender: AnyObject) {
passwordField.stringValue = ""
passwordField.enabled = true
changePasswordButton.enabled = false
}
@IBAction func saveButtonClicked(sender: AnyObject) {
saveConfig()
let saveAlert = NSAlert()
saveAlert.informativeText = "\(ImagrConfigManager.sharedManager.imagrConfigPath!)"
saveAlert.messageText = "Imagr config successfully saved!"
saveAlert.beginSheetModalForWindow(mainWindow, completionHandler: nil)
}
@IBAction func validateButtonClicked(sender: AnyObject) {
let tempPlistPath = "\(tempDir)imagr_config.plist"
saveConfig(tempPlistPath)
displayValidateView(tempPlistPath)
}
func updateConfig() {
if passwordField.enabled && passwordField.stringValue != "" {
ImagrConfigManager.sharedManager.password = <PASSWORD>()
passwordField.enabled = false
changePasswordButton.enabled = true
changePasswordButton.hidden = false
passwordField.stringValue = ""
NSLog("Password was updated")
}
if backgroundImageField.stringValue == "" {
ImagrConfigManager.sharedManager.backgroundImage = nil
} else {
ImagrConfigManager.sharedManager.backgroundImage = backgroundImageField.stringValue
}
if defaultDropdown.selectedItem == nil || defaultDropdown.selectedItem!.title == "" {
ImagrConfigManager.sharedManager.defaultWorkflow = nil
} else {
ImagrConfigManager.sharedManager.defaultWorkflow = defaultDropdown.selectedItem!.title
}
if autorunDropdown.selectedItem == nil || autorunDropdown.selectedItem!.title == "" {
ImagrConfigManager.sharedManager.autorunWorkflow = nil
} else {
ImagrConfigManager.sharedManager.autorunWorkflow = autorunDropdown.selectedItem!.title
}
NSLog("Updated ImagrConfigManager from MainViewController")
}
func saveConfig() {
updateConfig()
if ImagrConfigManager.sharedManager.hasLoaded == true && ImagrConfigManager.sharedManager.imagrConfigPath == nil {
savePanel.allowedFileTypes = ["plist"]
savePanel.beginSheetModalForWindow(mainWindow, completionHandler: savePanelDidClose)
} else {
ImagrConfigManager.sharedManager.save()
NSLog("Imagr config saved to path: \(ImagrConfigManager.sharedManager.imagrConfigPath!)")
let saveAlert = NSAlert()
saveAlert.informativeText = "\(ImagrConfigManager.sharedManager.imagrConfigPath!)"
saveAlert.messageText = "Imagr config successfully saved!"
saveAlert.beginSheetModalForWindow(mainWindow, completionHandler: nil)
}
}
func savePanelDidClose(response: NSModalResponse) {
if response == 1 {
ImagrConfigManager.sharedManager.imagrConfigPath = savePanel.URL!.path!
saveConfig()
}
}
func saveConfig(path: String) {
updateConfig()
ImagrConfigManager.sharedManager.save(path)
NSLog("Imagr config saved to path: \(path)")
}
@IBAction func validateOkClicked(sender: AnyObject) {
mainWindow.contentView = mainView
}
func displayValidateView(plistPath: String) {
// this should happen anytime this function is called.
// the task will be set to nil everytime it terminates
if task == nil {
task = NSTask()
}
// set up the task with the correct executable and path to validateplist.py
task!.launchPath = "/usr/bin/python"
let validatePlistPath = NSBundle.mainBundle().pathForResource("validateplist", ofType: "py")!
task!.arguments = [validatePlistPath, plistPath]
// set up a Pipe to handle stdout from the task
let pipe = NSPipe()
task!.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
// observer for when there is output available from the validateplist path
var obs1 : NSObjectProtocol!
obs1 = NSNotificationCenter.defaultCenter().addObserverForName(NSFileHandleDataAvailableNotification, object: outHandle, queue: nil) {
notification -> Void in
let data = outHandle.availableData
// make sure there is data or remove the observer
if data.length > 0 {
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// split the output by new line separators.
// each line should be a message from validateplist
let lines = str.componentsSeparatedByString("\n")
for line in lines {
// format each message with the appropriate colors
self.validateTextField.textStorage?.appendAttributedString(formatMessageString(line))
}
}
outHandle.waitForDataInBackgroundAndNotify()
} else {
NSNotificationCenter.defaultCenter().removeObserver(obs1)
}
}
// observer used to receive terminate notification. stops all progress and disables the necessary buttons
var obs2 : NSObjectProtocol!
obs2 = NSNotificationCenter.defaultCenter().addObserverForName(NSTaskDidTerminateNotification, object: task, queue: nil) {
notification -> Void in
NSLog("Validation task terminated")
self.validateSpinner.stopAnimation(self)
self.validateSpinner.hidden = true
self.validateOkButton.enabled = true
self.skipValidateButton.enabled = false
NSNotificationCenter.defaultCenter().removeObserver(obs2)
// make sure the task is nil so that when this function is called a new task is created
self.task = nil
}
// switch the view, start progress spinner and enable necessary buttons
mainWindow.contentView = validateView
validateSpinner.startAnimation(self)
validateSpinner.hidden = false
validateOkButton.enabled = false
skipValidateButton.enabled = true
// launch the task with GCD after a half second delay
let timeDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(timeDelay, dispatch_get_main_queue()) {
// Make sure text is all black for the first line
let startOutput = NSAttributedString(string: "Running validateplist...\n\n", attributes: [NSForegroundColorAttributeName: NSColor.blackColor()])
self.validateTextField.textStorage?.appendAttributedString(startOutput)
self.task!.launch()
}
}
}
// handles the datasource methods for the workflow tableView
extension MainViewController: NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
// get workflow array from
let workflows = ImagrConfigManager.sharedManager.workflows
if workflows != nil {
return workflows.count ?? 0
} else {
return 0
}
}
}
extension MainViewController: NSTableViewDelegate {
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
var text: String = ""
var cellIdentifier: String = ""
let workflow = ImagrConfigManager.sharedManager.workflows[row]
if tableColumn == tableView.tableColumns[0] {
text = workflow.name
cellIdentifier = "NameCellID"
} else if tableColumn == tableView.tableColumns[1] {
text = workflow.description
cellIdentifier = "DescriptionCellID"
} else if tableColumn == tableView.tableColumns[2] {
text = String(workflow.hidden ?? false)
cellIdentifier = "HiddenCellID"
} else if tableColumn == tableView.tableColumns[3] {
text = String(workflow.blessTarget ?? true)
cellIdentifier = "BlessCellID"
} else if tableColumn == tableView.tableColumns[4] {
text = String(workflow.restartAction ?? "none")
cellIdentifier = "RestartCellID"
}
if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
return cell
}
return nil
}
@IBAction func tableViewDoubleClick(sender: AnyObject) {
guard tableView.selectedRow >= 0 , let workflow = ImagrConfigManager.sharedManager.workflows?[tableView.selectedRow] else {
return
}
workflow.displayWorkflowWindow()
}
// DRAG AND DROP METHODS
func tableView(aTableView: NSTableView, writeRowsWithIndexes rowIndexes: NSIndexSet, toPasteboard pboard: NSPasteboard) -> Bool {
if (aTableView == tableView) {
let data:NSData = NSKeyedArchiver.archivedDataWithRootObject(rowIndexes)
let registeredTypes:[String] = [NSStringPboardType]
pboard.declareTypes(registeredTypes, owner: self)
pboard.setData(data, forType: NSStringPboardType)
return true
} else {
return false
}
}
func tableView(aTableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation operation: NSTableViewDropOperation) -> NSDragOperation {
if operation == .Above {
return .Move
}
return .Every
}
func tableView(tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableViewDropOperation) -> Bool {
let data:NSData = info.draggingPasteboard().dataForType(NSStringPboardType)!
let rowIndexes:NSIndexSet = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSIndexSet
if ((info.draggingSource() as! NSTableView == tableView) && (tableView == tableView)) {
let value = ImagrConfigManager.sharedManager.workflows[rowIndexes.firstIndex]
ImagrConfigManager.sharedManager.workflows.removeAtIndex(rowIndexes.firstIndex)
if (row > ImagrConfigManager.sharedManager.workflows.count){
ImagrConfigManager.sharedManager.workflows.insert(value, atIndex: row-1)
} else {
ImagrConfigManager.sharedManager.workflows.insert(value, atIndex: row)
}
tableView.reloadData()
return true
} else {
return false
}
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/BaseComponentViewController.swift
//
// BaseComponentViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/15/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
public class BaseComponentViewController: NSViewController {
internal var workflowName: String?
internal var workflowWindow: NSWindow?
override public func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
func configure(workflowWindow: NSWindow!) {
self.workflowWindow = workflowWindow
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/PackageComponent/PackageComponentViewController.swift
//
// PackageComponentViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/15/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
class PackageComponentViewController: NSViewController {
@IBOutlet weak var packageURLField: NSTextField!
@IBOutlet weak var firstBootCheckbox: NSButton!
var component: PackageComponent?
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? PackageComponent
packageURLField.stringValue = component!.URL
if component!.firstBoot == false {
firstBootCheckbox.state = 0
} else {
firstBootCheckbox.state = 1
}
}
override func viewDidDisappear() {
component!.URL = packageURLField.stringValue
if firstBootCheckbox.state == 0 {
component!.firstBoot = false
} else {
component!.firstBoot = true
}
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
<file_sep>/.github/ISSUE_TEMPLATE.md
## New issue checklist
<!-- Before submitting this issue, make sure you have done the following -->
- [ ] I have searched [existing issues](https://github.com/kylecrawshaw/ImagrAdmin/issues?q=is%3Aissue+sort%3Acreated-desc) and **this is not a duplicate**.
### General information
- Release Version:
- Reproducible every time? (Yes/No):
- Related issues:
## Bug report
#### Expected behavior
> ...
#### Actual behavior
> ...
#### Steps to reproduce
> ...
#### Crash log? Screenshots?
>...
## Question or Feature Request
> ...
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/IncludedWorkflowComponent/IncludedWorkflowViewController.swift
//
// IncludedWorkflowViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/15/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
class IncludedWorkflowViewController: NSViewController {
@IBOutlet var scriptField: NSTextView!
@IBOutlet weak var includedWorkflowDropdown: NSPopUpButton!
@IBOutlet weak var contentView: NSView!
@IBOutlet var mainView: NSView!
@IBOutlet var dropdownView: NSView!
@IBOutlet var scriptView: NSView!
@IBOutlet weak var scriptRadioButton: NSButton!
@IBOutlet weak var selectRadioButton: NSButton!
var component: IncludedWorkflowComponent?
var contentFrameOrigin: CGPoint!
var originalWindowFrame: CGRect!
override func viewDidLoad() {
super.viewDidLoad()
contentFrameOrigin = contentView.frame.origin
}
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? IncludedWorkflowComponent
let viewIdentifierSplit = self.identifier!.characters.split{$0 == "-"}.map(String.init)
let workflowName = viewIdentifierSplit[0]
var workflowTitles: [String] = []
for workflow in ImagrConfigManager.sharedManager.workflows! {
if workflow.name != workflowName {
workflowTitles.append(workflow.name)
}
}
includedWorkflowDropdown!.removeAllItems()
includedWorkflowDropdown!.addItemsWithTitles(workflowTitles)
if component!.script != nil {
scriptField!.string = component!.script
}
if component!.includedWorkflow != nil && component!.script == nil {
includedWorkflowDropdown!.selectItemWithTitle(component!.includedWorkflow!)
scriptRadioButton.state = 0
selectRadioButton.state = 1
} else if component!.script != nil {
scriptRadioButton.state = 1
selectRadioButton.state = 0
}
else {
includedWorkflowDropdown!.selectItemAtIndex(0)
scriptRadioButton.state = 0
selectRadioButton.state = 1
}
if originalWindowFrame == nil {
originalWindowFrame = component!.componentWindow!.frame
}
updateView(self)
}
override func viewDidDisappear() {
if selectRadioButton.state == 1 {
component!.includedWorkflow = includedWorkflowDropdown!.titleOfSelectedItem
} else {
component!.script = scriptField.string
}
component!.notifyUpdateTable()
}
@IBAction func updateView(sender: AnyObject) {
var newView: NSView!
if selectRadioButton.state == 1 {
newView = dropdownView
} else {
newView = scriptView
}
let workflow = ImagrConfigManager.sharedManager.getWorkflow(component!.workflowName)
workflow!.workflowWindow!.frame.origin.x
// Adjust the window size
let newHeight = newView.frame.height + originalWindowFrame.height
let newSize = NSMakeSize(originalWindowFrame.width, newHeight)
mainView.setFrameSize(newSize)
let newOriginX = workflow!.workflowWindow!.frame.origin.x + ((workflow!.workflowWindow!.contentView!.frame.size.width - newSize.width) / 2)
let newOriginY = (workflow!.workflowWindow!.contentView!.frame.size.height - newSize.height) + workflow!.workflowWindow!.frame.origin.y
let newOrigin = CGPoint(x: newOriginX, y: newOriginY)
let newFrame = CGRect(origin: newOrigin, size: newSize)
component!.componentWindow!.setFrame(newFrame, display: true, animate: false)
newView.setFrameOrigin(contentFrameOrigin)
var originalView: NSView!
for subview in mainView!.subviews {
if subview.identifier! == "placeholder" {
originalView = contentView
break
} else if subview.identifier! == "script" {
originalView = scriptView
break
} else if subview.identifier! == "select" {
originalView = dropdownView
break
}
}
mainView!.replaceSubview(originalView, with: newView)
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/ImageComponent/ImageComponentViewController.swift
//
// ImageComponentViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/14/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
class ImageComponentViewController: NSViewController {
@IBOutlet weak var imageURLField: NSTextField!
@IBOutlet weak var verifyImageCheckbox: NSButton!
var component: ImageComponent?
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? ImageComponent
imageURLField.stringValue = component!.URL
if component!.verify == false {
verifyImageCheckbox.state = 0
} else {
verifyImageCheckbox.state = 1
}
}
override func viewDidDisappear() {
component!.URL = imageURLField.stringValue
if verifyImageCheckbox.state == 0 {
component!.verify = false
} else {
component!.verify = true
}
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/EraseVolumeComponent/EraseVolumeComponent.swift
//
// ImageComponent.swift
// ImagrManager
//
// Created by <NAME> on 7/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
class EraseVolumeComponent: BaseComponent {
var volumeName: String!
var volumeFormat: String!
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "eraseVolume", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = EraseVolumeViewController()
self.volumeName = ""
self.volumeFormat = "Journaled HFS+"
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "eraseVolume", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = EraseVolumeViewController()
self.volumeName = dict.valueForKey("name") as? String ?? ""
self.volumeFormat = dict.valueForKey("format") as? String ?? "Journaled HFS+"
}
override func asDict() -> NSDictionary? {
let dict: [String: AnyObject] = [
"type": type,
"name": volumeName,
"format": volumeFormat
]
return dict
}
}<file_sep>/ImagrAdmin/Utils.swift
//
// Crypto.swift
// ImagrAdmin
//
// Created by <NAME> on 7/25/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
// adapted from http://stackoverflow.com/questions/25761344/how-to-crypt-string-to-sha1-with-swift
extension String {
func sha512() -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joinWithSeparator("")
}
}
func formatMessageString(message: String) -> NSMutableAttributedString {
let attrStr = NSMutableAttributedString(string: "\(message)\r", attributes: [NSForegroundColorAttributeName: NSColor.blackColor()])
if message.containsString("WARNING:") {
attrStr.addAttribute(NSForegroundColorAttributeName, value: NSColor.orangeColor(), range: NSMakeRange(0, 8))
} else if message.containsString("ERROR:") {
attrStr.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: NSMakeRange(0, 6))
} else if message.containsString("SUCCESS:") {
attrStr.addAttribute(NSForegroundColorAttributeName, value: NSColor.greenColor(), range: NSMakeRange(0, 8))
}
return attrStr
}
//for line in lines {
//
// var range: NSRange?
//
// self.validateTextField.textStorage?.appendAttributedString(attrStr)
// if range != nil {
// attrStr.removeAttribute(NSForegroundColorAttributeName, range: range!)
// }
//}<file_sep>/.github/PULL_REQUEST_TEMPLATE.md
## Pull request checklist
- [ ] I have resolved any merge conflicts.
#### This fixes issue
## What's in this pull request?
>...
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/LocalizationComponent/LocalizationManager.swift
//
// LocalizationManager.swift
// ImagrManager
//
// Created by <NAME> on 7/19/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Carbon
class LocalizationManager {
static func keyboardLayouts() -> [String: [String: String]] {
let dict = NSDictionary(dictionary: [kTISPropertyInputSourceType as String: "TISTypeKeyboardLayout"])
let inputSources = TISCreateInputSourceList(dict, true).takeRetainedValue() as NSArray as! [TISInputSource]
var kbLayouts: [String: [String: String]] = [:]
for src in inputSources {
let ptr = TISGetInputSourceProperty(src, kTISPropertyInputSourceID)
let inputSourceIdentifier = Unmanaged<CFString>.fromOpaque(COpaquePointer(ptr)).takeUnretainedValue() as String
let srcStr = String(src)
let nameStart = srcStr.rangeOfString("Layout: ")
let midStr = srcStr.rangeOfString(" (id=")
let layoutName = srcStr.substringWithRange(nameStart!.endIndex..<midStr!.startIndex)
let layoutId = srcStr.substringWithRange(midStr!.endIndex..<srcStr.endIndex.advancedBy(-1))
kbLayouts[inputSourceIdentifier] = ["id": layoutId, "name": layoutName]
}
return kbLayouts
}
func matchCountry(countryISO: String) -> Bool {
let countryCodePlist = NSDictionary(contentsOfFile:"/System/Library/CoreServices/Setup Assistant.app/Contents/Resources/SACountry.plist")
let countryCodes = countryCodePlist!.allKeys as! [String]
if countryCodes.contains(countryISO) {
return true
} else {
return false
}
}
static func countryCodes() -> [String] {
let countryCodePlist = NSDictionary(contentsOfFile:"/System/Library/CoreServices/Setup Assistant.app/Contents/Resources/SACountry.plist")
return countryCodePlist!.allKeys as! [String]
}
static func getLanguages(countryISO: String) -> [String] {
let countryLanguageList = NSDictionary(contentsOfFile: "/System/Library/CoreServices/Setup Assistant.app/Contents/Resources/SALanguageToCountry.plist")
var countryLanguageCodesList: [String] = []
for (countryLanguageCodes, countryLanguages) in countryLanguageList! {
if (countryLanguages as! [String]).contains(countryISO) {
countryLanguageCodesList.append(countryLanguageCodes as! String)
}
}
return countryLanguageCodesList
}
static func getTimezones(countryISO: String) -> [String]{
let countryTimezonesPlist = NSDictionary(contentsOfFile: "/System/Library/PrivateFrameworks/SetupAssistantSupport.framework/Versions/A/Resources/TimeZones.plist")
var countryTimezones: AnyObject? = countryTimezonesPlist!.valueForKey(countryISO) as? NSDictionary
var timezones: [String] = []
if countryTimezones == nil {
countryTimezones = countryTimezonesPlist!.valueForKey(countryISO) as? NSArray ?? []
timezones = countryTimezones as! [String]
} else {
for (_, timezoneName) in countryTimezones as! [String: AnyObject] {
for zone in timezoneName as! [AnyObject] {
timezones.append(zone as! String)
}
}
}
return timezones
}
static func getInputSources(countryISO: String) -> NSArray {
let countryInputSources = NSDictionary(contentsOfFile: "/System/Library/PrivateFrameworks/SetupAssistantSupport.framework/Versions/A/Resources/SALocaleToInputSourceID.plist")
var inputSourceChoices: [String] = []
for source in countryInputSources!.allKeys {
if (source as! String).rangeOfString(countryISO) != nil {
inputSourceChoices = countryInputSources!.valueForKey(source as! String) as! [String]
break
}
}
var allKeyboardLayouts = LocalizationManager.keyboardLayouts()
var keyboardLayoutNames: [String] = []
for choice in inputSourceChoices {
keyboardLayoutNames.append(allKeyboardLayouts[choice]!["name"]!)
}
return keyboardLayoutNames
}
static func getKeyboardLayoutId(layoutName: String) -> String? {
let allKeyboardLayouts = LocalizationManager.keyboardLayouts()
var keyboardLayoutId: String?
for (_, layout) in allKeyboardLayouts {
if layout["name"] == layoutName {
keyboardLayoutId = layout["id"]!
break
}
}
return keyboardLayoutId
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/RegisteredComponents.swift
//
// RegisteredComponents.swift
// ImagrManager
//
// Created by <NAME> on 7/14/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
let registeredComponents: Array<String> = [
"image",
"package",
"script",
"included_workflow",
"computer_name",
"eraseVolume",
"localize"
]
//let registerObj = (ImageComponent, PackageComponent)
func newComponentObj(type: String!, id: Int!, workflowId: Int!, workflowName: String!) -> AnyObject? {
switch type {
case "image":
return ImageComponent(id: id, workflowName: workflowName, workflowId: workflowId)
case "package":
return PackageComponent(id: id, workflowName: workflowName, workflowId: workflowId)
case "included_workflow":
return IncludedWorkflowComponent(id: id, workflowName: workflowName, workflowId: workflowId)
case "computer_name":
return ComputerNameComponent(id: id, workflowName: workflowName, workflowId: workflowId)
case "eraseVolume":
return EraseVolumeComponent(id: id, workflowName: workflowName, workflowId: workflowId)
case "script":
return ScriptComponent(id: id, workflowName: workflowName, workflowId: workflowId)
case "localize":
return LocalizationComponent(id: id, workflowName: workflowName, workflowId: workflowId)
default:
return nil
}
}
func newComponentObj(type: String!, id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) -> AnyObject? {
switch type {
case "image":
return ImageComponent(id: id, workflowName: workflowName, workflowId: workflowId, dict: dict)
case "package":
return PackageComponent(id: id, workflowName: workflowName, workflowId: workflowId, dict: dict)
case "included_workflow":
return IncludedWorkflowComponent(id: id, workflowName: workflowName, workflowId: workflowId, dict: dict)
case "computer_name":
return ComputerNameComponent(id: id, workflowName: workflowName, workflowId: workflowId, dict: dict)
case "eraseVolume":
return EraseVolumeComponent(id: id, workflowName: workflowName, workflowId: workflowId, dict: dict)
case "script":
return ScriptComponent(id: id, workflowName: workflowName, workflowId: workflowId, dict: dict)
case "localize":
return LocalizationComponent(id: id, workflowName: workflowName, workflowId: workflowId, dict: dict)
default:
return nil
}
}<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowViewController.swift
//
// WorkflowViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/10/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
//import Foundation
import Cocoa
class WorkflowViewController: NSViewController {
@IBOutlet weak var label: NSTextField!
@IBOutlet weak var nameField: NSTextField!
@IBOutlet weak var descriptionField: NSTextField!
@IBOutlet var tableView: NSTableView!
@IBOutlet var selectComponentPanel: NSPanel!
@IBOutlet weak var componentDropdown: NSPopUpButton!
@IBOutlet var workflowWindow: NSWindow!
@IBOutlet weak var blessCheckBox: NSButton!
@IBOutlet weak var restartActionDropdown: NSPopUpButton!
@IBOutlet weak var hiddenCheckbox: NSButton!
var workflow: ImagrWorkflowManager?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
workflow = ImagrConfigManager.sharedManager.getWorkflow(self.identifier)
let notificationName = "UpdateTableView-\(workflow!.workflowID!)"
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateTableNotificationReceived(_:)), name:notificationName, object: nil)
nameField.stringValue = workflow!.name
descriptionField.stringValue = workflow!.description
if workflow!.restartAction != nil {
restartActionDropdown.selectItemWithTitle(workflow!.restartAction)
}
if workflow!.blessTarget != nil && workflow!.blessTarget == false {
blessCheckBox.state = 0
} else {
blessCheckBox.state = 1
}
if workflow!.hidden != nil && workflow!.hidden == true {
hiddenCheckbox.state = 1
} else {
hiddenCheckbox.state = 0
}
tableView.setDelegate(self)
tableView.setDataSource(self)
tableView.target = self
let registeredTypes: [String] = [NSStringPboardType]
tableView.registerForDraggedTypes(registeredTypes)
}
func updateTableNotificationReceived(sender: AnyObject) {
NSLog("Received notification to update workflow with ID: \(workflow?.workflowID)")
tableView.reloadData()
}
override func viewDidAppear() {
tableView.reloadData()
}
override func viewDidDisappear() {
let workflowTitles = ImagrConfigManager.sharedManager.workflowTitles()
if workflowTitles.contains(nameField.stringValue) && workflow!.name != nameField.stringValue{
let nameAlert = NSAlert()
nameAlert.alertStyle = NSAlertStyle.CriticalAlertStyle
nameAlert.messageText = "This name is already assigned to another workflow"
nameAlert.informativeText = "Workflow names must be unique"
nameAlert.beginSheetModalForWindow(workflowWindow!, completionHandler: nil)
} else {
workflow!.name = nameField.stringValue
workflow!.description = descriptionField.stringValue
workflow!.restartAction = restartActionDropdown.selectedItem!.title
if blessCheckBox.state == 0 {
workflow!.blessTarget = false
} else {
workflow!.blessTarget = true
}
if hiddenCheckbox.state == 1 {
workflow!.hidden = true
} else {
workflow!.hidden = false
}
NSNotificationCenter.defaultCenter().postNotificationName("UpdateWorkflowTableView", object: nil)
}
}
@IBAction func removeComponent(sender: AnyObject) {
if tableView.selectedRow >= 0 {
workflow!.components.removeAtIndex(tableView.selectedRow)
tableView.reloadData()
}
}
@IBAction func displaySelectComponentPanel(sender: AnyObject) {
componentDropdown.removeAllItems()
componentDropdown.addItemsWithTitles(registeredComponents)
workflowWindow.beginSheet(selectComponentPanel, completionHandler: nil)
}
@IBAction func closeSelectComponentPanel(sender: NSButton!) {
let ComponentObj: BaseComponent
if sender.title == "OK" {
let componentID = workflow!.components.count
ComponentObj = newComponentObj(componentDropdown.selectedItem?.title, id: componentID, workflowId: workflow!.workflowID, workflowName: workflow!.name) as! BaseComponent
workflow?.components.append(ComponentObj)
workflowWindow.endSheet(selectComponentPanel)
ComponentObj.displayComponentPanel(workflowWindow!)
} else if sender.title == "Cancel" {
NSLog("User cancelled selecting new component")
workflowWindow.endSheet(selectComponentPanel)
} else{
workflowWindow.endSheet(selectComponentPanel)
}
}
@IBAction func reloadTableView(sender: AnyObject) {
tableView.reloadData()
}
@IBAction func okClicked(sender: AnyObject) {
workflowWindow.orderOut(nil)
}
}
extension WorkflowViewController: NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if workflow!.components != nil {
return workflow!.components.count ?? 0
} else {
return 0
}
}
}
extension WorkflowViewController: NSTableViewDelegate {
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
var text: String = ""
var cellIdentifier: String = ""
let component = workflow!.components[row]
if tableColumn == tableView.tableColumns[0] {
text = component.type
cellIdentifier = "TypeCellID"
}
if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: nil) as? NSTableCellView {
cell.textField?.stringValue = text
return cell
}
return nil
}
@IBAction func tableViewDoubleClick(sender: AnyObject) {
guard tableView.selectedRow >= 0 , let component = workflow!.components?[tableView.selectedRow] else {
return
}
component.displayComponentPanel(workflowWindow)
}
// DRAG AND DROP METHODS
func tableView(aTableView: NSTableView, writeRowsWithIndexes rowIndexes: NSIndexSet, toPasteboard pboard: NSPasteboard) -> Bool {
if (aTableView == tableView) {
let data:NSData = NSKeyedArchiver.archivedDataWithRootObject(rowIndexes)
let registeredTypes:[String] = [NSStringPboardType]
pboard.declareTypes(registeredTypes, owner: self)
pboard.setData(data, forType: NSStringPboardType)
return true
} else {
return false
}
}
func tableView(aTableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation operation: NSTableViewDropOperation) -> NSDragOperation {
if operation == .Above {
return .Move
}
return .Every
}
func tableView(tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableViewDropOperation) -> Bool
{
let data:NSData = info.draggingPasteboard().dataForType(NSStringPboardType)!
let rowIndexes:NSIndexSet = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSIndexSet
if ((info.draggingSource() as! NSTableView == tableView) && (tableView == tableView)) {
let value = workflow!.components[rowIndexes.firstIndex]
workflow!.components!.removeAtIndex(rowIndexes.firstIndex)
if (row > workflow!.components!.count){
workflow!.components!.insert(value, atIndex: row-1)
} else {
workflow!.components!.insert(value, atIndex: row)
}
tableView.reloadData()
return true
} else {
return false
}
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/ScriptComponent/ScriptComponentViewController.swift
//
// PackageComponentViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/15/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
class ScriptComponentViewController: NSViewController {
@IBOutlet weak var scriptURLField: NSTextField!
@IBOutlet var scriptContent: NSTextView!
@IBOutlet weak var firstBootCheckbox: NSButton!
@IBOutlet weak var contentView: NSView!
@IBOutlet var mainView: NSView!
@IBOutlet var scriptURLView: NSView!
@IBOutlet var bottomView: NSView!
@IBOutlet var scriptView: NSView!
@IBOutlet weak var manualRadioButton: NSButton!
@IBOutlet weak var urlRadioButton: NSButton!
var component: ScriptComponent?
var contentFrameOrigin: CGPoint!
var originalWindowFrame: CGRect!
override func viewDidLoad() {
super.viewDidLoad()
contentFrameOrigin = contentView.frame.origin
}
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? ScriptComponent
if component!.content != nil {
scriptContent.string = component!.content!
manualRadioButton.state = 1
urlRadioButton.state = 0
} else if component!.URL != nil {
scriptURLField.stringValue = component!.URL!
manualRadioButton.state = 0
urlRadioButton.state = 1
} else {
scriptURLField.stringValue = ""
manualRadioButton.state = 0
urlRadioButton.state = 1
}
if component!.firstBoot == false {
firstBootCheckbox.state = 0
} else {
firstBootCheckbox.state = 1
}
if originalWindowFrame == nil {
originalWindowFrame = component!.componentWindow!.frame
}
updateView()
}
override func viewDidDisappear() {
if manualRadioButton.state == 1 {
component!.content = scriptContent.string
component!.URL = nil
} else {
component!.content = nil
component!.URL = scriptURLField.stringValue
}
if firstBootCheckbox.state == 0 {
component!.firstBoot = false
} else {
component!.firstBoot = true
}
component!.notifyUpdateTable()
}
func updateView() {
var newView: NSView!
if urlRadioButton.state == 1{
newView = scriptURLView
} else {
newView = scriptView
}
let workflow = ImagrConfigManager.sharedManager.getWorkflow(component!.workflowName)
workflow!.workflowWindow!.frame.origin.x
// Adjust the window size
let newHeight = newView.frame.height + originalWindowFrame.height
let newSize = NSMakeSize(originalWindowFrame.width, newHeight)
mainView.setFrameSize(newSize)
let newOriginX = workflow!.workflowWindow!.frame.origin.x + ((workflow!.workflowWindow!.contentView!.frame.size.width - newSize.width) / 2)
let newOriginY = (workflow!.workflowWindow!.contentView!.frame.size.height - newSize.height) + workflow!.workflowWindow!.frame.origin.y
let newOrigin = CGPoint(x: newOriginX, y: newOriginY)
let newFrame = CGRect(origin: newOrigin, size: newSize)
component!.componentWindow!.setFrame(newFrame, display: true, animate: false)
newView.setFrameOrigin(contentFrameOrigin)
var originalView: NSView!
for subview in mainView!.subviews {
if subview.identifier! == "placeholder" {
originalView = contentView
break
} else if subview.identifier! == "script" {
originalView = scriptView
break
} else if subview.identifier! == "url" {
originalView = scriptURLView
break
}
}
mainView!.replaceSubview(originalView, with: newView)
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
@IBAction func toggleScriptType(sender: NSButton) {
NSLog("User clicked \"From URL\"")
updateView()
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/ComputerNameComponent/ComputerNameComponent.swift
//
// ImageComponent.swift
// ImagrManager
//
// Created by <NAME> on 7/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
class ComputerNameComponent: BaseComponent {
var useSerial: Bool!
var auto: Bool!
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "computer_name", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = ComputerNameViewController()
self.useSerial = false
self.auto = false
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "computer_name", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = ComputerNameViewController()
self.useSerial = dict.valueForKey("use_serial") as? Bool ?? false
self.auto = dict.valueForKey("auto") as? Bool ?? false
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
]
if useSerial == true {
dict["use_serial"] = useSerial
}
if auto == true {
dict["auto"] = auto
}
return dict
}
}<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/ComputerNameComponent/ComputerNameViewController.swift
//
// ImageComponentViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/14/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
class ComputerNameViewController: NSViewController {
@IBOutlet weak var useSerialCheckbox: NSButton!
@IBOutlet weak var autoCheckbox: NSButton!
var component: ComputerNameComponent?
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? ComputerNameComponent
if component!.useSerial == true {
useSerialCheckbox.state = 1
} else {
useSerialCheckbox.state = 0
}
if component!.auto == true {
autoCheckbox.state = 1
} else {
autoCheckbox.state = 0
}
}
override func viewDidDisappear() {
if useSerialCheckbox.state == 1 {
component!.useSerial = true
} else {
component!.useSerial = false
}
if autoCheckbox.state == 1 {
component!.auto = true
} else {
component!.auto = false
}
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/ImageComponent/ImageComponent.swift
//
// ImageComponent.swift
// ImagrManager
//
// Created by <NAME> on 7/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
class ImageComponent: BaseComponent {
var URL: String!
var verify: Bool!
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "image", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = ImageComponentViewController()
self.URL = ""
self.verify = true
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "image", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = ImageComponentViewController()
self.URL = dict.valueForKey("url") as? String ?? ""
self.verify = dict.valueForKey("verify") as? Bool ?? true
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
"url": URL,
]
if verify != nil {
dict["verify"] = verify
}
return dict
}
}<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/LocalizationComponent/LocalizationComponentViewController.swift
//
// ImageComponentViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/14/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
class LocalizationComponentViewController: NSViewController {
@IBOutlet weak var countryCodeDropdown: NSPopUpButton!
@IBOutlet weak var kbLayoutNameDropdown: NSPopUpButton!
@IBOutlet weak var languagesDropdown: NSPopUpButton!
@IBOutlet weak var timezoneDropdown: NSPopUpButton!
var component: LocalizationComponent?
override func viewDidLoad() {
if countryCodeDropdown.itemArray.count == 0 {
let countryCodes = LocalizationManager.countryCodes()
let countryCodesSorted = countryCodes.sort { $0 < $1 }
countryCodeDropdown.addItemsWithTitles(countryCodesSorted)
}
}
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? LocalizationComponent
let countryCode = component!.countryCode
if countryCode != nil && countryCodeDropdown.selectedItem!.title != "" {
countryCodeDropdown.selectItemWithTitle(countryCode!)
let languages = LocalizationManager.getLanguages(countryCode!)
updateDropdown(languagesDropdown, dropdownItems: languages, selectedItem: component!.language)
let timezones = LocalizationManager.getTimezones(countryCode!)
updateDropdown(timezoneDropdown, dropdownItems: timezones, selectedItem: component!.timezone)
let keyboardLayouts = LocalizationManager.getInputSources(countryCode!)
updateDropdown(kbLayoutNameDropdown, dropdownItems: keyboardLayouts, selectedItem: component!.keyboardLayoutName)
}
}
override func viewDidDisappear() {
if kbLayoutNameDropdown.selectedItem != nil {
component!.keyboardLayoutName = kbLayoutNameDropdown.selectedItem!.title
}
if kbLayoutNameDropdown.selectedItem != nil {
component!.keyboardLayoutId = LocalizationManager.getKeyboardLayoutId(kbLayoutNameDropdown.selectedItem!.title)
}
if timezoneDropdown.selectedItem != nil {
component!.timezone = timezoneDropdown.selectedItem!.title
}
if languagesDropdown.selectedItem != nil {
component!.language = languagesDropdown.selectedItem!.title
}
if countryCodeDropdown.selectedItem != nil {
component!.countryCode = countryCodeDropdown.selectedItem!.title
}
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
@IBAction func countryCodeChanged(sender: AnyObject) {
let selectedCountryCode = countryCodeDropdown.selectedItem!.title
let languages = LocalizationManager.getLanguages(selectedCountryCode)
updateDropdown(languagesDropdown, dropdownItems: languages, selectedItem: nil)
let timezones = LocalizationManager.getTimezones(selectedCountryCode)
updateDropdown(timezoneDropdown, dropdownItems: timezones, selectedItem: nil)
let keyboardLayouts = LocalizationManager.getInputSources(selectedCountryCode)
updateDropdown(kbLayoutNameDropdown, dropdownItems: keyboardLayouts, selectedItem: nil)
}
func updateDropdown(dropdown: NSPopUpButton, dropdownItems: NSArray, selectedItem: String?) {
dropdown.removeAllItems()
dropdown.addItemWithTitle("")
dropdown.addItemsWithTitles(dropdownItems as! [String])
dropdown.enabled = true
if selectedItem != nil {
dropdown.selectItemWithTitle(selectedItem!)
}
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/EraseVolumeComponent/EraseVolumeViewController.swift
//
// ImageComponentViewController.swift
// ImagrManager
//
// Created by <NAME> on 7/14/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Cocoa
class EraseVolumeViewController: NSViewController {
@IBOutlet weak var volumeNameField: NSTextField!
@IBOutlet weak var volumeFormatField: NSTextField!
var component: EraseVolumeComponent?
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? EraseVolumeComponent
volumeNameField.stringValue = component!.volumeName
volumeFormatField.stringValue = component!.volumeFormat
}
override func viewDidDisappear() {
component!.volumeName = volumeNameField.stringValue
component!.volumeFormat = volumeFormatField.stringValue
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/ImagrWorkflowManager.swift
//
// ImagrWorkflowManager.swift
// ImagrManager
//
// Created by <NAME> on 7/11/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
import AppKit
public class ImagrWorkflowManager {
var name: String!
var description: String!
var components: [BaseComponent]!
var restartAction: String!
var blessTarget: Bool!
var hidden: Bool!
var workflowWindowController: NSWindowController?
var workflowViewController: WorkflowViewController?
var workflowWindow: NSWindow?
var workflowID: Int! = ImagrConfigManager.sharedManager.nextWorkflowID()
init(dict: NSDictionary) {
self.name = dict.valueForKey("name") as? String! ?? ""
self.description = dict.valueForKey("description") as? String! ?? ""
self.restartAction = dict.valueForKey("restart_action") as? String! ?? "none"
self.blessTarget = dict.valueForKey("bless_target") as? Bool! ?? true
self.hidden = dict.valueForKey("hidden") as? Bool! ?? false
// init empty array and then add and init components if necessary
self.components = []
if let wfComponents = dict.valueForKey("components") as? [NSDictionary]! {
for component in wfComponents {
addComponent(component)
}
}
}
init(name: String, description: String, components: [BaseComponent]?) {
self.name = name
self.description = description
self.components = components ?? []
self.restartAction = "none"
self.blessTarget = true
self.hidden = false
}
func asDict() -> NSDictionary! {
var formattedComponents: [NSDictionary!] = []
for component in components {
formattedComponents.append(component.asDict())
}
let workflowDict: NSMutableDictionary = [
"name": name,
"description": description,
"components": formattedComponents,
]
if restartAction != nil {
workflowDict.setValue(restartAction, forKey: "restart_action")
}
if blessTarget != nil {
workflowDict.setValue(blessTarget, forKey: "bless_target")
}
if hidden != nil {
workflowDict.setValue(hidden, forKey: "hidden")
}
return workflowDict
}
func addComponent(dict: NSDictionary!) {
let componentID = components.count
guard let type = dict.valueForKey("type") as? String! else {
return
}
let component = newComponentObj(type, id: componentID, workflowName: name, workflowId: workflowID, dict: dict)
components.append(component as! BaseComponent)
}
func displayWorkflowWindow() {
if workflowWindowController == nil {
buildWorkflowWindow()
}
workflowWindow!.makeKeyAndOrderFront(self)
workflowWindowController!.showWindow(self)
}
private func buildWorkflowWindow() {
workflowViewController = WorkflowViewController()
workflowViewController!.identifier = String(name)
workflowWindow = NSWindow(contentViewController: workflowViewController!)
workflowWindow!.title = "Edit Workflow"
// Set a fixed sized for the workflow window
let fixedSize = workflowWindow!.frame.size
workflowWindow!.minSize = fixedSize
workflowWindow!.maxSize = fixedSize
// Hide window title bar buttons
let closeButton = workflowWindow!.standardWindowButton(NSWindowButton.CloseButton)
closeButton!.hidden = true
let minButton = workflowWindow!.standardWindowButton(NSWindowButton.MiniaturizeButton)
minButton!.hidden = true
let maxButton = workflowWindow!.standardWindowButton(NSWindowButton.ZoomButton)
maxButton!.hidden = true
workflowViewController!.workflowWindow = workflowWindow
workflowWindowController = NSWindowController(window: workflowWindow)
}
}<file_sep>/ImagrAdmin/ImagrConfigManager.swift
//
// ImagrConfigManager.swift
// ImagrManager
//
// Created by <NAME> on 7/11/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
public class ImagrConfigManager {
public static let sharedManager = ImagrConfigManager()
var imagrConfigPath: String?
var password: String?
var workflows: [ImagrWorkflowManager]! = []
var defaultWorkflow: String?
var backgroundImage: String?
var autorunWorkflow: String?
private var configData: NSMutableDictionary! = NSMutableDictionary()
var hasLoaded: Bool = false
private func clearConfig() {
imagrConfigPath = nil
password = nil
workflows = []
defaultWorkflow = nil
backgroundImage = nil
autorunWorkflow = nil
configData = NSMutableDictionary()
hasLoaded = false
}
public func loadConfig() {
clearConfig()
NSLog("Initialized new ImagrConfigManager.sharedManager")
hasLoaded = true
}
public func loadConfig(path: String!) {
clearConfig()
NSLog("Initialized ImagrConfigManager.sharedManager with \(path)")
imagrConfigPath = path
if NSFileManager.defaultManager().fileExistsAtPath(imagrConfigPath!) {
configData = NSMutableDictionary(contentsOfFile: imagrConfigPath!)
} else {
configData = NSMutableDictionary()
}
password = configData!["password"] as? String
defaultWorkflow = configData!["default_workflow"] as? String
autorunWorkflow = configData!["autorun"] as? String
backgroundImage = configData!["background_image"] as? String
let workflowsFromConfig = configData["workflows"] as? [AnyObject] ?? []
for workflow in workflowsFromConfig {
workflows.append(ImagrWorkflowManager(dict: workflow as! NSDictionary))
}
hasLoaded = true
}
public func nextWorkflowID() -> Int! {
return workflows.count
}
public func getWorkflow(name: String!) -> ImagrWorkflowManager? {
var workflow: ImagrWorkflowManager?
for possibleWorkflow in workflows! {
if possibleWorkflow.name == name {
workflow = possibleWorkflow
break
}
}
return workflow
}
public func getWorkflowByID(id: Int!) -> ImagrWorkflowManager? {
var workflow: ImagrWorkflowManager?
for possibleWorkflow in workflows! {
if possibleWorkflow.workflowID == id {
workflow = possibleWorkflow
break
}
}
return workflow
}
public func getComponent(viewIdentifier: String!) -> BaseComponent? {
let viewIdentifierSplit = viewIdentifier.characters.split{$0 == "-"}.map(String.init)
let workflowId = Int(viewIdentifierSplit[0])
let componentId = Int(viewIdentifierSplit[1])
let workflow = getWorkflowByID(workflowId)
var workflowComponent: BaseComponent?
for component in workflow!.components {
if component.id == componentId {
workflowComponent = component
}
}
return workflowComponent
}
public func getWorkflowForView(viewIdentifier: String) -> ImagrWorkflowManager? {
let viewIdentifierSplit = viewIdentifier.characters.split{$0 == "-"}.map(String.init)
let workflowId = viewIdentifierSplit[0]
return getWorkflowByID(Int(workflowId))
}
public func workflowTitles() -> [String] {
var workflowTitleList: [String] = []
for workflow in workflows! {
workflowTitleList.append(workflow.name)
}
return workflowTitleList
}
public func asDict() -> NSDictionary {
updateConfigDict()
return configData
}
private func updateConfigDict() {
configData.setValue(password, forKey: "password")
configData.setValue(defaultWorkflow, forKey: "default_workflow")
configData.setValue(autorunWorkflow, forKey: "autorun")
configData.setValue(backgroundImage, forKey: "background_image")
var formattedWorkflows: [NSDictionary] = []
if workflows != nil {
for workflow in workflows! {
formattedWorkflows.append(workflow.asDict())
}
}
configData.setValue(formattedWorkflows, forKey: "workflows")
NSLog("Updating configData from ImagrConfigManager")
}
public func save() {
updateConfigDict()
configData.writeToFile(imagrConfigPath!, atomically: false)
}
public func save(path: String) {
updateConfigDict()
configData.writeToFile(path, atomically: false)
}
}
<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/IncludedWorkflowComponent/IncludedWorkflowComponent.swift
//
// IncludedWorkflowComponent.swift
// ImagrManager
//
// Created by <NAME> on 7/15/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
class IncludedWorkflowComponent: BaseComponent {
var includedWorkflow: String?
var script: String?
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "included_workflow", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = IncludedWorkflowViewController()
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "included_workflow", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = IncludedWorkflowViewController()
self.includedWorkflow = dict.valueForKey("included_workflow") as? String
self.script = dict.valueForKey("script") as? String
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
]
if includedWorkflow != nil {
dict["name"] = includedWorkflow!
}
if script != nil {
dict["script"] = script!
}
return dict
}
}<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/PackageComponent/PackageComponent.swift
//
// PackageComponent.swift
// ImagrManager
//
// Created by <NAME> on 7/13/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
class PackageComponent: BaseComponent {
var URL: String!
var firstBoot: Bool?
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "package", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = PackageComponentViewController()
self.URL = ""
self.firstBoot = true
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "package", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = PackageComponentViewController()
self.URL = dict.valueForKey("url") as? String ?? ""
self.firstBoot = dict.valueForKey("first_boot") as? Bool ?? true
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
"url": URL,
]
if firstBoot != nil {
dict["first_boot"] = firstBoot
}
return dict
}
}<file_sep>/ImagrAdmin/WorkflowSupport/WorkflowComponents/LocalizationComponent/LocalizationComponent.swift
//
// ImageComponent.swift
// ImagrManager
//
// Created by <NAME> on 7/12/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import Cocoa
class LocalizationComponent: BaseComponent {
var keyboardLayoutName: String?
var keyboardLayoutId: String?
var countryCode: String?
var language: String?
var timezone: String?
// var locale: String?
init(id: Int!, workflowName: String!, workflowId: Int!) {
super.init(id: id, type: "localize", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = LocalizationComponentViewController()
}
init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) {
super.init(id: id, type: "localize", workflowName: workflowName, workflowId: workflowId)
super.componentViewController = LocalizationComponentViewController()
self.keyboardLayoutName = dict.valueForKey("keyboard_layout_name") as? String
self.keyboardLayoutId = dict.valueForKey("keyboard_layout_id") as? String
self.timezone = dict.valueForKey("timezone") as? String
self.language = dict.valueForKey("language") as? String
if let locale = dict.valueForKey("locale") as? String {
let localeComponents = locale.characters.split{$0 == "_"}.map(String.init)
if localeComponents.count == 1 {
self.countryCode = localeComponents[0]
} else if localeComponents.count == 2 {
self.countryCode = localeComponents[1]
}
}
}
override func asDict() -> NSDictionary? {
var dict: [String: AnyObject] = [
"type": type,
]
if (keyboardLayoutName != nil) && (keyboardLayoutName != "") {
dict["keyboard_layout_name"] = keyboardLayoutName!
}
if (keyboardLayoutId != nil) && (keyboardLayoutId != "" ){
dict["keyboard_layout_id"] = Int(keyboardLayoutId!)
}
if (language != nil) && (language! != "") {
dict["language"] = language!
}
if (countryCode != nil && countryCode! != "" && language != nil) {
dict["locale"] = "\(language!)_\(countryCode!)"
}
if (timezone != nil) && (timezone != "") {
dict["timezone"] = timezone!
}
return dict
}
}<file_sep>/README.md
# ImagrAdmin

ImagrAdmin is a GUI application for macOS to update and create configuration plists
for [Imagr](https://github.com/grahamgilbert/imagr/). Imagr is built around the idea of
one main configuration file that contains workflows with a number of different components.
Before ImagrAdmin you would have to know what keys you could set for the different
workflow components. ImagrAdmin attempts to ease that process so you can focus on
creating great scripts and packages to be installed with Imagr.
### Imagr Workflow Components
##### Currently Supported Components
- [image](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#images)
- [package](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#packages) *
- [script](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#scripts)
- [included workflow](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#included-workflow)
- [computer_name](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#computer-name)
- [eraseVolume](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#erase-volume)
- [localize](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#localization)
*HTTP header support coming soon. Currently if you have a flat package that requires request headers it will not work.
##### Soon to be Supported Components
- [partition](https://github.com/grahamgilbert/imagr/wiki/Workflow-Config#partition)
## Todo
- [ ] Add support for HTTP headers for package components
- [ ] Add partition component
## Credits
- [@clburlison](https://github.com/clburlison): Created the ImagrAdmin icon
- [@grahamgilbert](https://github.com/grahamgilbert): Created [Imagr](https://github.com/grahamgilbert/imagr)
| 755a3d3d4cfba338834db257038246b2f34651d2 | [
"Swift",
"Markdown"
]
| 25 | Swift | kylecrawshaw/ImagrAdmin | 540f64bd7d17d000e274871366abd06c9c06e0b4 | 3d5f2fc140edb81dd28b2425efa54c8d7b5a0664 |
refs/heads/master | <repo_name>cvanlith/flamingo<file_sep>/viewer/src/main/webapp/viewer-html/common/layout.js
/*
* Copyright (C) 2012 B3Partners B.V.
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
Ext.define('viewer.LayoutManager', {
defaultRegionSettings: {
header: {region: 'north', columnOrientation: 'horizontal', useTabs: false, defaultLayout: {height: 150}},
leftmargin_top: {region:'west', subregion:'center', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {width: 250}},
leftmargin_bottom: {region:'west', subregion:'south', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {height: 250}},
left_menu: {region:'center', subregion:'west', columnOrientation: 'horizontal', subRegionOrientation: 'vertical', singleComponentBlock: true, useTabs: false,isPopup:true, defaultLayout: {width: 150}},
top_menu: {region:'none'},
content: {region:'center', subregion:'center', columnOrientation: 'horizontal', subRegionOrientation: 'vertical', singleComponentBlock: true, useTabs: false, defaultLayout: {}},
content_bottom: {region:'none'},
popupwindow: { region: 'popupwindow', useTabs: true,hasSharedPopup:true },
rightmargin_top: {region:'east', subregion:'center', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {width: 250}},
rightmargin_bottom: {region:'east', subregion:'south', columnOrientation: 'vertical', subRegionOrientation: 'vertical', useTabs: true, defaultLayout: {height: 250}},
footer: {region:'south', columnOrientation: 'horizontal', useTabs: false, defaultLayout: {height: 150}}
},
layout: {},
configuredComponents: {},
layoutItems: {},
mapId: '',
componentList: [],
wrapperId: 'wrapper',
autoRender: true,
tabComponents: {},
popupWin: null,
constructor: function(config) {
Ext.apply(this, config || {});
if(this.autoRender) {
this.createLayout();
}
},
createLayout: function() {
var me = this;
// console.log('LAYOUTMANAGER: ', me);
var regionList = me.createRegionList();
// console.log('REGIONLIST: ', regionList);
var viewportItems = me.buildLayoutRegions(regionList);
// console.log('VIEWPORTITEMS: ', viewportItems);
me.renderLayout(viewportItems);
},
filterComponentList: function(components) {
var me = this;
var result = Ext.Array.filter(components, function(comp) {
return me.configuredComponents[comp.name] != undefined;
});
return result;
},
createRegionList: function() {
var me = this;
var layoutItems = {};
Ext.Object.each(me.layout, function(regionid, regionconfig) {
// If region has components, add it to the list
if(me.filterComponentList(regionconfig.components).length > 0) {
// Fetch default config
var defaultConfig = me.defaultRegionSettings[regionid];
// Layoutregions are added throug array because 1 Ext region (e.g. west) can have multiple regions
if(!Ext.isDefined(layoutItems[defaultConfig.region])) {
layoutItems[defaultConfig.region] = [];
}
// Push the layout to the array
layoutItems[me.defaultRegionSettings[regionid].region].push({
// Region name
name: regionid,
// regionConfig holds the regionconfig from the layoutmanager
regionConfig: regionconfig,
// regionDefaultConfig holds the defaultConfig region
regionDefaultConfig: defaultConfig
});
}
});
return layoutItems;
},
buildLayoutRegions: function(regionList) {
var viewportItems = [];
var me = this;
Ext.Object.each(regionList, function(region, value) {
viewportItems.push(me.getLayoutRegion(region, value));
});
return viewportItems;
},
getLayoutRegion: function(regionid, regionitems) {
var me = this;
var layout = {
width: 0,
height: 0
};
var regionlayout = null;
var extLayout = '';
if(regionitems.length > 1) {
var items = me.getSubLayoutRegion(regionitems);
var centerItem = me.getSubRegionCenterItem(regionitems);
if(items.length > 0 && centerItem != null) {
extLayout = { type: 'vbox', align: 'stretch' };
if(centerItem.regionDefaultConfig.columnOrientation == 'horizontal') extLayout = { type: 'hbox', align: 'stretch' };
if(regionid != 'center') {
layout.width = centerItem.regionDefaultConfig.defaultLayout.width;
regionlayout = centerItem.regionConfig.layout;
if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
layout.width = parseInt(regionlayout.width);
} else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
layout.flex = parseInt(regionlayout.width) / 100;
}
} else {
layout.flex = 1;
layout.height = '100%';
}
return Ext.apply({
xtype: 'container',
region: regionid,
layout: extLayout,
items: items
}, layout);
}
} else {
regionlayout = regionitems[0].regionConfig.layout;
var componentItems = me.createComponents(me.filterComponentList(regionitems[0].regionConfig.components), regionitems[0].regionDefaultConfig, regionlayout,regionitems[0].name);
componentItems = me.getRegionContent(componentItems, regionlayout);
if(regionitems[0].regionDefaultConfig.region != "none" && regionitems[0].regionDefaultConfig.region != "popupwindow") {
layout = regionitems[0].regionDefaultConfig.defaultLayout;
if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
layout.width = parseInt(regionlayout.width);
} else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
layout.flex = parseInt(regionlayout.width) / 100;
}
if(regionlayout.height != '' && regionlayout.heightmeasure == 'px') {
layout.height = parseInt(regionlayout.height);
} else if(regionlayout.height != '' && regionlayout.heightmeasure == '%') {
layout.flex = parseInt(regionlayout.height) / 100;
}
extLayout = 'fit';
if(regionlayout.useTabs == false && componentItems.length > 1 && !Ext.isDefined(regionitems[0].regionDefaultConfig.singleComponentBlock) && !regionitems[0].regionDefaultConfig.singleComponentBlock) {
extLayout = { type: 'vbox', align: 'stretch' };
if(regionitems[0].regionDefaultConfig.columnOrientation == 'horizontal') {
extLayout = { type: 'hbox', align: 'stretch' };
}
}
var style = {};
if(regionlayout.bgcolor != '') {
style = {
backgroundColor: regionlayout.bgcolor
};
}
return Ext.apply({
xtype: 'container',
region: regionid,
layout: extLayout,
items: componentItems,
style: style
}, layout);
} else if(regionitems[0].regionDefaultConfig.region == "popupwindow") {
var width = 400;
if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
width = parseInt(regionlayout.width);
} else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
width = '' + parseInt(regionlayout.width) + '%';
}
var height = 400;
if(regionlayout.height != '' && regionlayout.heightmeasure == 'px') {
height = parseInt(regionlayout.height);
} else if(regionlayout.height != '' && regionlayout.heightmeasure == '%') {
height = '' + parseInt(regionlayout.height) + '%';
}
var popupLayout = 'fit';
if(regionlayout.useTabs == false && componentItems.length > 1) {
popupLayout = { type: 'hbox', align: 'stretch' };
}
var title = ' ';
if(regionlayout.title && regionlayout.title != '') {
title = regionlayout.title;
}
var posx = 0,
posy = 0,
position = 'center';
if(regionlayout.posx && regionlayout.posy && regionlayout.posx != '' && regionlayout.posy != '') {
posx = regionlayout.posx;
posy = regionlayout.posy;
position = 'fixed';
}
var popupWindowConfig = {
title: title,
showOnStartup:true,
details:{
closable: true,
closeAction: 'hide',
hideMode: 'offsets',
width: width,
height: height,
resizable: true,
draggable: true,
layout: popupLayout,
modal: false,
renderTo: Ext.getBody(),
autoScroll: true,
items: componentItems,
x: posx,
y: posy,
position: position
}
};
me.popupWin = Ext.create('viewer.components.ScreenPopup', popupWindowConfig);
}
}
return {};
},
getSubLayoutRegion: function(regionitems) {
var me = this;
var items = {};
Ext.Array.each(regionitems, function(item, index) {
var sublayout = {};
var regionlayout = item.regionConfig.layout;
var componentItems = me.createComponents(me.filterComponentList(item.regionConfig.components), item.regionDefaultConfig, regionlayout,item.name);
componentItems = me.getRegionContent(componentItems, regionlayout);
if(item.regionDefaultConfig.columnOrientation == 'vertical') {
if(item.regionDefaultConfig.subregion != 'center') {
sublayout = Ext.apply({
width: 0
}, item.regionDefaultConfig.defaultLayout);
if(regionlayout.height != '' && regionlayout.heightmeasure == 'px') {
sublayout.height = parseInt(regionlayout.height);
} else if(regionlayout.height != '' && regionlayout.heightmeasure == '%') {
sublayout.flex = parseInt(regionlayout.height) / 100;
}
} else {
sublayout.flex = 1;
}
}
if(item.regionDefaultConfig.columnOrientation == 'horizontal') {
if(item.regionDefaultConfig.subregion != 'center') {
sublayout = Ext.apply({
height: 0
}, item.regionDefaultConfig.defaultLayout);
if(regionlayout.width != '' && regionlayout.widthmeasure == 'px') {
sublayout.width = parseInt(regionlayout.width);
} else if(regionlayout.width != '' && regionlayout.widthmeasure == '%') {
sublayout.flex = parseInt(regionlayout.width) / 100;
}
} else {
sublayout.flex = 1;
}
}
var extLayout = 'fit';
if(regionlayout.useTabs == false && componentItems.length > 1 && !Ext.isDefined(item.regionDefaultConfig.singleComponentBlock) && !item.regionDefaultConfig.singleComponentBlock) {
extLayout = { type: 'vbox', align: 'stretch' };
if(item.regionDefaultConfig.subRegionOrientation == 'horizontal') {
extLayout = { type: 'hbox', align: 'stretch' };
}
}
var style = {};
if(regionlayout.bgcolor != '') {
style = {
backgroundColor: regionlayout.bgcolor
};
}
if(item.regionDefaultConfig.subregion != "none") {
items[item.regionDefaultConfig.subregion] = Ext.apply({
xtype: 'container',
items: componentItems,
layout: extLayout,
style: style
}, sublayout);
}
});
return me.reorderSubRegions(items);
},
reorderSubRegions: function(subregions) {
var order = ['north','west','center','east','south'];
var items = [];
Ext.Array.each(order, function(regionname) {
if(Ext.isDefined(subregions[regionname])) {
items.push(subregions[regionname]);
}
});
return items;
},
getSubRegionCenterItem: function(regionitems) {
var centerItem = null;
Ext.Array.each(regionitems, function(item, index) {
if(item.regionDefaultConfig.subregion == 'center') {
centerItem = item;
}
});
return centerItem;
},
createComponents: function(components, regionDefaultConfig, regionlayout,regionName) {
var componentItems = [];
var cmpId = null;
var me = this;
var first = true;
var singleBlock = (Ext.isDefined(regionDefaultConfig.singleComponentBlock) && regionDefaultConfig.singleComponentBlock);
Ext.Array.each(components, function(component) {
if(!singleBlock || (singleBlock && first)) {
cmpId = Ext.id();
}
var compStyle = {width: '100%',height: '100%'};
var compFlex = 0;
if(regionlayout.useTabs == false && !singleBlock) {
compStyle = {width: '100%'};
if(Ext.isDefined(regionDefaultConfig.subRegionOrientation)) {
if(regionDefaultConfig.subRegionOrientation == 'horizontal') {
compStyle = {height: '100%'};
}
} else {
if(regionDefaultConfig.columnOrientation == 'horizontal') {
compStyle = {height: '100%'};
}
}
compFlex = 1;
}
var cmpView = {
xtype: 'container',
// Title is used in tabs
title: component.name,
cls: 'component-view',
tpl: '<tpl for="."><div class="viewer-component-block" id="{id}" style="width: 100%;height: 100%;margin: 0px;padding: 0px;"></div></tpl>',
data: {
id: cmpId,
cmp_name: component.name
},
layout: 'fit',
hideMode: 'offsets',
style: compStyle,
flex: compFlex
};
if(!singleBlock || (singleBlock && first)) {
componentItems.push(cmpView);
}
var componentItem = {
htmlId: cmpId,
componentName: component.name,
componentClass: component.componentClass
};
if(regionDefaultConfig.isPopup) {
componentItem.isPopup = true;
}
if(regionDefaultConfig.showOnStartup) {
componentItem.showOnStartup = true;
}
if(regionDefaultConfig.hasSharedPopup) {
componentItem.hasSharedPopup = true;
}
if(regionName){
componentItem.regionName=regionName;
}
me.componentList.push(componentItem);
if(component.componentClass == "viewer.mapcomponents.FlamingoMap" || component.componentClass == "viewer.mapcomponents.OpenLayersMap") {
me.mapId = cmpId;
}
first = false;
});
return componentItems;
},
getRegionContent: function(componentItems, regionlayout) {
var me = this;
if(Ext.isDefined(regionlayout.useTabs) && regionlayout.useTabs && componentItems.length > 1) {
var cmpId = Ext.id();
Ext.Array.each(componentItems, function(component, index) {
me.tabComponents[component.data.cmp_name] = {
tabId: cmpId,
tabNo: index
}
});
var tabBarLayout = {};
if(regionlayout.bgcolor != '') {
tabBarLayout = {
style: {
backgroundColor: regionlayout.bgcolor,
backgroundImage: 'none' // Otherwise backgroundcolor is overridden by image
}
};
}
var tabcomponent = {
xtype: 'tabpanel',
id: cmpId,
activeTab: 0,
deferredRender: false,
defaults: {
hideMode: 'offsets'
},
items: componentItems,
tabBar: tabBarLayout
};
return tabcomponent;
}
return componentItems;
},
renderLayout: function(viewportItems) {
var me = this;
var containerStyle = {};
if(Ext.isIE8 && me.maxHeight && me.maxHeight !== null) {
// maxHeight is needed for IE8 bug where maxHeight on wrapper only does not work
containerStyle = {
maxHeight: me.maxHeight
};
}
me.mainLayoutContainer = Ext.create('Ext.container.Container', {
layout: 'border',
items: viewportItems,
renderTo: me.wrapperId,
height: me.getContainerheight(),
width: '100%',
style: containerStyle
});
},
getContainerheight: function() {
var me = this, containerHeight = '100%';
if(Ext.isWebKit && Ext.webKitVersion < 537.31) {
// There is a bug in webkit which allows the inner div to extend further than the max-height of the wrapper div
// Seems to be fixed in future Chrome versions (https://bugs.webkit.org/show_bug.cgi?id=26559) so remove this fix when possible
// solved in versions > 537.31
var wrapperHeight = Ext.get(me.wrapperId).getHeight();
if(wrapperHeight >= me.maxHeight) {
containerHeight = me.maxHeight + 'px';
}
}
return containerHeight;
},
getMapId: function() {
return this.mapId;
},
getComponentList: function() {
return this.componentList;
},
setTabTitle: function(componentId, title) {
// Not sure if this works, don't know for sure how to set a tab title
var me = this;
if(me.isTabComponent(componentId)) {
Ext.getCmp(me.tabComponents[componentId].tabId).tabBar.items.getAt(me.tabComponents[componentId].tabNo).setText(title);
}
},
isTabComponent: function(componentId) {
var me = this;
return Ext.isDefined(me.tabComponents[componentId]);
},
showStartupPopup: function() {
this.popupWin.show();
},
hideStartupPopup: function() {
this.popupWin.hide();
},
resizeLayout: function(continueFunction) {
var me = this;
if(Ext.isWebKit) {
// Webkit bug
me.mainLayoutContainer.setHeight(me.getContainerheight());
}
me.mainLayoutContainer.doLayout();
setTimeout(function(){
if(continueFunction != undefined){
continueFunction();
}
viewerController.mapComponent.getMap().updateSize();
},200);
}
});
<file_sep>/viewer/minify/build.xml
<project name="viewer-html" default="minify" basedir=".">
<!-- http://code.google.com/p/closure-compiler/wiki/BuildingWithAnt -->
<property name="minify.outputdir" value="${basedir}/build/web/viewer-html/"/>
<property name="viewerhtml.path" value="${basedir}/web/viewer-html"/>
<target name="minify" description="Minify source JavaScript files with Closure Compiler">
<taskdef name="jscomp" classname="com.google.javascript.jscomp.ant.CompileTask" classpath="../libs/GoogleClosureCompiler/compiler.jar"/>
<jscomp output="${minify.outputdir}/viewer-min.js"
compilationLevel="simple" prettyPrint="true" printInputDelimiter="true" debug="false">
<sources dir="${viewerhtml.path}/common/viewercontroller">
<file name="ViewerController.js"/>
<file name="MapComponent.js"/>
</sources>
<sources dir="${viewerhtml.path}/components">
<file name="Component.js"/>
<file name="LogMessage.js"/>
<file name="Logger.js"/>
<file name="DataSelectionChecker.js"/>
</sources>
<sources dir="${viewerhtml.path}/common">
<file name="overrides.js"/>
<file name="ScreenPopup.js"/>
<file name="CQLFilterWrapper.js"/>
<file name="MobileSlider.js"/>
<file name="Combobox.js"/>
<file name="MobileCombobox.js"/>
</sources>
<!-- server-side Ajax wrappers -->
<sources dir="${viewerhtml.path}/common/ajax">
<file name="ServiceInfo.js"/>
<file name="CSWClient.js"/>
<file name="FeatureService.js"/>
<file name="SLD.js"/>
<file name="Bookmark.js"/>
<file name="LayerSelector.js"/>
<file name="CombineImage.js"/>
<file name="FeatureInfo.js"/>
<file name="EditFeature.js"/>
<file name="ArcQueryUtil.js"/>
<file name="Twitter.js"/>
</sources>
<!-- abstract MapComponent -->
<sources dir="${viewerhtml.path}/common/viewercontroller/controller">
<file name="Map.js"/>
<file name="Layer.js"/>
<file name="TilingLayer.js"/>
<file name="WMSLayer.js"/>
<file name="ImageLayer.js"/>
<file name="VectorLayer.js"/>
<file name="ArcLayer.js"/>
<file name="Feature.js"/>
<file name="MapTip.js"/>
<file name="Extent.js"/>
<file name="Event.js"/>
<file name="Tool.js"/>
<file name="Component.js"/>
<file name="ToolMapClick.js"/>
</sources>
</jscomp>
<jscomp output="${minify.outputdir}/flamingo-min.js"
compilationLevel="simple" prettyPrint="true" printInputDelimiter="true" debug="false" >
<sources dir="${viewerhtml.path}/common/viewercontroller/flamingo">
<file name="FlamingoLayer.js"/>
<file name="FlamingoArcLayer.js"/>
<file name="FlamingoArcServerLayer.js"/>
<file name="FlamingoArcIMSLayer.js"/>
<file name="FlamingoWMSLayer.js"/>
<file name="FlamingoVectorLayer.js"/>
<file name="FlamingoMap.js"/>
<file name="FlamingoTool.js"/>
<file name="FlamingoImageLayer.js"/>
<file name="FlamingoTilingLayer.js"/>
<file name="ToolMapClick.js"/>
<file name="FlamingoComponent.js"/>
<file name="FlamingoMapComponent.js"/>
</sources>
<sources dir="${viewerhtml.path}/common/viewercontroller/flamingo/components">
<file name="Overview.js"/>
</sources>
<sources dir="${viewerhtml.path}/common/viewercontroller/flamingo/tools">
<file name="JSButton.js"/>
</sources>
</jscomp>
<jscomp output="${minify.outputdir}/openlayers-min.js"
compilationLevel="simple" prettyPrint="true" printInputDelimiter="true" debug="false">
<sources dir="${viewerhtml.path}/common/viewercontroller/openlayers">
<file name="OpenLayersLayer.js"/>
<file name="OpenLayersArcLayer.js"/>
<file name="OpenLayersArcIMSLayer.js"/>
<file name="OpenLayersArcServerLayer.js"/>
<file name="OpenLayersWMSLayer.js"/>
<file name="OpenLayersVectorLayer.js"/>
<file name="OpenLayersImageLayer.js"/>
<file name="OpenLayersTilingLayer.js"/>
<file name="OpenLayersTool.js"/>
<file name="OpenLayersMap.js"/>
<file name="Utils.js"/>
<file name="ToolMapClick.js"/>
<file name="OpenLayersComponent.js"/>
<file name="OpenLayersMapComponent.js"/>
</sources>
<sources dir="${viewerhtml.path}/common/viewercontroller/openlayers/components">
<file name="LoadingPanel.js"/>
<file name="OpenLayersBorderNavigation.js"/>
<file name="OpenLayersLoadMonitor.js"/>
<file name="OpenLayersOverview.js"/>
<file name="OpenLayersMaptip.js"/>
</sources>
<sources dir="${viewerhtml.path}/common/viewercontroller/openlayers/tools">
<file name="OpenLayersIdentifyTool.js"/>
<file name="OpenLayersDefaultTool.js"/>
</sources>
</jscomp>
</target>
<target name="minify-clean">
<delete file="${minify.outputdir}/viewer-min.js"/>
<delete file="${minify.outputdir}/flamingo-min.js"/>
<delete file="${minify.outputdir}/openlayers-min.js"/>
</target>
</project>
| 185eedffc0a4fd75b3492747ed741a96175c8028 | [
"JavaScript",
"Ant Build System"
]
| 2 | JavaScript | cvanlith/flamingo | af48d19803a7ca9a647749a8a88ef21eda3e2719 | 78439763460c000d57488f9b4aaadc5a2fef6354 |
refs/heads/master | <file_sep>import convertDate from '@/DynamicProperty/dateFormat.js'
const convertDateDetailSection = (schema,model, isDBConvert) =>{
if(schema.length > 0){
schema.forEach(element => {
if(element.type == "date"){
model.forEach(e => {
e[element.model] = convertDate(e[element.model],isDBConvert);
});
}
});
}
}
export default convertDateDetailSection;<file_sep>//Get Cal culation formulas
function returnFormula(Formulas) {
var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];
var tokens = Formulas.split(new RegExp(separators.join('|'), 'g'));
var FieldCtrls = '';
for (var i = 0; i < tokens.length; i++) {
if (tokens[i] != "" && tokens[i].substring(0, 1) == '#') {
FieldCtrls = FieldCtrls + tokens[i].substring(0, tokens[i].length - 1) + ',';
Formulas = Formulas.replace(tokens[i], "parseFloat($('" + tokens[i].substring(0, tokens[i].length - 1) + "').val())");
}
}
if (FieldCtrls != '') {
FieldCtrls = FieldCtrls.substring(0, FieldCtrls.length - 1);
return FieldCtrls + '^' + Formulas;
}
}<file_sep>import axios from 'axios';
const axiosInstance = axios.create();
/**
*
*/
axiosInstance.interceptors.request.use(
config => {
return config;
},
error => {
// eslint-disable-line
// TODO: Do something with request error
return Promise.reject(error);
}
);
/**
*
*/
axiosInstance.interceptors.response.use(
response => {
// eslint-disable-line
// TODO: Do something before request is sent
return response;
},
error => {
// eslint-disable-line
// TODO: Do something with request error
return Promise.reject(error);
}
);
const fetchRequester = async ({ method, url, data }) => {
console.log('method:', method)
console.log('url:', url)
console.log('data:', data)
const response = await axiosInstance.request({
url,
method,
data,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'dbname': localStorage.getItem('dataBaseName') || '',
'dbusername':localStorage.getItem('dbusername') || '',
'dbpassword':localStorage.getItem('dbpassword') || '',
'dbserver':localStorage.getItem('dbserver') || ''
}
});
return response;
};
export default fetchRequester;<file_sep>
export default function ConvertNumber2Word(Value, Type) // Type 1 For American Style of format and 0 For Indian Style of Format
{
if (Type == 0) { return AmountInWordsINR(Value); } else { return toWords(Value); }
}
// American Numbering System
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function toWords(s) {
s = s.toString(); s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.');
if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split('');
var str = ''; var sk = 0; for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' '; i++; sk = 1;
}
else if (n[i] != 0) {
str += tw[n[i] - 2] + ' '; sk = 1;
}
}
else if (n[i] != 0) {
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'hundred '; sk = 1;
} if ((x - i) % 3 == 1) { if (sk) str += th[(x - i - 1) / 3] + ' '; sk = 0; }
}
if (x != s.length) {
var y = s.length; str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
return str.replace(/\s+/g, ' ');
}
function AmountInWordsINR(value) {
var junkVal = value;
junkVal = Math.floor(junkVal);
var obStr = new String(junkVal);
var numReversed = obStr.split("");
var actnumber = numReversed.reverse();
if (Number(junkVal) >= 0) {
//do nothing
}
else {
// alert('wrong Number cannot be converted');
return false;
}
if (Number(junkVal) == 0) {
document.getElementById('container').innerHTML = obStr + '' + 'Rupees Zero Only';
return false;
}
if (actnumber.length > 10) {
alert('Oops!!!! the Number is too big to covertes');
return false;
}
var iWords = ["Zero", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine"];
var ePlace = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
var tensPlace = ['dummy', ' Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];
var iWordsLength = numReversed.length;
var totalWords = "";
var inWords = new Array();
var finalWord = "";
var j = 0;
for (var i = 0; i < iWordsLength; i++) {
switch (i) {
case 0:
if (actnumber[i] == 0 || actnumber[i + 1] == 1) {
inWords[j] = '';
}
else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + ' Only';
break;
case 1:
tens_complication();
break;
case 2:
if (actnumber[i] == 0) {
inWords[j] = '';
}
else if (actnumber[i - 1] != 0 && actnumber[i - 2] != 0) {
inWords[j] = iWords[actnumber[i]] + ' Hundred and';
}
else {
inWords[j] = iWords[actnumber[i]] + ' Hundred';
}
break;
case 3:
if (actnumber[i] == 0 || actnumber[i + 1] == 1) {
inWords[j] = '';
}
else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] != 0 || actnumber[i] > 0) {
inWords[j] = inWords[j] + " Thousand";
}
break;
case 4:
tens_complication();
break;
case 5:
if (actnumber[i] == 0 || actnumber[i + 1] == 1) {
inWords[j] = '';
}
else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] != 0 || actnumber[i] > 0) {
inWords[j] = inWords[j] + " Lakh";
}
break;
case 6:
tens_complication();
break;
case 7:
if (actnumber[i] == 0 || actnumber[i + 1] == 1) {
inWords[j] = '';
}
else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + " Crore";
break;
case 8:
tens_complication();
break;
default:
break;
}
j++;
}
function tens_complication() {
if (actnumber[i] == 0) { inWords[j] = ''; }
else if (actnumber[i] == 1) { inWords[j] = ePlace[actnumber[i - 1]]; }
else { inWords[j] = tensPlace[actnumber[i]]; }
}
inWords.reverse();
for (i = 0; i < inWords.length; i++) { finalWord += inWords[i]; }
return finalWord;
}
<file_sep>
const convertDate = (value, isDBConvert ) =>{
if(!value || value== '') return '';
if(isDBConvert){
const [day, month, year] = value.split('/')
return `${month}/${day}/${year}`
} else{
let newValue = value.split('T');
if(newValue[0]== '1900-01-01'){
return '';
}
let date = new Date(newValue[0]).toISOString().substr(0, 10)
const [year, month, day] = date.split('-')
return `${day}/${month}/${year}`
}
}
export default convertDate;<file_sep>
import VueFormGenerator from 'vue-form-generator'
import ConvertNumber2Word from '@/DynamicProperty/NumberToWords.js'
const updateModalAfterChangeMaster = (schemas,model) =>{
var tempSchema = schemas;
if(tempSchema.length >0){
tempSchema.forEach(p =>{
if(p.formula !=""){
var Formula = p.formula.trim();
var SVTCOLSUM = 'SVTCOLSUM', SVTCOLSUMGROUP = 'SVTCOLSUMGROUP', SVTAMTINWORDS = 'SVTAMTINWORDS', SVTROUND50 = 'SVTROUND50', SVTROUND100 = 'SVTROUND100', SVTROUND2 = 'SVTROUND2';
var SVTROUNDOFFAMT = 'SVTROUNDOFFAMT', SVTCOLAVG = 'SVTCOLAVG', SVTGETGRIDDATA = 'SVTGETGRIDDATA';
var formulaSplit = Formula.split("(");
if (Formula.substring(0, 1) == '#' || Formula.substring(0, 1) == '(') {
var FieldData = returnFormula(Formula,model).split('^');
Formula = FieldData[1];
// alert(Formula);
//alert(JSON.stringify(FieldData));
var ouput;
try{
ouput = eval(Formula);
}catch(e){
ouput =0;
}
model[p.model]= parseFloat(ouput.toFixed(2));
} else{
if (formulaSplit[0].toString().trim() == SVTCOLAVG) {
try {
var k = 0, AvgValue = 0
Formula = Formula.replace(SVTCOLAVG, '');
Formula = Formula.substr(2) //Remove first character from string
Formula = Formula.substr(0, Formula.length - 2) //Remove last character from string
detailSectionData.forEach( function(value, i){
for(var key in value){
if(key == Formula){
AvgValue = AvgValue + parseFloat(value[key]);
k = k + 1;
}
}
});
model[p.model]= (AvgValue / k).toFixed(2);
} catch (ex) { }
}else if (formulaSplit[0].trim() == SVTROUND50) {
Formula = Formula.replace(SVTROUND50, '');
FieldData = returnFormula(Formula,model).split('^');
Formula = FieldData[1];
model[p.model]= Math.round(eval(Formula)).toFixed(2).toString();
}
else if (formulaSplit[0].trim() == SVTROUND100) {
Formula = Formula.replace(SVTROUND100, '');
FieldData = returnFormula(Formula,model).split('^');
Formula = FieldData[1];
model[p.model]= Math.ceil(eval(Formula)).toFixed(2);
}
else if (formulaSplit[0].trim()== SVTROUND2) {
Formula = Formula.replace(SVTROUND2, '');
FieldData = returnFormula(Formula,model).split('^');
Formula = FieldData[1];
model[p.model]= parseFloat(eval(Formula).toFixed(2));
}
else if (formulaSplit[0].trim() == SVTROUNDOFFAMT) {
Formula = Formula.replace(SVTROUNDOFFAMT, '');
FieldData = returnFormula(Formula,model).split('^');
Formula = FieldData[1]; var roundOffAmt = eval(Formula).toFixed(0) - eval(Formula).toFixed(2);
model[p.model]= parseFloat(roundOffAmt.toFixed(2));
}
else if (formulaSplit[0].toString() == 'SVTCURDATE') {
model[p.model] = '' + getCurrentDate();
}
else if (formulaSplit[0].toString() == 'SVTCURTIME') {
model[p.model] = '' + getTimeZone();
}
else if (formulaSplit[0].toString() == 'SVTFYF') {
model[p.model] = '' + getFinYears(1); /*Financial year start year like 01/04/2014 returns 14*/
}
else if (formulaSplit[0].toString() == 'SVTFYT') {
model[p.model] = '' + getFinYears(2); /*Financial year end year like 31/03/2015 returns 15*/
}
}
}
//check load from query field data
if(p.loadFromQuery != "" && callQueries){
let fieldName = p.loadFromQuery.split(".");
let itemCode = "";
let party = selectedParty;
if(fieldName[0] == "i" || fieldName[0] == "g" || fieldName[0] == "u"){
if(detailModal["ITEMCODE"] != ""){
itemCode= detailModal["ITEMCODE"];
} else{
itemCode= "000";
}
}
if(fieldName[0] == "s"){
itemCode="s";
}
if(fieldName[0] == "c"){
itemCode="c";
}
//reduce call if modal not empty
let modelData = "";
modelData = model[p.model];
if(itemCode != "" && itemCode != "000" && itemCode && party && modelData == ""){
httpClient({
method: 'GET',
url: `${process.env.VUE_APP_API_BASE}loadDataFromQuery?fieldName=${p.loadFromQuery}&itemCode=${itemCode}&selectedParty=${party}`,
})
.then((result) => {
model[p.model]= result.data.fieldValue;
console.log('load from query'+ result.data.fieldValue);
}).catch((err) => {
console.log('error gettting data from load field by query');
});
}
}
if(p.pickUpQuery != ""){
let pickUpField = "";
let query = p.pickUpQuery;
pickUpField = model[p.pickUpAfterField];
//replace value in query
let myRegExp = new RegExp('#'+p.pickUpAfterField+'#','ig');
query = query.replace(myRegExp,pickUpField);
query = query.replace(/\`/g,"'");
console.log('pickup query= '+query);
if(pickUpField !=""){
httpClient({
method: 'GET',
url: `${process.env.VUE_APP_API_BASE}loadDataFromQuery?&query=${query}`,
})
.then((result) => {
model[p.model] = result.data.fieldValue;
console.log('load from pickup query'+ result.data.fieldValue);
}).catch((err) => {
console.log('error gettting data from load field by query');
});
}
}
});
}
return false;
}
//Get Cal culation formulas
function returnFormula(Formulas,model) {
var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];
var tokens = Formulas.trim().split(new RegExp(separators.join('|'), 'g'));
var FieldCtrls = '';
for (var i = 0; i < tokens.length; i++) {
if (tokens[i] != "" && tokens[i].substring(0, 1) == '#') {
FieldCtrls = FieldCtrls + tokens[i].substring(0, tokens[i].length - 1).replace('#','').toUpperCase() + ',';
let fieldProperty =tokens[i].substring(0, tokens[i].length - 1).replace('#','').toUpperCase();
if(model.hasOwnProperty(fieldProperty)){
Formulas = Formulas.replace(tokens[i], model[fieldProperty]);
}
}
}
if (FieldCtrls != '') {
FieldCtrls = FieldCtrls.substring(0, FieldCtrls.length - 1);
return FieldCtrls + '^' + Formulas;
}
}
//Get System Current Date (dd MMM yyyy)
function getCurrentDate() {
var current_date = new Date();
var month_value = current_date.getMonth();
var day_value = current_date.getDate();
var year_value = current_date.getFullYear();
return day_value + '/' + (month_value + 1) + '/' + year_value;
}
//get client time
function getTimeZone() {
var localTime = new Date();
var hours = localTime.getHours();
var minutes = localTime.getMinutes();
var seconds = localTime.getSeconds();
return hours + "." + minutes + "." + seconds;
}
//get client system seconds from time
function getTimeStamp() { var localTime = new Date(); return localTime; }
//get client system seconds from time for auto save in cookies add seconds based on client settings
function getTimeStampForAutoSave() { var localTime = new Date(); localTime.setSeconds(localTime.getSeconds() + parseInt($.session.get(Session_AutoSaveInSeconds))); return localTime; }
/*Get Financila Year Start Year and End Year*/
function getFinYears(flag) {
switch (flag) {
case 1: /*Financial year start year like 01/04/2014 returns 14*/
var FromFinalYear = $.session.get(Session_FromYear).split("/");
if (FromFinalYear.length > 0) { return FromFinalYear[2].slice(-2) } else { return "" }
break;
case 2: /*Financial year end year like 31/03/2015 returns 15*/
var ToFinalYear = $.session.get(Session_ToYear).split("/");
if (ToFinalYear.length > 0) { return ToFinalYear[2].slice(-2) } else { return "" }
break;
}
}
export default updateModalAfterChangeMaster;<file_sep>const generateNewModal = (schemas, model) => {
var tempSchema = schemas;
var newModal = [];
tempSchema.forEach(element => {
if(element.default== true || element.inputType == "number" || element.inputType == "numberList"){
if(element.inputType == "number" || element.inputType == "numberList" && (element.useStdDefault == "" || element.useStdDefault == null)){
model[element.model] = 0;
}else{
if(element.inputType == "number" && (element.useStdDefault != "" || element.useStdDefault != null)){
model[element.model]= +element.useStdDefault;
} else{
model[element.model]= element.useStdDefault;
}
}
}
});
return model;
};
export default generateNewModal;<file_sep>import convertDate from '@/DynamicProperty/dateFormat.js'
const convertDateWithSchema = (schema, model, isDBConvert) =>{
if(schema.length > 0){
schema.forEach(element => {
if(element.type == "date"){
model[element.model] = convertDate(model[element.model],isDBConvert);
}
});
}
}
export default convertDateWithSchema; | 718ddf37367c58968f85d81d6e94407bfb7d2f24 | [
"JavaScript"
]
| 8 | JavaScript | anilkarwa/Vfactic-pwa | 8a03e1024bfa47402704d44022cd46d0b40e0529 | 251aee037aa7727d020336818a42429274df579e |
refs/heads/master | <repo_name>mkmanges/my-gatsby-website<file_sep>/src/components/Overpriced/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Overpriced extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.banker__header}
title="Open for details"
>
Overpriced Associates Degree <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
I moved to Arizona in 1999 during what turned out to be a tech bubble. Investors were lining up to throw money at companies that generated zero revenue and those companies were hiring anyone with a pulse and a little computer knowledge. I had the former and decided it might be a good idea to get some of the latter, so I enrolled in an overpriced school offering an Associates degree in IT and Computer Networking in only 15 months.
</p>
<p>
I did finish this program while working a full-time overnight shift. It was difficult but I am proud of my effort. However, if I had it to do over, I would have put those resources into finishing my B.S. degree at Arizona State University.
</p>
<p>
By the way, that tech bubble burst about 4 months before I finished the program. I refuse to say that education is ever a waste of time but that program cost a <em>lot</em> of money and the only jobs offered to me paid about 30% less than I was making at the job I already had.
</p>
</ToggleDisplay>
</div>
)
}
}
export default Overpriced<file_sep>/src/components/DevEd/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class DevEd extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.banker__header}
title="Open for details"
>
Frontend Development Education <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
My learning approach has been simple. Stay focused. It's really easy to get distracted by the next new, shiny thing in web development, especially when I run into a difficult challenge. I have refused to let myself get distracted to avoid hard challenges. Instead, I force myself to stay on topic until the challenge has been overcome. At times this approach has caused much weeping and gnashing of teeth but it has paid great dividends. <em>I'm looking at you, JavaScript.</em>
</p>
<blockquote>
<p>The only true wise man is a man who knows that he knows nothing.</p>
<p>- Socrates</p>
</blockquote>
<p>
At times I must be really wise because front end development makes me feel like I know nothing. But then there are times when I overcome yet another obstacle and I think to myself, <em>maybe I can do this</em>.
</p>
<br/>
<p><strong>My Learning Path</strong></p>
<p>
I didn't begin studying as a total <em>noob</em>. Back in 2013 I managed to hand-code a photography portfolio site. It was a single page responsive site that was all of 3 files: 1 HTML file, 1 CSS file, and 1 JavaScript file. I was very proud of that site; for two years it was probably my best photography saleman. But that was several years ago...
</p>
<p>
I began where so many begin. FreeCodeCamp. Codecademy. Udacity. I followed along with the training videos and did the projects. I found them all useful for introducing a foundation of coding knowledge. When my family went home last summer, I stayed behind for a month to focus on the JavaScript section in FreeCodeCamp. That was a rough month. I was away from my family for the first time and I was struggling through arrays, objects, and functions. But it was time well spent.
</p>
<p>
I began to notice a problem with this approach to learning. When following along with a video or tutorial I was able to understand what was happening. But when I tried to build something on my own, I was lost. I could see that I needed to get away from watching other people code and start struggling through my own projects, regardless of their triviality. For example, to better understand Vue I created a <em>Rock Paper Scissors</em> game using Vuex for state management. At the time I didn't realize that this was a really common thing to build. No matter. I had to refer to the documentation a lot but in the end my understanding had grown by leaps and bounds. To learn Node.js and Express I built the first version of a <em>Recipe Box</em> app for Kelly. Again, my understanding took off. It's been fun to look back and see how far I've come.
</p>
<br/>
<p><strong>My Excellent Skills</strong></p>
<p>
HTML5, CSS3, FLEXBOX
</p>
<p><strong>My Fluent Skills</strong></p>
<p>
JAVASCRIPT (ES6), REACT, VUE, JAMSTACK, WEBPACK, EXPRESS, SASS, CSS GRID, PUG/JADE, GIT
</p>
<p><strong>My Novice Skills</strong></p>
<p>
NODE, NPM, MONGODB, GRAPHQL
</p>
<br/>
<p><strong>What's Next?</strong></p>
<p>
The more I learn, more I see that I have barely scratched the frontend development surface. I will continue to build new projects, read documentation, and experiment. At this point, I think that a job as a frontend developer would really fuel my learning and take my knowledge to the next level.
</p>
<br/>
<p><strong>Things I Plan To Learn</strong></p>
<p>
<ul>
<li>GraphQL</li>
<li>CSS Animations</li>
<li>Databases</li>
<li>Algolia Search</li>
<li>SVG Images</li>
</ul>
</p>
</ToggleDisplay>
</div>
)
}
}
export default DevEd<file_sep>/src/components/Dicing/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Dicing extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.dicing__header}
title="Open for details"
>
Dicing Saw Operator <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
When I began this job, the company was small and privately owned. I worked a full-time overnight shift while attending school full-time during the day. We made ultrasonic transducers--those devices you think of when a woman has an ultrasound of her unborn baby. In fact, the company founder had invented a production technique that at the time made our product cutting edge. It was the first 3-D ultrasound.
</p>
<p>
After almost a year, our company merged with GE Medical Systems. Until this point, the atmosphere was relaxed and I knew everyone. It felt like a family. After the merge, that changed. Everything became driven by numbers.
</p>
<p><strong>What I Learned</strong></p>
<ul>
<li>I <em>really</em> enjoy training/teaching people. My first opportunity to be a trainer came about when a new team member needed to be trained. No one else was interested, so I volunteered... and I loved it. There is nothing like seeing the proverbial light come on for someone.</li>
<li>When I started, I saw this position as temporary. When I finished school, I would be leaving. Since I did not intend to stay long-term, it did not seem right to me at the time to take any promotions. So right up front I indicated this. Now I realize this was a mistake and it cost me opportunites. I should never predetermine my future.</li>
<li>We had a diverse team and no one really gave it much thought. Everyone worked at getting along and everyone did their job well. It was a great group of people to work with.</li>
<li>Our team was much more productive when we were a private company. The manager was hands-off but there when we needed him. He trusted us to be adults and to do our job. </li>
<li>If given the choice to work for a small, private company or a large corporation, I would most likely choose the small company.</li>
</ul>
</ToggleDisplay>
</div>
)
}
}
export default Dicing<file_sep>/src/components/Experience/index.jsx
import React from 'react'
import style from './index.module.scss'
import ReactLogo from '../../assets/icons/react-logo.png'
const Experience = (props) => (
<section className={style.exp}>
<img
src={props.logo}
alt="logo"
className={style.logo}
/>
<h3 className={style.tool}>{props.tool}</h3>
<p className={style.skill}>{props.level}</p>
</section>
)
export default Experience<file_sep>/gatsby-node.js
const path = require('path');
const slash = require('slash');
const {
createPaginationPages,
createLinkedPages,
prefixPathFormatter,
} = require('gatsby-pagination');
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators;
return new Promise((resolve, reject) => {
const postTemplate = path.resolve(`src/templates/blog-post.jsx`);
const blogTemplate = path.resolve(`src/templates/blog.jsx`);
graphql(`
{
allContentfulBlogPost {
edges {
node {
id
title
slug
content {
id
content
}
date
heroImage {
id
file {
url
}
}
authorInfo {
id
name
photo {
id
file {
url
}
}
}
}
}
}
}
`).then((result) => {
if (result.errors) {
console.error(result.errors);
}
// create blog.js page that passes pathContext props to blog-post.js
createPaginationPages({
createPage,
edges: result.data.allContentfulBlogPost.edges,
component: slash(blogTemplate),
pathFormatter: prefixPathFormatter("/blog"),
limit: 10,
});
// create page for each blog post when title is clicked
createLinkedPages({
createPage,
edges: result.data.allContentfulBlogPost.edges,
component: slash(postTemplate),
edgeParser: edge => ({
path: `/blog/${edge.node.slug}`,
context: {
slug: edge.node.slug,
},
}),
circular: true,
});
resolve();
});
});
};
<file_sep>/src/components/BusinessImages/index.jsx
import React from 'react';
import style from './index.module.scss';
const BusinessImages = () => (
<div className={style.images}>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/hospital.jpg`}
alt="Oasis Hospital in Al Ain, UAE"
className={style.images__business}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/group.jpg`}
alt="Customer service group"
className={style.images__business}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/doctor.jpg`}
alt="Headshot of female doctor"
className={style.images__business}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/sign.jpg`}
alt="Sign for Oasis Hospital in Al Ain, UAE"
className={style.images__business}
/>
</div>
);
export default BusinessImages;
<file_sep>/src/components/PortraitImages/index.jsx
import React from 'react';
import style from './index.module.scss';
const PortraitImages = () => (
<div className={style.images}>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/man.jpg`}
alt="Man posing on sand dune"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/jumping.jpg`}
alt="Man jumping in air throwing sand"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/couple.jpg`}
alt="Couple posing together in front of mountain"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1518983987/mysite/memories.jpg`}
alt="Backlight family posing in front of colorful sunset"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1519026501/mysite/family-8.jpg`}
alt="Three young boys smiling"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1519026501/mysite/couple-15.jpg`}
alt="Couple on a carpet in the desert"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1519026501/mysite/desert-couple.jpg`}
alt="Couple holding hands in desert"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1519026501/mysite/throwing-sand.jpg`}
alt="Man throwing sand in desert"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/woman.jpg`}
alt="Woman in blue dress lying on desert sand"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1519026501/mysite/family-5.jpg`}
alt="Family in desert with long shadows"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1519026501/mysite/family-2.jpg`}
alt="Family in desert"
className={style.images__portrait}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/f_auto/v1518983990/mysite/Derwin.jpg`}
alt="Young man wearing a hat"
className={style.images__portrait}
/>
</div>
);
export default PortraitImages
;<file_sep>/src/components/Tech/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Tech extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.tech__header}
title="Open for details"
>
In-home Computer Tech <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
Do you remember the electronics retailer, Circuit City? They have been defunct for over a decade and rightly so. I left the company about 4 months before they closed up shop and, to put it mildly, they were a dumpster fire. I was hired to be a <em>Firedog</em> which was their version of BestBuy's <em>Geek Squad</em>.
</p>
<p>
The manager of the computer department was a bald guy named Scott who literally could not connect his laptop to the wifi. Everyday he asked me to do it for him. One of the services we offered was in-home computer setup. That meant unpackaging all the hardware, connecting it (neatly), doing basic configurations, and installing extra software like antivirus and Microsoft Office. The package description also indicated some basic computer training once everything was up and running. Back then it took about 20 minutes just to install the drivers for an HP printer. Scott seemed to think all this should take 30 minutes. Maybe 35 if you go slow.
</p>
<p><strong>What I Learned</strong></p>
<ul>
<li>Don't just give lip service to things like customer service and employee loyalty.</li>
<li>I worked in the store on a Black Friday and it was one of the worst experiences of my life. <em>Black Friday comes straight from the pits of hell</em>.</li>
</ul>
</ToggleDisplay>
</div>
)
}
}
export default Tech<file_sep>/src/pages/webdev.jsx
import React from 'react';
import style from '../styles/webdev.module.scss';
import Experience from '../components/Experience';
import Project from '../components/Project';
import ReactLogo from '../assets/icons/react-logo.png';
import JS from '../assets/icons/js-logo.png';
import ES6 from '../assets/icons/es6-logo.png';
import CSS3 from '../assets/icons/css-logo.png';
import GraphQLLogo from '../assets/icons/graphql-logo.png';
import GraphCMS from '../assets/icons/graphcms-logo.png';
import HTMLLogo from '../assets/icons/html-logo.png';
import JAM from '../assets/icons/jamstack-logo.png';
import NodeJS from '../assets/icons/node-logo.png';
import NPM from '../assets/icons/npm-logo.png';
import Photoshop from '../assets/icons/photoshop-logo.png';
import Illustrator from '../assets/icons/illustrator-logo.png';
import Vue from '../assets/icons/vue-logo.png';
import Webpack from '../assets/icons/webpack-logo.png';
import Gatsby from '../assets/icons/gatsby-logo.png';
import CSSGrid from '../assets/icons/css-grid-logo.png';
import Mongo from '../assets/icons/mongodb-logo.png';
import Express from '../assets/icons/express-logo.png';
import Pug from '../assets/icons/pug-logo.png';
import SASS from '../assets/icons/sass-logo.png';
import Contentful from '../assets/icons/contentful-logo.png';
import Netlify from '../assets/icons/netlify-logo.png';
const Webdev = () => (
<div className={style.body}>
<section className={style.about}>
<h2 className={style.about__heading}>Frontend Development Skills</h2>
<p><em><strong>#LearningByDoing</strong></em></p>
<p>
I have read official documentation, countless blogs, and followed along with numerous training videos on my way to becoming a Frontend Developer. But at the end of the day, nothing increases my understanding of any concept like rolling up my sleeves and attempting a project without a safety net.
</p>
<p>My intention to learn Frontend Development began in June 2017 after three years as the IT Manager for a Dubai sports training and retail startup. I am proud of how far I've come in a short time but I still have a lot to learn. Of course, this is web development so I will <em>always</em> have a lot to learn!</p>
</section>
<h2>Technology I'm Learning</h2>
<section className={style.experience}>
<Experience
logo={JS}
tool="JavaScript"
level="Fluent"
/>
<Experience
logo={ReactLogo}
tool="React"
level="Fluent"
/>
<Experience
logo={ES6}
tool="ES6"
level="Fluent"
/>
<Experience
logo={CSS3}
tool="CSS3"
level="Excellent"
/>
<Experience
logo={GraphQLLogo}
tool="GraphQL"
level="Novice"
/>
<Experience
logo={Contentful}
tool="Contentful"
level="Fluent"
/>
<Experience
logo={HTMLLogo}
tool="HTML"
level="Excellent"
/>
<Experience
logo={JAM}
tool="JAMstack"
level="Fluent"
/>
<Experience
logo={NodeJS}
tool="Node.js"
level="Novice"
/>
<Experience
logo={NPM}
tool="NPM"
level="Novice"
/>
<Experience
logo={Photoshop}
tool="Photoshop"
level="Excellent"
/>
<Experience
logo={Illustrator}
tool="Illustrator"
level="Fluent"
/>
<Experience
logo={Vue}
tool="Vue"
level="Fluent"
/>
<Experience
logo={Webpack}
tool="Webpack"
level="Fluent"
/>
<Experience
logo={Gatsby}
tool="Gatsby"
level="Fluent"
/>
<Experience
logo={CSSGrid}
tool="CSS Grid"
level="Fluent"
/>
<Experience
logo={Mongo}
tool="MongoDB"
level="Novice"
/>
<Experience
logo={Express}
tool="ExpressJS"
level="Fluent"
/>
<Experience
logo={Pug}
tool="Pug"
level="Fluent"
/>
<Experience
logo={SASS}
tool="SASS"
level="Fluent"
/>
<Experience
logo={Netlify}
tool="Netlify"
level="Fluent"
/>
<Experience
logo={GraphCMS}
tool="GraphCMS"
level="Fluent"
/>
</section>
<h2>Projects</h2>
<section className={style.projects}>
<Project
name="React Calculator"
url="https://react-calc-d042018.netlify.com/"
logos={[ReactLogo, JS, ES6, CSS3, Photoshop, NPM, Netlify]}
desc="A working calculator built using React. Includes button animation, keyboard input, pop up shortcut menu, and designed after an 'old school' calculator. This was NOT a tutorial project; everything is bespoke."
/>
<Project
name="ESL Educational Video Sharing Site"
url="https://misskellysvideos.netlify.com/"
logos={[JS, ReactLogo, SASS, ES6, Gatsby, CSS3, GraphQLLogo, Contentful, JAM, Photoshop, NPM, Netlify]}
desc="A real website for an ESL kindergarten teacher to share English videos with her students. Add new videos simply using Contentful CMS."
/>
<Project
name="michaelmanges.com"
url="https://www.michaelmanges.com"
logos={[JS, ReactLogo, SASS, ES6, Gatsby, CSS3, GraphQLLogo, Contentful, JAM, Photoshop, CSSGrid, NPM, Netlify]}
desc="My professional website and blog."
/>
<Project
name="Recipe Box"
url="https://github.com/mkmanges/recipe-box"
logos={[JS, NodeJS, ES6, Express, Pug, NPM, CSS3, SASS, Webpack, Mongo, HTMLLogo]}
desc="A personal project I made for my wife to store and search for recipes."
/>
<Project
name="Rock Paper Scissors"
url="https://mkmanges.github.io/rock-paper-scissors/"
logos={[JS, Vue, NPM, HTMLLogo, SASS, CSS3]}
desc="Personal project to learn Vue.js modules."
/>
<Project
name="Wikipedia Viewer"
url="https://mkmanges.github.io/wikipedia-viewer/"
logos={[JS, HTMLLogo, ES6, NPM, SASS, CSS3]}
desc="A FreeCodeCamp JavaScript API project."
/>
<Project
name="Chuck Norris Quote Machine"
url="https://mkmanges.github.io/chuck-norris-facts/"
logos={[JS, HTMLLogo, ES6, NPM, CSS3]}
desc="A FreeCodeCamp JavaScript API project."
/>
</section>
</div>
);
export default Webdev;
<file_sep>/src/components/Retail/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Retail extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.retail__header}
title="Open for details"
>
Retail Management <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
I spent a few years in management with a fast-paced, high volume company that rewarded hard work and results. This company is different from any other I worked for. For instance, if they implemented an idea that sounded good on paper but fell flat in practice, rather than blame the employees for failing to carry out their vision, they acknowledged that it was not working and scrapped the idea. I respected them so much for this.
</p>
<p><strong>What I Learned</strong></p>
<ul>
<li>Admitting that your idea is not working is not a sign of weakness. Throw that crazy idea out there but if it's not working, just own it and move on. Your employees will love you for it.</li>
<li>'Never Be Satisfied' is a great company motto. We can always do better. <em>However</em>, that motto should not prevent supervisors from giving positive feedback. Eventually, <em>never be satisfied</em> begins to feel like <em>never good enough</em>.</li>
<li>Good Results + Relationships > Great Results alone. When it came to results, I stood out from the crowd. In fact, I was one of the managers brought in to turn around struggling stores. But my rapid managerial rise only went so far. My supervisor confided that my results were stellar but that my people skills needed work. Even though at the time the idea had not yet gained mainstream traction, he was telling me that I need to improve my Emotional Intelligence. It was difficult to hear but he was right. </li>
</ul>
</ToggleDisplay>
</div>
)
}
}
export default Retail<file_sep>/src/templates/blog-post.jsx
import React from 'react';
import Link from 'gatsby-link';
import Markdown from 'react-markdown';
import shortid from 'shortid';
import style from '../styles/blog-post.module.scss';
import twitter from '../assets/icons/64-twitter.png';
import linkedin from '../assets/icons/64-linkedin.png';
import github from '../assets/icons/GitHub-Mark-64px.png';
class BlogPost extends React.Component {
render() {
const post = this.props.data.contentfulBlogPost;
const { next, prev } = this.props.pathContext;
const createTitlePrev = (slug) => {
const noBlog = slug.slice(6, prev.length);
const title = noBlog.replace(/-/g, ' ');
return title;
};
const createTitleNext = (slug) => {
const noBlog = slug.slice(6, next.length);
const title = noBlog.replace(/-/g, ' ');
return title;
};
const nextTitle = createTitleNext(next);
const prevTitle = createTitlePrev(prev);
return (
<div>
<div className={style.body__aboveHero}>
<div key={post.id} className={style.post__aboveHero}>
<p className={style.date}>{post.date}</p>
<h2 className={style.title}>{post.title}</h2>
</div>
</div>
<img
src={post.heroImage.file.url}
alt={post.title}
className={style.heroImage}
/>
<div className={style.body__belowHero}>
<div key={post.id} className={style.post}>
<div className={style.main}>
<Markdown
source={post.content.content}
className={style.content}
/>
<div className={style.authorSection}>
<p><strong>Let's connect!</strong></p>
<section>
<a href="https://twitter.com/decrepit_webdev" rel="noopener noreferrer" target="_blank" title="@decrepit_webdev"><img src={twitter} alt="Twitter logo" className={style.icons} /></a>
<a href="https://github.com/mkmanges" rel="noopener noreferrer" target="_blank" title="@mkmanges"><img src={github} alt="Github logo" className={style.icons} /></a>
<a href="https://www.linkedin.com/in/michaelmanges/" rel="noopener noreferrer" target="_blank" title="@michaelmanges"><img src={linkedin} alt="LinkedIn logo" className={style.icons} /></a>
</section>
</div>
<hr className={style.divider} />
<h5>Tags</h5>
<div className={style.tags}>
{post.tag.map(tag => (
<button key={shortid.generate()} className={style.tags__button}>{tag}</button>
))}
</div>
</div>
<div className={style.postNav}>
<div className={style.postNav__prev}>
<p className={style.prev}>← Previous Post</p>
<hr />
<Link to={prev} className={style.postNav__item}>{prevTitle}</Link>
</div>
<div className={style.postNav__next}>
<p className={style.next}>Next Post →</p>
<hr />
<Link to={next} className={style.postNav__item}>{nextTitle}</Link>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default BlogPost;
export const postQuery = graphql`
query readEachBlogPost(
$slug: String!
) {
contentfulBlogPost(
slug: { eq: $slug }
) {
id
title
slug
tag
content {
id
content
}
date(formatString: "MMM DD, YYYY")
heroImage {
id
file {
url
}
}
authorInfo {
id
name
photo {
id
file {
url
}
}
}
}
}
`;
<file_sep>/src/components/Startup/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Startup extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.startup__header}
>
IT Manager - Dubai Startup <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>For three years I had the title of IT Manager. But that was a loose title; I wore many hats.</p>
<ul>
<li>Graphic Designer</li>
<li>eCommerce Manager</li>
<li>Sports Photographer</li>
<li>Product Photographer</li>
<li>Marketing</li>
<li>Webmaster (for lack of a better term)</li>
<li>The Tech Guy</li>
</ul>
<p>Basically, I was the person handling anything technical and/or creative. Much of what I did was learned on the fly because someone had to do it. As I've heard is said in Japan when a job needs to be done, 'Why not me?'</p>
<p><strong>What I Learned</strong></p>
<ul>
<li>Communication is HUGE and bad communication destroys trust and morale. Several times I was ready to cut ties with this operation and the #1 reason was lack of communication. People feel valued when we make the effort to communicate with them!</li>
<li>Be wise. Do not work without a contract. I wanted to trust in good intentions but the so-called promise of future pay is not a salary. Protect yourself and get the terms in writing.</li>
<li>I picked up several new skills: basic design principles, Photoshop, Illustrator, product & sports photography, Shopify e-commerce platform, HTML/CSS, email marketing, working remotely, and how to do business with people from a variety of cultural backgrounds.</li>
<li>Negotation is a valuable skill. If I don't like the initial offer, make a counter offer. Be creative.</li>
</ul>
</ToggleDisplay>
</div>
)
}
}
export default Startup<file_sep>/src/pages/photography.jsx
import React from 'react';
import style from '../styles/photography.module.scss';
import ArtisticImages from '../components/ArtisticImages';
import BusinessImages from '../components/BusinessImages';
import PortraitImages from '../components/PortraitImages';
const Photography = () => (
<div>
<div className={style.hero}>
<h4 className={style.year}>Since 2011</h4>
<h1 className={style.h1}>Photography</h1>
<p className={style.byline}>Portraits • Business • Artistic</p>
</div>
<div className={style.body}>
<h2>Portraits</h2>
<p>Individual • Couples • Families</p>
<PortraitImages />
<h2>Artistic</h2>
<p>Some of My Favorite Work</p>
<ArtisticImages />
<h2>Business</h2>
<p>Make an Impression</p>
<BusinessImages />
</div>
</div>
);
export default Photography;
<file_sep>/src/layouts/index.jsx
import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import Header from '../components/Header'
import Footer from '../components/Footer'
import '../styles/styles.scss'
import icon32 from '../assets/logo/32-website-favicon.png'
const TemplateWrapper = ({ children, data }) => (
<div>
<Helmet
title="<NAME>"
meta={[
{ name: 'description', content: 'Web developer and photographer <NAME>' },
{ name: 'keywords', content: 'webdev, photography, gatsbyjs, reactjs, frontend, graphql, design, photo, photos' },
]}
link={[
{ rel: 'shortcut icon', type: 'image/png', href: `${icon32}` }
]}
/>
<Header
title={data.site.siteMetadata.title}
byline={data.site.siteMetadata.byline}
/>
<div>
{children()}
</div>
<Footer />
</div>
)
TemplateWrapper.propTypes = {
children: PropTypes.func,
}
export default TemplateWrapper
export const query = graphql`
query SiteInfo {
site {
siteMetadata {
title
byline
}
}
}
`
<file_sep>/src/components/Driver/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Driver extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.driver__header}
title="Open for details"
>
OTR Truck Driver <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
The most difficult job I've ever had? This one. I was an over-the-road truck driver. For me, that meant spending 2-4 weeks at a time sitting in a drivers seat inside a small moving box that sits 10 feet off the ground.
</p>
<p>
This job took a heavy mental toll on me. It was difficult to spend so much time alone with my thoughts. I've joked that I went crazy several times during my year+ of driving. Pardon the pun, but there was also a heavy physical toll--I got <em>really</em> fat while driving. And what would expect when you sit on your bum day after day eating fried truckstop food for every meal?
</p>
<p>
There are a few upsides to truck driving. I was able to scratch my travel itch by driving through 43 of the 50 states and Canada. And the pay was good.
</p>
<p><strong>What I Learned</strong></p>
<ul>
<li>We should have a lot more respect for truck drivers. They have a difficult and dangerous job.</li>
<li>I need to stay physcially active when I have a sedentary job. You know, like web development.</li>
</ul>
</ToggleDisplay>
</div>
)
}
}
export default Driver<file_sep>/src/pages/about.jsx
import React from 'react';
import style from '../styles/about.module.scss';
import CulturalLessons from '../components/CulturalLessons/index';
import ParentingLessons from '../components/ParentingLessons/index';
import Adulting from '../components/Adulting';
import Startup from '../components/Startup';
import Photographer from '../components/Photographer';
import Retail from '../components/Retail';
import Banker from '../components/Banker';
import Processor from '../components/Processor';
import Dicing from '../components/Dicing';
import Tech from '../components/Tech';
import Driver from '../components/Driver';
import College1 from '../components/College1';
import Overpriced from '../components/Overpriced';
import College2 from '../components/College2';
import DevEd from '../components/DevEd';
import Hiking from '../components/Hiking/index';
import Camping from '../components/Camping/index';
import Fishing from '../components/Fishing/index';
import RockHounding from '../components/RockHounding/index';
import Traveling from '../components/Traveling/index';
const About = () => (
<div className={style.body}>
<section className={style.short}>
<h2>The Short Story</h2>
<p>
I learned an important lesson about being genuine when my wife and I were just getting to know each other. We found ourselves on an overnight backpacking trip with mutual friends in the Superstition Mountains in Arizona. If you've ever been backpacking, you know that your hair gets messed up, your clothes are dirty, and, if you're like me, you might develop an odd smell. On that trip the normal dating pretenses were blown away and she saw a much closer version of the real me. For 30 miles, Kelly and I hiked and talked without the pretenses of looking and acting like the best versions of ourselves. The results? We were married in October 2001 and I feel like I married the same person I dated because we had been real with each other from the beginning.
</p>
<p>
If it's true that we are all our own brand, I want my brand to the real version of myself. Hair messed up. Clothes dirty. Me being a little smelly. In one word: <em>real</em>
</p>
</section>
<section className={style.long}>
<h2>TL;DR</h2>
<p>
I often hear myself telling my three sons that they need to learn from their mistakes. That is good advice for me, too. There are so many times I would love to go back in time so I could have a redo. Of course, I cannot but I can prevent history from repeating itself by learning from my mistakes. Below I'm going to share some of what my history has taught me.
</p>
</section>
<section className={style.today}>
<h3>Today</h3>
<p>
It seems like friends and family from home assume that my life is one adventure after another. After all, since 2009 my family and I have lived overseas in the United Arab Emirates. Living overseas has been fascinating for all the obvious reasons. We've been able to travel to London, Paris, Singapore, Seoul, Thailand, Oman, and Kuwait. Honestly, though, life is pretty routine. My wife is a kindergarten teacher for the Abu Dhabi government. Our three teenage sons are home schooled and take tennis lessons twice a week. Since June 2017, after ending a three year stint with a Dubai startup, I have been pinned to my laptop learning frontend web development. It's been 9 years since we moved to the Middle East and after this school year, we intend to complete our time here. The Arabic word is <em>khalas</em>.
</p>
<CulturalLessons />
<hr />
<ParentingLessons />
<hr />
<Adulting />
<hr />
</section>
<section className={style.work}>
<h3>Work Experiences</h3>
<p>
This is not meant to be a resumé but rather a glimse into my experiences and some of my takeaways. My hope is that in sharing this you will feel like you know me. Some of my lessons are negative in nature, so I might withhold some company names. My intention is to share what I've learned, not malign former employers. I am thankful for all these opportunities.
</p>
<Startup />
<hr />
<Photographer />
<hr />
<Retail />
<hr />
<Banker />
<hr />
<Processor />
<hr />
<Dicing />
<hr />
<Tech />
<hr />
<Driver />
<hr />
</section>
<section className={style.education}>
<h3>Education</h3>
<p>
I want to be upfront regarding my college education... I spent several years in college but left <em>twice</em> without earning a Bachelor's degree.
</p>
<College1 />
<hr />
<Overpriced />
<hr />
<College2 />
<hr />
<DevEd />
<hr />
</section>
<section className={style.fun}>
<h3>For Fun</h3>
<p>
I think I might like the outdoors <span role="img" aria-label="emoji">🏕️ </span><span role="img" aria-label="emoji">🌳 </span><span role="img" aria-label="emoji">⛰️ </span><span role="img" aria-label="emoji">🎣</span>
</p>
<Hiking />
<hr />
<Camping />
<hr />
<Fishing />
<hr />
<RockHounding />
<hr />
<Traveling />
<hr />
</section>
</div>
);
export default About;
<file_sep>/src/components/Fishing/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Fishing extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.banker__header}
title="Open for details"
>
Fishing <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
Again, this goes back to my childhood and now Kelly and our boys are also <em>hooked</em> on fishing. We aren't hardcore anglers. When visiting my parents, we generally enjoy taking a couple boats out on a calm lake to bobber fish for bluegills. Our favorite lake is hidden gem called Little Turkey in northeast Indiana.
</p>
</ToggleDisplay>
</div>
)
}
}
export default Fishing<file_sep>/src/components/Header/index.jsx
import React from 'react';
import Link from 'gatsby-link';
import { NavLink } from 'react-router-dom';
import ToggleDisplay from 'react-toggle-display';
import classNames from 'classnames/bind';
import style from './index.module.scss';
import logo from '../../assets/logo/website-logo.png';
import hamburger from '../../assets/icons/hamburger.png';
class Header extends React.Component {
constructor() {
super();
this.state = { show: false };
}
handleClick() {
this.setState({ show: !this.state.show });
}
closeMenu() {
this.setState({ show: false });
}
render() {
return (
<div className={style.navigation}>
<div>
<Link
to="/"
className={style.title__link}
onClick={() => this.closeMenu()}
>
<img src={logo} alt="<NAME> logo" className={style.title} />
</Link>
<h4 className={style.byline}>{this.props.byline}</h4>
</div>
<nav className={style.menu}>
<nav className={style.mobile}>
<button
onClick={() => this.handleClick()}
className={style.mobile__button}
>
<ToggleDisplay if={this.state.show} className={style.mobile__close}>
×
</ToggleDisplay>
<ToggleDisplay if={!this.state.show}>
<img src={hamburger} className={style.hamburger} />
</ToggleDisplay>
</button>
</nav>
{/* DESKTOP NAVIGATION */}
<NavLink
to="/webdev/"
className={style.menu__item}
activeClassName={style.menu__active}
>
WebDev
</NavLink>
<NavLink
to="/blog/"
className={style.menu__item}
activeClassName={style.menu__active}
>
Blog
</NavLink>
<NavLink
to="/about/"
className={style.menu__item}
activeClassName={style.menu__active}
>
About
</NavLink>
<NavLink
to="/photography/"
className={style.menu__item}
activeClassName={style.menu__active}
>
Photography
</NavLink>
</nav>
{/* MOBILE MENU ITEMS */}
<ToggleDisplay show={this.state.show} className={style.mobile__items}>
<NavLink
to="/webdev/"
className={style.mobile__item}
activeClassName={style.menu__active}
onClick={() => this.closeMenu()}
>
WebDev
</NavLink>
<NavLink
to="/blog/"
className={style.mobile__item}
activeClassName={style.menu__active}
onClick={() => this.closeMenu()}
>
Blog
</NavLink>
<NavLink
to="/about/"
className={style.mobile__item}
activeClassName={style.menu__active}
onClick={() => this.closeMenu()}
>
About
</NavLink>
<NavLink
to="/photography/"
className={style.mobile__item}
activeClassName={style.menu__active}
onClick={() => this.closeMenu()}
>
Photography
</NavLink>
</ToggleDisplay>
</div>
);
}
}
export default Header;
<file_sep>/README.md
# My Official Website - Style Updated
### A [GatsbyJS](https://www.gatsbyjs.org/) website powered by [Contentful](https://contentful.com)
My website and blog were built with Gatsby and ReactJS.
Contentful powers the blog.
It is hosted on Netlify.
<file_sep>/src/components/Traveling/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Traveling extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.banker__header}
title="Open for details"
>
Traveling <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
I've had a few traveling goals since I was younger:
</p>
<ol>
<li>Visit all 50 U.S. states</li>
<li>Visit all 7 continents</li>
</ol>
<p>
So far I've been to 43 states but I'm a little behind schedule on the continents. I've only been to North American, Asia, and Europe. My favorite cities visited so far (in no particular order):
</p>
<ul>
<li>Seoul, South Korea</li>
<li>Paris, France</li>
<li>London, England</li>
<li>Bangkok, Thailand</li>
<li>Singapore</li>
<li>Dubai, United Arab Emirates</li>
<li>San Diego, CA, USA</li>
<li>Chicago, IL, USA</li>
</ul>
</ToggleDisplay>
</div>
)
}
}
export default Traveling<file_sep>/src/pages/index.jsx
import React from 'react';
import Link from 'gatsby-link';
import 'typeface-raleway';
import 'typeface-titillium-web';
import style from '../styles/index.module.scss';
import HTML from '../assets/icons/html-logo.png';
import CSS from '../assets/icons/css-logo.png';
import ReactLogo from '../assets/icons/react-logo.png';
import ES6 from '../assets/icons/es6-logo.png';
import GraphQLLogo from '../assets/icons/graphql-logo.png';
import Gatsby from '../assets/icons/gatsby-logo.png';
const IndexPage = ({ data }) => (
<div className={style.body}>
<section className={style.intro}>
<h1>React Frontend Developer</h1>
<p>
I am activily seeking a junior/entry level React Frontend Developer position in the Phoenix, Arizona, USA area.
</p>
</section>
{/* FRONTEND */}
<section className={style.frontend}>
<h3>Modern Frontend Technology</h3>
<p>Since June 2017 I have been a full-time frontend web development student focusing on modern build tools.</p>
<section className={style.frontend__logos}>
<img src={ReactLogo} alt="React logo" className={style.frontend__logo} />
<img src={ES6} alt="ES6 logo" className={style.frontend__logo} />
<img src={HTML} alt="HTML logo" className={style.frontend__logo} />
<img src={CSS} alt="CSS logo" className={style.frontend__logo} />
<img src={GraphQLLogo} alt="GraphQL logo" className={style.frontend__logo} />
<img src={Gatsby} alt="Gatsby logo" className={style.frontend__logo} />
</section>
<p>Checkout the <Link to="/webdev/" className={style.link}>WebDev</Link> page to see my experience and projects.</p>
</section>
{/* PHOTOGRAPHY */}
<section className={style.photography}>
<h3>Professional Photography</h3>
<p>What began as a hobby grew into much more when people began to notice my work. Even though professional photography is a part-time side gig, I am thankful to have a creative outlet.</p>
<section className={style.photography__images}>
<img src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517768591/creative2_rowt9l.jpg`} alt="Fish pier at night" className={style.photography__image} />
<img src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517768592/creative3_khq0ii.jpg`} alt="Black and white spiral stairway" className={style.photography__image} />
<img src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517768592/creative1_kxw9bv.jpg`} alt="Purple V shaped structure at night" className={style.photography__image} />
</section>
<section className={style.photography__linkButton}>
<Link className={style.photography__link} to="/photography/">
<button className={style.photography__button}>See More →</button>
</Link>
</section>
</section>
{/* BLOG */}
<section className={style.blog}>
<hr className={style.blog__hr} />
<h3>Recent Blog Posts</h3>
{data.allContentfulBlogPost.edges.map(post => (
<div key={post.node.id} className={style.blog__post}>
<p className={style.blog__date}>{post.node.date}</p>
<Link
key={post.node.id}
to={`/blog/${post.node.slug}`}
className={style.blog__link}
>
<h4 className={style.blog__title}>{post.node.title}</h4>
</Link>
<img src={post.node.heroImage.file.url} alt={post.node.title} className={style.blog__image} />
</div>
))}
</section>
</div>
);
export default IndexPage;
export const lastThreePosts = graphql`
query LastThree {
allContentfulBlogPost(
sort: {fields: [date], order: DESC}
limit: 3
) {
edges {
node {
id
title
slug
date(formatString: "MMM DD, YYYY")
heroImage {
id
file {
url
}
}
}
}
}
}
`;
<file_sep>/gatsby-config.js
require('dotenv').config({ path: './.env.development' })
const autoprefixer = require('autoprefixer')
module.exports = {
siteMetadata: {
title: 'Michael Manges',
byline: 'The Decrepit Webdev',
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-plugin-postcss-sass`,
options: {
postCssPlugins: [autoprefixer()],
precision: 8,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `src`,
path: `${__dirname}/src/`,
},
},
{
resolve: `gatsby-plugin-svgr`,
options: {
dir: `./src/assets/svg`,
icon: true,
viewBox: false,
},
},
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.GATSBY_CONTENTFUL_SPACEID,
accessToken: process.env.GATSBY_CONTENTFUL_ACCESS_TOKEN,
},
},
],
};
<file_sep>/src/components/Footer/index.jsx
import React from 'react'
import Link from 'gatsby-link'
import style from './index.module.scss'
import Gatsby from '../../assets/icons/gatsby-logo.png'
import Netlify from '../../assets/icons/netlify-logo.png'
import Contentful from '../../assets/icons/contentful-logo.png'
const Footer = () => (
<div className={style.footer}>
<p className={style.power}>Powered by</p>
<div className={style.logos}>
<a href="https://gatsbyjs.org" target="_blank">
<img
src={Gatsby}
alt="GatsbyJS logo"
title="Gatsby"
/>
</a>
<a href="https://netlify.com" target="_blank">
<img
src={Netlify}
alt="Netlify logo"
title="Netlify"
/>
</a>
<a href="https://contentful.com" target="_blank">
<img
src={Contentful}
alt="Contentful logo"
title="Contentful CMS"
/>
</a>
</div>
<p className={style.copyright}>Copyright © 2018 <NAME></p>
</div>
)
export default Footer
<file_sep>/src/components/Project/index.jsx
import React from 'react'
import style from './index.module.scss'
const Project = (props) => (
<section className={style.project}>
<h3 className={style.name}>
<a href={props.url} target="_blank" className={style.name__link}>{props.name}</a>
<hr/>
</h3>
<div className={style.logos}>
{props.logos.map(logo => (
<div>
<img src={logo} alt="logo" className={style.logo} />
</div>
))}
</div>
<p className={style.desc}>{props.desc}</p>
</section>
)
export default Project<file_sep>/src/components/Hiking/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Hiking extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.banker__header}
title="Open for details"
>
Hiking <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
One of the reasons I moved to Arizona from the midwest was the climate. I love to be outdoors and hiking a mountain trail might be one of my all time favorite activites. My wife and I really got to know each other while hiking. It's great exercise and it takes me away from the stress of life. My favorite trail is the Echo Canyon Trailhead on Camelback Mountain in Phoenix, Arizona.
</p>
</ToggleDisplay>
</div>
)
}
}
export default Hiking<file_sep>/src/components/Processor/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class Processor extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.processor__header}
title="Open for details"
>
University Financial Aid Processor <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
This is a difficult job to discuss because my biggest takeaways are negative and cynical. One positive was my co-workers. I really enjoyed the people I worked with.
</p>
<p>
I held two positions at this private <em>for-profit</em> university. At the time, we were pushing the boundries of online education and most of our students were spread across the U.S. I started as a financial aid advisor connecting with students over the phone. After a short period of time, I was promoted to financial aid processor. I processed all the FAFSA financial aid including processing and dispersing federal and private student loans. I was also a liaison between the university financial aid office and the accounting office.
</p>
<p><strong>What I Learned</strong></p>
<ul>
<li>For-profit and education should NOT mix. It's impossible to hold students to a high standard when they are viewed as customers.</li>
<li>Crap work in large quantities gets rewarded.</li>
<li>The people who find that crap work and fix it are not rewarded. Their numbers are too low.</li>
<li>Companies often say one thing but mean another.</li>
<li>Cubicles suck.</li>
<li>Most people in a certain region of the U.S. do not say 'goodbye' when a phone conversation is over. They just hang up. It's nothing personal--that's just how they roll.</li>
</ul>
</ToggleDisplay>
</div>
)
}
}
export default Processor<file_sep>/src/components/ArtisticImages/index.jsx
import React from 'react';
import style from './index.module.scss';
const ArtisticImages = () => (
<div className={style.images}>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/creative4_jgy5r2.jpg`}
alt="Abu Dhabi Grand Mosque arches"
className={style.images__artistic}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/creative9_y1kzbx`}
alt="Light trails on Dubai round-a-bout"
className={style.images__artistic}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/creative8_zqot0r`}
alt="Overcast morning on Glorietta Bay San Diego"
className={style.images__artistic}
/>
<img
src={`https://res.cloudinary.com/${process.env.GATSBY_CLOUD_NAME}/image/upload/q_auto:best/v1517811454/mysite/creative6_nbnqzc`}
alt="Emirates Palace Hotel fountains"
className={style.images__artistic}
/>
</div>
);
export default ArtisticImages
;<file_sep>/src/components/College2/index.jsx
import React from 'react'
import style from './index.module.scss'
import ToggleDisplay from 'react-toggle-display'
class College2 extends React.Component {
constructor() {
super()
this.state = { show: false }
}
handleClick() {
this.setState({ show: !this.state.show })
}
render() {
return (
<div>
<h4
onClick={ () => this.handleClick() }
className={style.banker__header}
title="Open for details"
>
College Round Two <ToggleDisplay
if={!this.state.show}
className={style.plus}>+</ToggleDisplay>
<ToggleDisplay
if={this.state.show}
className={style.plus}>-</ToggleDisplay>
</h4>
<ToggleDisplay show={this.state.show}>
<p>
Shortly after Kelly and I married, I enrolled in the computer science program at Arizona State University. Looking back I realize that enrolling in CS was probably a mistake. I literally knew nothing about programming. My introduction to programming was Java and it kicked my butt. This was frustrating because I was told Java was a great first language since it's so easy to learn. It was not easy for me. I was able to keep up for the first half of the semester but after that, no matter how hard I tried, it was moving too fast. I was lost and I assumed I just didn't have what it took to be a developer. More than a decade passed before I gave coding another chance.
</p>
<p>
At this point, I just wanted a degree and with my previous physical therapy credits, biology seemed to be the path of least resistance. So after a semester of CS, I changed my major to biology. During this time, Kelly became pregnant with our first child. The timeline would be tough but we thought after he came Kelly would teach one more year and I would be dad by day and full-time student by night. Our son had other ideas.
</p>
<p><strong>Life Happens</strong></p>
<p>
While she was on summer break, Kelly went into preterm labor. Less than 24 hours later, we were parents to a very little boy who was now in the Neonatal Intensive Care Unit. We were scared. I withdrew from my summer class to be with Kelly and our son.
</p>
<p>
Our son came home with a mostly clean bill of health after spending his first 20 days on earth in the hospital. Today he is healthy and you would never know by looking at him that he had a rough start. But the experience shook Kelly and me. She wanted to be done as a teacher so she could be full-time Mom. While teachers don't make a ton of money, she had been teaching for 14 years and we were used to her salary.
</p>
<p>
I found an entry level management job with a company that rewarded hard work and results. If I agreed to work the overnight shift, it meant a higher hourly rate and monthly bonuses. It also meant working almost 50 hours a week. I tried to continue with school while being a new dad and working nights but it was proving to be too much. I withdrew from my classes.
</p>
<p><strong>I Would Like to Finish My Degree But...</strong></p>
<p>
It's been several years since I left school. In that time, I am blown away by the rise in tuition rates. Even though I would love to return to school, I feel like I have been priced out of the market. As of this writing, undergraduate <em>online</em> classes at Arizona State University cost between $510 - $718 per credit hour. Is it any wonder why so many graduates are swimming in student loan debt?
</p>
</ToggleDisplay>
</div>
)
}
}
export default College2 | 08506e608ed5fe8e3ee0c1d1af4728ef4962e326 | [
"JavaScript",
"Markdown"
]
| 28 | JavaScript | mkmanges/my-gatsby-website | 82a4e0d47d91af2a8aa73931726a21177414a973 | ebff734dc8e8d0f38806361507ee7dcd843fd7e2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.